diff --git a/.travis.yml b/.travis.yml index 0292d381cdd..1ea0a30844e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +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. + language: java +dist: trusty jdk: - openjdk7 - oraclejdk8 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c5450ce3cd4..703c5fa05b5 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..2bc42bea379 --- /dev/null +++ b/Jenkinsfile-asf @@ -0,0 +1,78 @@ +#!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' + } + axis { + name 'SERVER_VERSION' + values '2.1', '3.0', '3.11', '4.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() { + sh """ + container_id=\$(docker run -td -e TEST_JAVA_VERSION=${TEST_JAVA_VERSION} -e SERVER_VERSION=${SERVER_VERSION} -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-datastax b/Jenkinsfile-datastax new file mode 100644 index 00000000000..9e7b92bed4f --- /dev/null +++ b/Jenkinsfile-datastax @@ -0,0 +1,569 @@ +#!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 3.x' + 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 1.x' + 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.2.5" + env.PATH = "${env.MAVEN_HOME}/bin:${env.PATH}" + env.JAVA_HOME = sh(label: 'Get JAVA_HOME',script: '''#!/bin/bash -le + . ${JABBA_SHELL} + jabba which ${JABBA_VERSION}''', returnStdout: true).trim() + env.JAVA8_HOME = sh(label: 'Get JAVA8_HOME',script: '''#!/bin/bash -le + . ${JABBA_SHELL} + jabba which 1.8''', returnStdout: true).trim() + + sh label: 'Download Apache CassandraⓇ',script: '''#!/bin/bash -le + . ${JABBA_SHELL} + jabba use ${JABBA_VERSION} + . ${CCM_ENVIRONMENT_SHELL} ${SERVER_VERSION} + ''' + + sh label: 'Display Java and environment information',script: '''#!/bin/bash -le + # Load CCM environment variables + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + . ${JABBA_SHELL} + jabba use ${JABBA_VERSION} + + java -version + mvn -v + printenv | sort + ''' +} + +def buildDriver(jabbaVersion) { + def buildDriverScript = '''#!/bin/bash -le + + . ${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 + # Load CCM environment variables + set -o allexport + . ${HOME}/environment.txt + set +o allexport + + . ${JABBA_SHELL} + jabba use ${JABBA_VERSION} + + printenv | sort + + mvn -B -V verify \ + -fail-never -P${TEST_PROFILE} \ + -Dcom.datastax.driver.TEST_BASE_NODE_WAIT=120 \ + -Dcom.datastax.driver.NEW_NODE_DELAY_SECONDS=100 \ + -Dcassandra.version=${CCM_CASSANDRA_VERSION} \ + -Ddse=${CCM_IS_DSE} \ + -Dccm.java.home=${CCM_JAVA_HOME} \ + -Dccm.path=${CCM_JAVA_HOME}/bin \ + -Dccm.maxNumberOfNodes=3 \ + -DfailIfNoTests=false \ + -Dmaven.test.failure.ignore=true \ + -Dmaven.javadoc.skip=true \ + -Dproxy.path=${HOME}/proxy + + # run isolated tests + mvn -B -V verify \ + -fail-never -Pisolated \ + -Dcom.datastax.driver.TEST_BASE_NODE_WAIT=120 \ + -Dcom.datastax.driver.NEW_NODE_DELAY_SECONDS=100 \ + -Dcassandra.version=${CCM_CASSANDRA_VERSION} \ + -Ddse=${CCM_IS_DSE} \ + -Dccm.java.home=${CCM_JAVA_HOME} \ + -Dccm.path=${CCM_JAVA_HOME}/bin \ + -Dccm.maxNumberOfNodes=3 \ + -DfailIfNoTests=false \ + -Dmaven.test.failure.ignore=true \ + -Dmaven.javadoc.skip=true + ''' +} + +def executeCodeCoverage() { + jacoco( + execPattern: '**/target/jacoco.exec', + classPattern: '**/classes', + sourcePattern: '**/src/main/java' + ) +} + +def notifySlack(status = 'started') { + // Notify Slack channel for every build except adhoc executions + if (params.ADHOC_BUILD_TYPE != 'BUILD-AND-EXECUTE-TESTS') { + // Set the global pipeline scoped environment (this is above each matrix) + env.BUILD_STATED_SLACK_NOTIFIED = 'true' + + def buildType = 'Commit' + if (params.CI_SCHEDULE != 'DO-NOT-CHANGE-THIS-SELECTION') { + buildType = "${params.CI_SCHEDULE.toLowerCase().capitalize()}" + } + + def color = 'good' // Green + if (status.equalsIgnoreCase('aborted')) { + color = '808080' // Grey + } else if (status.equalsIgnoreCase('unstable')) { + color = 'warning' // Orange + } else if (status.equalsIgnoreCase('failed')) { + color = 'danger' // Red + } + + def message = """Build ${status} for ${env.DRIVER_DISPLAY_NAME} [${buildType}] +<${env.GITHUB_BRANCH_URL}|${env.BRANCH_NAME}> - <${env.RUN_DISPLAY_URL}|#${env.BUILD_NUMBER}> - <${env.GITHUB_COMMIT_URL}|${env.GIT_SHA}>""" + if (!status.equalsIgnoreCase('Started')) { + message += """ +${status} after ${currentBuild.durationString - ' and counting'}""" + } + + slackSend color: "${color}", + channel: "#java-driver-dev-bots", + message: "${message}" + } +} + +def describePerCommitStage() { + script { + currentBuild.displayName = "Per-Commit build" + currentBuild.description = 'Per-Commit build and testing of development Apache CassandraⓇ against Oracle JDK 8' + } +} + +def describeAdhocAndScheduledTestingStage() { + script { + if (params.CI_SCHEDULE == 'DO-NOT-CHANGE-THIS-SELECTION') { + // Ad-hoc build + currentBuild.displayName = "Adhoc testing" + currentBuild.description = "Testing ${params.ADHOC_BUILD_AND_EXECUTE_TESTS_SERVER_VERSION} against JDK version ${params.ADHOC_BUILD_AND_EXECUTE_TESTS_JABBA_VERSION}" + } else { + // Scheduled build + currentBuild.displayName = "${params.CI_SCHEDULE.toLowerCase().replaceAll('_', ' ').capitalize()} schedule" + currentBuild.description = "Testing server versions [${params.CI_SCHEDULE_SERVER_VERSIONS}] against JDK version ${params.CI_SCHEDULE_JABBA_VERSION}" + } + } +} + +// branch pattern for cron +// should match 3.x, 4.x, 4.5.x, etc +def branchPatternCron() { + ~"((\\d+(\\.[\\dx]+)+))" +} + +pipeline { + agent none + + // Global pipeline timeout + options { + timeout(time: 10, unit: 'HOURS') + buildDiscarder(logRotator(artifactNumToKeepStr: '10', // Keep only the last 10 artifacts + numToKeepStr: '50')) // Keep only the last 50 build records + } + + parameters { + choice( + name: 'ADHOC_BUILD_TYPE', + choices: ['BUILD', 'BUILD-AND-EXECUTE-TESTS'], + description: '''

Perform a adhoc build operation

+ + + + + + + + + + + + + + + +
ChoiceDescription
BUILDPerforms a Per-Commit build
BUILD-AND-EXECUTE-TESTSPerforms a build and executes the integration and unit tests
''') + 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-5.1', // Legacy DataStax Enterprise + 'dse-6.0', // Previous DataStax Enterprise + 'dse-6.7', // Previous DataStax Enterprise + 'dse-6.8.0', // Current DataStax Enterprise + 'ALL'], + description: '''Apache Cassandra® or DataStax Enterprise server version to use for adhoc BUILD-AND-EXECUTE-TESTS builds + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ChoiceDescription
2.1Apache Cassandra® v2.1.x
2.2Apache Cassandra® v2.2.x
3.0Apache Cassandra® v3.0.x
3.11Apache Cassandra® v3.11.x
4.0Apache Cassandra® v4.x (CURRENTLY UNDER DEVELOPMENT)
dse-5.1DataStax Enterprise v5.1.x
dse-6.0DataStax Enterprise v6.0.x
dse-6.7DataStax Enterprise v6.7.x
dse-6.8.0DataStax Enterprise v6.8.0
''') + choice( + name: 'ADHOC_BUILD_AND_EXECUTE_TESTS_JABBA_VERSION', + choices: ['zulu@1.6', // Zulu JDK 1.6 + 'zulu@1.7', // Zulu JDK 1.7 + '1.8', // Oracle JDK version 1.8 (current default) + 'openjdk@1.11'], // OpenJDK version 11 + description: '''JDK version to use for TESTING when running adhoc BUILD-AND-EXECUTE-TESTS builds. All builds will use JDK8 for building the driver + + + + + + + + + + + + + + + + + + + + + + + +
ChoiceDescription
zulu@1.6Zulu JDK version 1.6
zulu@1.7Zulu JDK version 1.7
1.8Oracle JDK version 1.8 (Used for compiling regardless of choice)
openjdk@1.11OpenJDK version 11
''') + choice( + name: 'ADHOC_BUILD_AND_EXECUTE_TESTS_TEST_PROFILE', + choices: ['short', 'long'], + description: 'Test profile to execute during test phase of the build') + choice( + name: 'CI_SCHEDULE', + choices: ['DO-NOT-CHANGE-THIS-SELECTION', 'WEEKNIGHTS', 'WEEKENDS', 'MONTHLY'], + description: 'CI testing schedule to execute periodically scheduled builds and tests of the driver (DO NOT CHANGE THIS SELECTION)') + string( + name: 'CI_SCHEDULE_SERVER_VERSIONS', + defaultValue: 'DO-NOT-CHANGE-THIS-SELECTION', + description: 'CI testing server version(s) to utilize for scheduled test runs of the driver (DO NOT CHANGE THIS SELECTION)') + string( + name: 'CI_SCHEDULE_JABBA_VERSION', + defaultValue: 'DO-NOT-CHANGE-THIS-SELECTION', + description: 'CI testing JDK version(s) to utilize for scheduled test runs of the driver (DO NOT CHANGE THIS SELECTION)') + string( + name: 'CI_SCHEDULE_TEST_PROFILE', + defaultValue: 'DO-NOT-CHANGE-THIS-SELECTION', + description: 'CI testing profile to execute (DO NOT CHANGE THIS SELECTION)') + } + + 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 3:00 AM + ### JDK8 tests against 2.1, 3.0, 3.11 and 4.0 + H 3 * * 1-5 %CI_SCHEDULE=WEEKNIGHTS;CI_SCHEDULE_SERVER_VERSIONS=2.1 3.0 3.11 4.0;CI_SCHEDULE_JABBA_VERSION=1.8;CI_SCHEDULE_TEST_PROFILE=long + # Every weekend (Sunday) around 2:00 PM + ### JDK11 tests against 2.1, 3.0, 3.11 and 4.0 + H 14 * * 0 %CI_SCHEDULE=WEEKENDS;CI_SCHEDULE_SERVER_VERSIONS=2.1 3.0 3.11 4.0;CI_SCHEDULE_JABBA_VERSION=openjdk@1.11;CI_SCHEDULE_TEST_PROFILE=long + """ : "") + } + + environment { + OS_VERSION = 'ubuntu/jammy64/java-driver' + JABBA_SHELL = '/usr/lib/jabba/jabba.sh' + CCM_ENVIRONMENT_SHELL = '/usr/local/bin/ccm_environment.sh' + } + + stages { + stage ('Per-Commit') { + options { + timeout(time: 2, unit: 'HOURS') + } + when { + beforeAgent true + allOf { + expression { params.ADHOC_BUILD_TYPE == 'BUILD' } + expression { params.CI_SCHEDULE == 'DO-NOT-CHANGE-THIS-SELECTION' } + expression { params.CI_SCHEDULE_SERVER_VERSIONS == 'DO-NOT-CHANGE-THIS-SELECTION' } + expression { params.CI_SCHEDULE_JABBA_VERSION == 'DO-NOT-CHANGE-THIS-SELECTION' } + expression { params.CI_SCHEDULE_TEST_PROFILE == 'DO-NOT-CHANGE-THIS-SELECTION' } + not { buildingTag() } + } + } + + matrix { + axes { + axis { + name 'SERVER_VERSION' + values '3.11', // Current Apache CassandraⓇ + '4.0' // Development Apache CassandraⓇ + } + } + + agent { + label "${OS_VERSION}" + } + environment { + // Per-commit builds are only going to run against JDK8 + JABBA_VERSION = '1.8' + TEST_PROFILE = 'short' + } + + stages { + stage('Initialize-Environment') { + steps { + initializeEnvironment() + script { + if (env.BUILD_STATED_SLACK_NOTIFIED != 'true') { + notifySlack() + } + } + } + } + stage('Describe-Build') { + steps { + describePerCommitStage() + } + } + stage('Build-Driver') { + steps { + buildDriver('1.8') + } + } + stage('Execute-Tests') { + steps { + catchError { + // Use the matrix JDK for testing + executeTests() + } + } + post { + always { + /* + * Empty results are possible + * + * - Build failures during mvn verify may exist so report may not be available + */ + junit testResults: '**/target/surefire-reports/TEST-*.xml', allowEmptyResults: true + junit testResults: '**/target/failsafe-reports/TEST-*.xml', allowEmptyResults: true + } + } + } + stage('Execute-Code-Coverage') { + // Ensure the code coverage is run only once per-commit + when { environment name: 'SERVER_VERSION', value: '4.0' } + steps { + executeCodeCoverage() + } + } + } + } + post { + aborted { + notifySlack('aborted') + } + success { + notifySlack('completed') + } + unstable { + notifySlack('unstable') + } + failure { + notifySlack('FAILED') + } + } + } + + stage('Adhoc-And-Scheduled-Testing') { + when { + beforeAgent true + allOf { + expression { (params.ADHOC_BUILD_TYPE == 'BUILD' && params.CI_SCHEDULE != 'DO-NOT-CHANGE-THIS-SELECTION') || + params.ADHOC_BUILD_TYPE == 'BUILD-AND-EXECUTE-TESTS' } + not { buildingTag() } + anyOf { + expression { params.ADHOC_BUILD_TYPE == 'BUILD-AND-EXECUTE-TESTS' } + allOf { + expression { params.ADHOC_BUILD_TYPE == 'BUILD' } + expression { params.CI_SCHEDULE != 'DO-NOT-CHANGE-THIS-SELECTION' } + expression { params.CI_SCHEDULE_SERVER_VERSIONS != 'DO-NOT-CHANGE-THIS-SELECTION' } + } + } + } + } + + environment { + SERVER_VERSIONS = "${params.CI_SCHEDULE_SERVER_VERSIONS == 'DO-NOT-CHANGE-THIS-SELECTION' ? params.ADHOC_BUILD_AND_EXECUTE_TESTS_SERVER_VERSION : params.CI_SCHEDULE_SERVER_VERSIONS}" + JABBA_VERSION = "${params.CI_SCHEDULE_JABBA_VERSION == 'DO-NOT-CHANGE-THIS-SELECTION' ? params.ADHOC_BUILD_AND_EXECUTE_TESTS_JABBA_VERSION : params.CI_SCHEDULE_JABBA_VERSION}" + TEST_PROFILE = "${params.CI_SCHEDULE_TEST_PROFILE == 'DO-NOT-CHANGE-THIS-SELECTION' ? params.ADHOC_BUILD_AND_EXECUTE_TESTS_TEST_PROFILE : params.CI_SCHEDULE_TEST_PROFILE}" + } + + matrix { + 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-5.1', // Legacy DataStax Enterprise + 'dse-6.0', // Previous DataStax Enterprise + 'dse-6.7', // Previous DataStax Enterprise + 'dse-6.8.0' // Current DataStax Enterprise + } + } + when { + beforeAgent true + allOf { + expression { return env.SERVER_VERSIONS.split(' ').any { it =~ /(ALL|${env.SERVER_VERSION})/ } } + } + } + agent { + label "${env.OS_VERSION}" + } + + stages { + stage('Initialize-Environment') { + steps { + initializeEnvironment() + script { + if (env.BUILD_STATED_SLACK_NOTIFIED != 'true') { + notifySlack() + } + } + } + } + stage('Describe-Build') { + steps { + describeAdhocAndScheduledTestingStage() + } + } + stage('Build-Driver') { + steps { + // Jabba default should be a JDK8 for now + buildDriver('1.8') + } + } + stage('Execute-Tests') { + steps { + catchError { + // Use the matrix JDK for testing + executeTests() + } + } + post { + always { + /* + * Empty results are possible + * + * - Build failures during mvn verify may exist so report may not be available + * - With boolean parameters to skip tests a failsafe report may not be available + */ + junit testResults: '**/target/surefire-reports/TEST-*.xml', allowEmptyResults: true + junit testResults: '**/target/failsafe-reports/TEST-*.xml', allowEmptyResults: true + } + } + } + stage('Execute-Code-Coverage') { + // Ensure the code coverage is run only once per-commit + when { + allOf { + environment name: 'SERVER_VERSION', value: '4.0' + environment name: 'JABBA_VERSION', value: '1.8' + } + } + steps { + executeCodeCoverage() + } + } + } + } + post { + aborted { + notifySlack('aborted') + } + success { + notifySlack('completed') + } + unstable { + notifySlack('unstable') + } + failure { + notifySlack('FAILED') + } + } + } + } +} diff --git a/LICENSE b/LICENSE index d6456956733..38f06999ef6 100644 --- a/LICENSE +++ b/LICENSE @@ -200,3 +200,10 @@ 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: + +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 driver-core/src/main/java/com/datastax/driver/core/VIntCoding.java diff --git a/LICENSE_binary b/LICENSE_binary new file mode 100644 index 00000000000..5232779c907 --- /dev/null +++ b/LICENSE_binary @@ -0,0 +1,229 @@ + + 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: + +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 driver-core/src/main/java/com/datastax/driver/core/VIntCoding.java + +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 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..c60d8ceb245 --- /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/jpountz/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 efb3a113cad..a56816e0767 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,20 @@ -# Datastax Java Driver for Apache Cassandra® +# Java Driver for Apache Cassandra® -[![Build Status](https://travis-ci.org/datastax/java-driver.svg?branch=3.x)](https://travis-ci.org/datastax/java-driver) +:warning: The java-driver has recently been donated by Datastax to The Apache Software Foundation and the Apache Cassandra project. Bear with us as we move assets and coordinates. + +[![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/cassandra-driver-core/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.apache.cassandra/cassandra-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 the latest -version through the [Java driver -docs](http://docs.datastax.com/en/developer/java-driver/latest/index.html) or via the release tags, -[e.g. -3.6.0](https://github.com/datastax/java-driver/tree/3.6.0).* - -_**Feeback requested!** Help us focus our efforts, provide your input on -the [Platform and Runtime Survey](http://goo.gl/forms/qwUE6qnL7U) (we kept it short)._ +version through the [Java Driver +docs](http://docs.datastax.com/en/developer/java-driver/3.11/index.html) or via the release tags, +[e.g. 3.12.1](https://github.com/apache/cassandra-java-driver/tree/3.12.1).* A modern, [feature-rich](manual/) and highly tunable Java client library for Apache Cassandra (2.1+) and using exclusively Cassandra's binary protocol -and Cassandra Query Language v3. _Use the [DataStax Enterprise Java driver][dse-driver] +and Cassandra Query Language v3. _Use the [DataStax Enterprise Java Driver][dse-driver] for better compatibility and support for DataStax Enterprise._ **Features:** @@ -41,38 +40,32 @@ The driver contains the following modules: - driver-core: the core layer. - driver-mapping: the object mapper. -- driver-extras: optional features for the Java driver. +- driver-extras: optional features for the Java Driver. - driver-examples: example applications using the other modules which are only meant for demonstration purposes. - driver-tests: tests for the java-driver. **Useful links:** -- JIRA (bug tracking): https://datastax-oss.atlassian.net/browse/JAVA -- MAILING LIST: https://groups.google.com/a/lists.datastax.com/forum/#!forum/java-driver-user -- DATASTAX ACADEMY SLACK: #datastax-drivers on https://academy.datastax.com/slack -- TWITTER: [@dsJavaDriver](https://twitter.com/dsJavaDriver) tweets Java - driver releases and important announcements (low frequency). - [@DataStaxEng](https://twitter.com/datastaxeng) has more news including - other drivers, Cassandra, and DSE. -- DOCS: the [manual](http://docs.datastax.com/en/developer/java-driver/3.5/manual/) has quick +- JIRA (bug tracking): https://issues.apache.org/jira/projects/CASSJAVA +- MAILING LIST: https://cassandra.apache.org/_/community.html#discussions +- DOCS: the [manual](http://docs.datastax.com/en/developer/java-driver/3.11/manual/) has quick start material and technical details about the driver and its features. -- API: http://www.datastax.com/drivers/java/3.5 -- GITHUB REPOSITORY: https://github.com/datastax/java-driver +- API: https://docs.datastax.com/en/drivers/java/3.11 +- GITHUB REPOSITORY: https://github.com/apache/cassandra-java-driver - [changelog](changelog/) -- [binary tarball](http://downloads.datastax.com/java-driver/cassandra-java-driver-3.6.0.tar.gz) ## Getting the driver The last release of the driver is available on Maven Central. You can install it in your application using the following Maven dependency (_if -using DataStax Enterprise, install the [DataStax Enterprise Java driver][dse-driver] instead_): +using DataStax Enterprise, install the [DataStax Enterprise Java Driver][dse-driver] instead_): ```xml - com.datastax.cassandra + org.apache.cassandra cassandra-driver-core - 3.6.0 + 3.12.1 ``` @@ -80,9 +73,9 @@ Note that the object mapper is published as a separate artifact: ```xml - com.datastax.cassandra + org.apache.cassandra cassandra-driver-mapping - 3.6.0 + 3.12.1 ``` @@ -90,9 +83,9 @@ The 'extras' module is also published as a separate artifact: ```xml - com.datastax.cassandra + org.apache.cassandra cassandra-driver-extras - 3.6.0 + 3.12.1 ``` @@ -101,53 +94,37 @@ We also provide a [shaded JAR](manual/shaded_jar/) to avoid the explicit dependency to Netty. If you can't use a dependency management tool, a -[binary tarball](http://downloads.datastax.com/java-driver/cassandra-java-driver-3.6.0.tar.gz) +[binary tarball](https://cassandra.apache.org/_/download.html) is available for download. ## Compatibility -The Java client driver 3.6.0 ([branch 3.x](https://github.com/datastax/java-driver/tree/3.x)) is compatible with Apache -Cassandra 2.1, 2.2 and 3.0+ (see [this page](http://docs.datastax.com/en/developer/java-driver/latest/manual/native_protocol/) for +The Java client driver 3.12.1 ([branch 3.x](https://github.com/apache/cassandra-java-driver/tree/3.x)) is compatible with Apache +Cassandra 2.1, 2.2 and 3.0+ (see [this page](http://docs.datastax.com/en/developer/java-driver/3.11/manual/native_protocol/) for the most up-to-date compatibility information). UDT and tuple support is available only when using Apache Cassandra 2.1 or higher (see [CQL improvements in Cassandra 2.1](http://www.datastax.com/dev/blog/cql-in-2-1)). Other features are available only when using Apache Cassandra 2.0 or higher (e.g. result set paging, -[BatchStatement](https://github.com/datastax/java-driver/blob/3.x/driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java), +[BatchStatement](https://github.com/apache/cassandra-java-driver/blob/3.x/driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java), [lightweight transactions](http://www.datastax.com/documentation/cql/3.1/cql/cql_using/use_ltweight_transaction_t.html) -- see [What's new in Cassandra 2.0](http://www.datastax.com/documentation/cassandra/2.0/cassandra/features/features_key_c.html)). Trying to use these with a cluster running Cassandra 1.2 will result in -an [UnsupportedFeatureException](https://github.com/datastax/java-driver/blob/3.x/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedFeatureException.java) being thrown. +an [UnsupportedFeatureException](https://github.com/apache/cassandra-java-driver/blob/3.x/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedFeatureException.java) being thrown. The java driver supports Java JDK versions 6 and above. -If using _DataStax Enterprise_, the [DataStax Enterprise Java driver][dse-driver] provides -more features and better compatibility. - -__Disclaimer__: Some _DataStax/DataStax Enterprise_ products might partially work on -big-endian systems, but _DataStax_ does not officially support these systems. - ## Upgrading from previous versions If you are upgrading from a previous version of the driver, be sure to have a look at the [upgrade guide](/upgrade_guide/). -If you are upgrading to _DataStax Enterprise_, use the [DataStax Enterprise Java driver][dse-driver] for more -features and better compatibility. - -## License -Copyright 2012-2018, DataStax -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +---- -http://www.apache.org/licenses/LICENSE-2.0 +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. -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. -[dse-driver]: http://docs.datastax.com/en/developer/java-driver-dse/latest +Binary artifacts of this product bundle Java Native Runtime libraries, which is available under the Eclipse Public License version 2.0. diff --git a/build.yaml b/build.yaml deleted file mode 100644 index 58442c8321d..00000000000 --- a/build.yaml +++ /dev/null @@ -1,95 +0,0 @@ -schedules: - commit: - # Run short suite on commit with enough C* versions to get full protocol version coverage. - schedule: per_commit - matrix: - exclude: - # Exclude all builds on old jdk versions - - java: ['openjdk6','openjdk7'] - # Exclude java8 with all versions except latest - - java: openjdk8 - cassandra: ['2.2', '3.0'] - # Exclude java11 with all versions except latest - - java: openjdk11 - cassandra: ['2.1', '2.2', '3.0'] - env_vars: | - TEST_GROUP="short" - disable_commit_status: true - disable_pull_requests: true - notify: - slack: java-driver-dev-bots - nightly: - # Run full suite nightly on change for all primary branches if they have changes. - schedule: nightly - branches: - # regex matches primary branch format (2.1, 3.x, 3.0.x, 3.1.x, etc). - include: ["/\\d+(\\.[\\dx]+)+/"] - env_vars: | - TEST_GROUP="long" - disable_commit_status: true - disable_pull_requests: true - notify: - slack: java-driver-dev-bots - adhoc: - # Adhoc job for non-primary braches that doesn't have a schedule but may be used to run all configs. - schedule: adhoc - branches: - # regex matches primary branch format (2.1, 3.x, 3.0.x, 3.1.x, etc). - exclude: ["/\\d+(\\.[\\dx]+)+/"] - env_vars: | - TEST_GROUP="long" - disable_commit_status: true - disable_pull_requests: true - notify: - slack: java-driver-dev-bots -java: - - openjdk6 - - openjdk7 - - openjdk8 - - openjdk11 -os: - - ubuntu/bionic64/java-driver -cassandra: - - '2.1' - - '2.2' - - '3.0' - - '3.11' -build: - - script: | - . /usr/local/bin/jdk_switcher.sh - jdk_switcher use openjdk8 - export MAVEN_HOME=/home/jenkins/.mvn/apache-maven-3.2.5 - export PATH=$MAVEN_HOME/bin:$PATH - mvn -B -V install -DskipTests - - script: | - . /usr/local/bin/jdk_switcher.sh - jdk_switcher use $JAVA_VERSION - - type: maven - version: 3.2.5 - goals: verify --fail-never -P$TEST_GROUP - properties: | - com.datastax.driver.TEST_BASE_NODE_WAIT=120 - com.datastax.driver.NEW_NODE_DELAY_SECONDS=100 - cassandra.version=$CCM_CASSANDRA_VERSION - ccm.java.home=$CCM_JAVA_HOME - ccm.path=$CCM_JAVA_HOME/bin - ccm.maxNumberOfNodes=3 - failIfNoTests=false - maven.test.failure.ignore=true - maven.javadoc.skip=true - - type: maven - version: 3.2.5 - goals: verify --fail-never -Pisolated - properties: | - com.datastax.driver.TEST_BASE_NODE_WAIT=120 - com.datastax.driver.NEW_NODE_DELAY_SECONDS=100 - cassandra.version=$CCM_CASSANDRA_VERSION - ccm.java.home=$CCM_JAVA_HOME - ccm.path=$CCM_JAVA_HOME/bin - ccm.maxNumberOfNodes=3 - failIfNoTests=false - maven.test.failure.ignore=true - maven.javadoc.skip=true - - xunit: - - "**/target/surefire-reports/TEST-*.xml" - - "**/target/failsafe-reports/TEST-*.xml" diff --git a/changelog/README.md b/changelog/README.md index 1f00268b898..c8c12cffdbf 100644 --- a/changelog/README.md +++ b/changelog/README.md @@ -1,14 +1,137 @@ + + ## Changelog -### 3.7.0 (In progress) + + +## 3.12.1 +- [improvement] CASSJAVA-55: Remove setting "Host" header for metadata requests. +- [bug] JAVA-3125: Match broadcast RPC for control connection and Astra events + +## 3.12.0 +- [improvement] CASSANDRA-18971: Switch all archs to netty-tcnative-boringssl-static +- [improvement] CASSJAVA-58: Update 3.x DRIVER_NAME to match 4.x Java driver + +## 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 + +- [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 + +- [improvement] JAVA-2676: Don't reschedule flusher after empty runs. +- [new feature] JAVA-2772: Support new protocol v5 message format. + + +## 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 + +- [new feature] JAVA-2356: Support for DataStax Cloud API. +- [improvement] JAVA-2483: Allow to provide secure bundle via URL. +- [improvement] JAVA-2499: Allow to read the secure bundle from an InputStream. +- [improvement] JAVA-2457: Detect CaaS and change default consistency. +- [improvement] JAVA-2485: Add errors for Cloud misconfiguration. +- [documentation] JAVA-2504: Migrate Cloud "getting started" page to driver manual. +- [improvement] JAVA-2516: Enable hostname validation with Cloud +- [bug] JAVA-2515: NEW_NODE and REMOVED_NODE events should trigger ADDED and REMOVED. + + +### 3.7.2 + +- [bug] JAVA-2249: Stop stripping trailing zeros in ByteOrderedTokens. +- [bug] JAVA-1492: Don't immediately reuse busy connections for another request. +- [bug] JAVA-2198: Handle UDTs with names that clash with collection types. +- [bug] JAVA-2204: Avoid memory leak when client holds onto a stale TableMetadata instance. + + +### 3.7.1 + +- [bug] JAVA-2174: Metadata.needsQuote should accept empty strings. +- [bug] JAVA-2193: Fix flaky tests in WarningsTest. + + +### 3.7.0 -- [improvement] JAVA-2025: Include exception message in Abstract*Codec.accepts(null). - [improvement] JAVA-2025: Include exception message in Abstract\*Codec.accepts(null). - [improvement] JAVA-1980: Use covariant return types in RemoteEndpointAwareJdkSSLOptions.Builder methods. - [documentation] JAVA-2062: Document frozen collection preference with Mapper. - [bug] JAVA-2071: Fix NPE in ArrayBackedRow.toString(). - [bug] JAVA-2070: Call onRemove instead of onDown when rack and/or DC information changes for a host. - [improvement] JAVA-1256: Log parameters of BuiltStatement in QueryLogger. +- [documentation] JAVA-2074: Document preference for LZ4 over Snappy. +- [bug] JAVA-1612: Include netty-common jar in binary tarball. +- [improvement] JAVA-2003: Simplify CBUtil internal API to improve performance. +- [improvement] JAVA-2002: Reimplement TypeCodec.accepts to improve performance. +- [documentation] JAVA-2041: Deprecate cross-DC failover in DCAwareRoundRobinPolicy. +- [documentation] JAVA-1159: Document workaround for using tuple with udt field in Mapper. +- [documentation] JAVA-1964: Complete remaining "Coming Soon" sections in docs. +- [improvement] JAVA-1950: Log server side warnings returned from a query. +- [improvement] JAVA-2123: Allow to use QueryBuilder for building queries against Materialized Views. +- [bug] JAVA-2082: Avoid race condition during cluster close and schema refresh. ### 3.6.0 diff --git a/ci/appveyor.ps1 b/ci/appveyor.ps1 index bc1d95b69f7..c0db375e05c 100644 --- a/ci/appveyor.ps1 +++ b/ci/appveyor.ps1 @@ -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. + #> + Add-Type -AssemblyName System.IO.Compression.FileSystem $dep_dir="C:\Users\appveyor\deps" diff --git a/ci/appveyor.yml b/ci/appveyor.yml index 81dd5b01958..bd621defb76 100644 --- a/ci/appveyor.yml +++ b/ci/appveyor.yml @@ -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. + environment: test_profile: default matrix: 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..b1bf201442b --- /dev/null +++ b/ci/run-tests.sh @@ -0,0 +1,9 @@ +#!/bin/bash -x + +. ~/env.txt +printenv | sort +cd $(dirname "$(readlink -f "$0")")/.. +mvn -B -V install -DskipTests -Dmaven.javadoc.skip=true +jabba use ${TEST_JAVA_VERSION} +printenv | sort +mvn -B -V verify -T 1 -Dcassandra.version=${SERVER_VERSION} -Ddse=false -Dmaven.test.failure.ignore=true -Dmaven.javadoc.skip=true; diff --git a/ci/uploadtests.ps1 b/ci/uploadtests.ps1 index cf88b16229c..aaf7279ed46 100644 --- a/ci/uploadtests.ps1 +++ b/ci/uploadtests.ps1 @@ -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. + #> + $testResults=Get-ChildItem TEST-TestSuite.xml -Recurse Write-Host "Uploading test results." diff --git a/clirr-ignores.xml b/clirr-ignores.xml index e7c34ac458c..271bd6f7773 100644 --- a/clirr-ignores.xml +++ b/clirr-ignores.xml @@ -1,3 +1,23 @@ + + + com/datastax/driver/core/FrameCompressor$LZ4Compressor @@ -158,5 +177,198 @@ * Relaxed parameters from List to Iterable for in, lt, lte, eq, gt, and gte - + + 7005 + com/datastax/driver/core/exceptions/AlreadyExistsException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/AuthenticationException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/BootstrappingException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/BusyConnectionException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/BusyPoolException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 6001 + com/datastax/driver/core/exceptions/ConnectionException + address + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/ConnectionException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7012 + com/datastax/driver/core/exceptions/CoordinatorException + com.datastax.driver.core.EndPoint getEndPoint() + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/FunctionExecutionException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/InvalidConfigurationInQueryException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/InvalidQueryException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/OperationTimedOutException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/OperationTimedOutException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/OverloadedException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/ProtocolError + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/QueryConsistencyException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/ReadFailureException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/ReadTimeoutException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/ServerError + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/SyntaxError + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/TransportException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/TruncateException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/UnauthorizedException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/UnavailableException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/UnpreparedException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/UnsupportedProtocolVersionException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/WriteFailureException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + + + 7005 + com/datastax/driver/core/exceptions/WriteTimeoutException + *java.net.InetSocketAddress* + *com.datastax.driver.core.EndPoint* + JAVA-2355: Abstract connection information into new EndPoint type for sni support + diff --git a/docs.yaml b/docs.yaml index b38b86397d7..4b30dcd5813 100644 --- a/docs.yaml +++ b/docs.yaml @@ -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. + title: Java Driver for Apache Cassandra summary: High performance Java client for Apache Cassandra homepage: http://datastax.github.io/java-driver/ @@ -33,7 +50,7 @@ sections: files: 'faq/**/*.md' links: - title: Code - href: https://github.com/datastax/java-driver/ + href: https://github.com/apache/cassandra-java-driver/ - title: Docs href: http://docs.datastax.com/en/developer/java-driver/ - title: Issues diff --git a/doxyfile b/doxyfile index 414bdbd7ec4..d64c6fe1d82 100644 --- a/doxyfile +++ b/doxyfile @@ -1,10 +1,30 @@ + + + # Doxyfile 1.8.10 #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- DOXYFILE_ENCODING = UTF-8 -PROJECT_NAME = "DataStax Java Driver" +PROJECT_NAME = "Java Driver" PROJECT_NUMBER = PROJECT_BRIEF = PROJECT_LOGO = @@ -333,4 +353,4 @@ MAX_DOT_GRAPH_DEPTH = 0 DOT_TRANSPARENT = NO DOT_MULTI_TARGETS = NO GENERATE_LEGEND = YES -DOT_CLEANUP = YES \ No newline at end of file +DOT_CLEANUP = YES diff --git a/driver-core/pom.xml b/driver-core/pom.xml index c2bf48fbe17..45aff62c17d 100644 --- a/driver-core/pom.xml +++ b/driver-core/pom.xml @@ -1,12 +1,14 @@ - + com.datastax.shaded.* + com.datastax.shaded.metrics;* @@ -261,6 +284,7 @@ io.netty:* + io.dropwizard.metrics:metrics-core io.netty:netty-transport-native-epoll @@ -271,6 +295,10 @@ io.netty com.datastax.shaded.netty + + com.codahale.metrics + com.datastax.shaded.metrics + @@ -287,6 +315,8 @@ META-INF/maven/io.netty/netty-handler/pom.xml META-INF/maven/io.netty/netty-transport/pom.properties META-INF/maven/io.netty/netty-transport/pom.xml + META-INF/maven/io.dropwizard.metrics/metrics-core/pom.properties + META-INF/maven/io.dropwizard.metrics/metrics-core/pom.xml diff --git a/driver-core/src/main/java/com/datastax/driver/core/AbstractAddressableByIndexData.java b/driver-core/src/main/java/com/datastax/driver/core/AbstractAddressableByIndexData.java index ea05bf92f2e..689b41d0b25 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/AbstractAddressableByIndexData.java +++ b/driver-core/src/main/java/com/datastax/driver/core/AbstractAddressableByIndexData.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/AbstractData.java b/driver-core/src/main/java/com/datastax/driver/core/AbstractData.java index 8013729f65d..8de0ad00037 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/AbstractData.java +++ b/driver-core/src/main/java/com/datastax/driver/core/AbstractData.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/AbstractGettableByIndexData.java b/driver-core/src/main/java/com/datastax/driver/core/AbstractGettableByIndexData.java index 9d46e7c09f5..389aeea33e7 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/AbstractGettableByIndexData.java +++ b/driver-core/src/main/java/com/datastax/driver/core/AbstractGettableByIndexData.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/AbstractGettableData.java b/driver-core/src/main/java/com/datastax/driver/core/AbstractGettableData.java index ec29ed7a17d..f6c32a34fb6 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/AbstractGettableData.java +++ b/driver-core/src/main/java/com/datastax/driver/core/AbstractGettableData.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/AbstractMonotonicTimestampGenerator.java b/driver-core/src/main/java/com/datastax/driver/core/AbstractMonotonicTimestampGenerator.java index 4c84113526c..5c5548a748b 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/AbstractMonotonicTimestampGenerator.java +++ b/driver-core/src/main/java/com/datastax/driver/core/AbstractMonotonicTimestampGenerator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java b/driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java index ec109b6f308..c559af07632 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +++ b/driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -171,7 +173,7 @@ public void run() { } else { logger.error( "Retries against {} have been suspended. It won't be retried unless the node is restarted.", - e.getHost()); + e.getEndPoint()); currentAttempt.compareAndSet(handlerFuture, null); } } catch (InterruptedException e) { @@ -184,7 +186,7 @@ public void run() { } else { logger.error( "Retries against {} have been suspended. It won't be retried unless the node is restarted.", - e.getHost()); + e.getEndPoint()); currentAttempt.compareAndSet(handlerFuture, null); } } catch (ClusterNameMismatchException e) { @@ -195,7 +197,7 @@ public void run() { } else { logger.error( "Retries against {} have been suspended. It won't be retried unless the node is restarted.", - e.address.getAddress()); + e.endPoint); currentAttempt.compareAndSet(handlerFuture, null); } } catch (Exception e) { diff --git a/driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java b/driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java index 61de3414fd2..b99b1981c18 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +++ b/driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/AbstractTableMetadata.java b/driver-core/src/main/java/com/datastax/driver/core/AbstractTableMetadata.java index 5a375e2d958..2cdb9c52e46 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/AbstractTableMetadata.java +++ b/driver-core/src/main/java/com/datastax/driver/core/AbstractTableMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -258,14 +260,22 @@ protected StringBuilder appendOptions(StringBuilder sb, boolean formatted) { sb.append("WITH "); if (options.isCompactStorage()) and(sb.append("COMPACT STORAGE"), formatted); if (!clusteringOrder.isEmpty()) and(appendClusteringOrder(sb), formatted); - sb.append("read_repair_chance = ").append(options.getReadRepairChance()); - and(sb, formatted) - .append("dclocal_read_repair_chance = ") - .append(options.getLocalReadRepairChance()); + if (cassandraVersion.getMajor() < 4) + sb.append("read_repair_chance = ").append(options.getReadRepairChance()); + else sb.append("read_repair = '").append(options.getReadRepair()).append('\''); + if (cassandraVersion.getMajor() < 4) + and(sb, formatted) + .append("dclocal_read_repair_chance = ") + .append(options.getLocalReadRepairChance()); if (cassandraVersion.getMajor() < 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() == 0)) and(sb, formatted).append("replicate_on_write = ").append(options.getReplicateOnWrite()); and(sb, formatted).append("gc_grace_seconds = ").append(options.getGcGraceInSeconds()); + if (cassandraVersion.getMajor() > 3) + and(sb, formatted) + .append("additional_write_policy = '") + .append(options.getAdditionalWritePolicy()) + .append('\''); and(sb, formatted) .append("bloom_filter_fp_chance = ") .append(options.getBloomFilterFalsePositiveChance()); diff --git a/driver-core/src/main/java/com/datastax/driver/core/AggregateMetadata.java b/driver-core/src/main/java/com/datastax/driver/core/AggregateMetadata.java index 65b149e7542..15b95122d74 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/AggregateMetadata.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java b/driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java index 224dc252266..6728bc8d089 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -467,13 +469,13 @@ public void onSet( // This mean we have probably have a bad node, so defunct the connection connection.defunct( new ConnectionException( - connection.address, + connection.endPoint, String.format("Got unexpected %s result response", rm.kind))); future.setException( new DriverInternalError( String.format( "Got unexpected %s result response from %s", - rm.kind, connection.address))); + rm.kind, connection.endPoint))); return; } @@ -482,26 +484,26 @@ public void onSet( break; case ERROR: future.setException( - ((Responses.Error) response).asException(connection.address)); + ((Responses.Error) response).asException(connection.endPoint)); break; default: // This mean we have probably have a bad node, so defunct the connection connection.defunct( new ConnectionException( - connection.address, + connection.endPoint, String.format("Got unexpected %s response", response.type))); future.setException( new DriverInternalError( String.format( "Got unexpected %s response from %s", - response.type, connection.address))); + response.type, connection.endPoint))); break; } } catch (RuntimeException e) { // If we get a bug here, the client will not get it, so better forwarding the error future.setException( new DriverInternalError( - "Unexpected error while processing response from " + connection.address, + "Unexpected error while processing response from " + connection.endPoint, e)); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/ArrayBackedRow.java b/driver-core/src/main/java/com/datastax/driver/core/ArrayBackedRow.java index 8e7028035ed..22aa4fdca62 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ArrayBackedRow.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ArrayBackedRow.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.java b/driver-core/src/main/java/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.java index f20b34e5451..804b991ead4 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.java +++ b/driver-core/src/main/java/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/AuthProvider.java b/driver-core/src/main/java/com/datastax/driver/core/AuthProvider.java index 5a47debf1cd..b623f901468 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/AuthProvider.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -31,17 +33,7 @@ public interface AuthProvider { * *

This is only useful as a placeholder when no authentication is to be used. */ - public static final AuthProvider NONE = - new AuthProvider() { - @Override - public Authenticator newAuthenticator(InetSocketAddress host, String authenticator) { - throw new AuthenticationException( - host, - String.format( - "Host %s requires authentication, but no authenticator found in Cluster configuration", - host)); - } - }; + AuthProvider NONE = new ExtendedAuthProvider.NoAuthProvider(); /** * The {@code Authenticator} to use when connecting to {@code host} @@ -52,4 +44,19 @@ public Authenticator newAuthenticator(InetSocketAddress host, String authenticat */ public Authenticator newAuthenticator(InetSocketAddress host, String authenticator) throws AuthenticationException; + + /** + * Dummy Authenticator that accounts for DSE authentication configured with transitional mode. + * + *

In this situation, the client is allowed to connect without authentication, but DSE would + * still send an AUTHENTICATE response. This Authenticator handles this situation by sending back + * a dummy credential. + */ + class TransitionalModePlainTextAuthenticator + extends PlainTextAuthProvider.PlainTextAuthenticator { + + public TransitionalModePlainTextAuthenticator() { + super("", ""); + } + } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/Authenticator.java b/driver-core/src/main/java/com/datastax/driver/core/Authenticator.java index 00e2a48279a..29d85b2386c 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Authenticator.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java b/driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java index ef8cd34800f..22ff7594e91 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -21,9 +23,7 @@ import com.google.common.collect.ImmutableList; import java.nio.ByteBuffer; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.List; /** @@ -82,22 +82,23 @@ public BatchStatement(Type batchType) { IdAndValues getIdAndValues(ProtocolVersion protocolVersion, CodecRegistry codecRegistry) { IdAndValues idAndVals = new IdAndValues(statements.size()); - for (Statement statement : statements) { - if (statement instanceof StatementWrapper) + for (int i = 0; i < statements.size(); i++) { + Statement statement = statements.get(i); + if (statement instanceof StatementWrapper) { statement = ((StatementWrapper) statement).getWrappedStatement(); + } if (statement instanceof RegularStatement) { RegularStatement st = (RegularStatement) statement; ByteBuffer[] vals = st.getValues(protocolVersion, codecRegistry); String query = st.getQueryString(codecRegistry); idAndVals.ids.add(query); - idAndVals.values.add( - vals == null ? Collections.emptyList() : Arrays.asList(vals)); + idAndVals.values[i] = vals == null ? Requests.EMPTY_BB_ARRAY : vals; } else { // We handle BatchStatement in add() so ... assert statement instanceof BoundStatement; BoundStatement st = (BoundStatement) statement; idAndVals.ids.add(st.statement.getPreparedId().boundValuesMetadata.id); - idAndVals.values.add(Arrays.asList(st.wrapper.values)); + idAndVals.values[i] = st.wrapper.values; } } return idAndVals; @@ -212,7 +213,7 @@ public int requestSizeInBytes(ProtocolVersion protocolVersion, CodecRegistry cod + (q instanceof String ? CBUtil.sizeOfLongString((String) q) : CBUtil.sizeOfShortBytes(((MD5Digest) q).bytes)); - size += CBUtil.sizeOfValueList(idAndVals.values.get(i)); + size += CBUtil.sizeOfValueList(idAndVals.values[i]); } switch (protocolVersion) { case V2: @@ -221,6 +222,7 @@ public int requestSizeInBytes(ProtocolVersion protocolVersion, CodecRegistry cod case V3: case V4: case V5: + case V6: size += CBUtil.sizeOfConsistencyLevel(getConsistencyLevel()); size += QueryFlag.serializedSize(protocolVersion); // Serial CL and default timestamp also depend on session-level defaults (QueryOptions). @@ -301,11 +303,11 @@ void ensureAllSet() { static class IdAndValues { public final List ids; - public final List> values; + public final ByteBuffer[][] values; IdAndValues(int nbstatements) { ids = new ArrayList(nbstatements); - values = new ArrayList>(nbstatements); + values = new ByteBuffer[nbstatements][]; } } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java b/driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java index 279f81bc25d..863498a3f3f 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -23,7 +25,6 @@ import java.math.BigInteger; import java.net.InetAddress; import java.nio.ByteBuffer; -import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; @@ -322,10 +323,11 @@ public int requestSizeInBytes(ProtocolVersion protocolVersion, CodecRegistry cod case V3: case V4: case V5: + case V6: size += CBUtil.sizeOfConsistencyLevel(getConsistencyLevel()); size += QueryFlag.serializedSize(protocolVersion); if (wrapper.values.length > 0) { - size += CBUtil.sizeOfValueList(Arrays.asList(wrapper.values)); + size += CBUtil.sizeOfValueList(wrapper.values); } // Fetch size, serial CL and default timestamp also depend on session-level defaults // (QueryOptions). diff --git a/driver-core/src/main/java/com/datastax/driver/core/BytesToSegmentDecoder.java b/driver-core/src/main/java/com/datastax/driver/core/BytesToSegmentDecoder.java new file mode 100644 index 00000000000..a20f2dfe61d --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/BytesToSegmentDecoder.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.driver.core; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.LengthFieldBasedFrameDecoder; +import java.nio.ByteOrder; + +/** + * Decodes {@link Segment}s from a stream of bytes. + * + *

This works like a regular length-field-based decoder, but we override {@link + * #getUnadjustedFrameLength} to handle two peculiarities: the length is encoded on 17 bits, and we + * also want to check the header CRC before we use it. So we parse the whole segment header ahead of + * time, and store it until we're ready to build the segment. + */ +class BytesToSegmentDecoder extends LengthFieldBasedFrameDecoder { + + private final SegmentCodec segmentCodec; + private SegmentCodec.Header header; + + BytesToSegmentDecoder(SegmentCodec segmentCodec) { + super( + // max length (Netty wants this to be the overall length including everything): + segmentCodec.headerLength() + + SegmentCodec.CRC24_LENGTH + + Segment.MAX_PAYLOAD_LENGTH + + SegmentCodec.CRC32_LENGTH, + // offset and size of the "length" field: that's the whole header + 0, + segmentCodec.headerLength() + SegmentCodec.CRC24_LENGTH, + // length adjustment: add the trailing CRC to the declared length + SegmentCodec.CRC32_LENGTH, + // bytes to skip: the header (we've already parsed it while reading the length) + segmentCodec.headerLength() + SegmentCodec.CRC24_LENGTH); + this.segmentCodec = segmentCodec; + } + + @Override + protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { + try { + ByteBuf payloadAndCrc = (ByteBuf) super.decode(ctx, in); + if (payloadAndCrc == null) { + return null; + } else { + assert header != null; + Segment segment = segmentCodec.decode(header, payloadAndCrc); + header = null; + return segment; + } + } catch (Exception e) { + // Don't hold on to a stale header if we failed to decode the rest of the segment + header = null; + throw e; + } + } + + @Override + protected long getUnadjustedFrameLength(ByteBuf buffer, int offset, int length, ByteOrder order) { + // The parent class calls this repeatedly for the same "frame" if there weren't enough + // accumulated bytes the first time. Only decode the header the first time: + if (header == null) { + header = segmentCodec.decodeHeader(buffer.slice(offset, length)); + } + return header.payloadLength; + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/CBUtil.java b/driver-core/src/main/java/com/datastax/driver/core/CBUtil.java index 00019fa0173..98aaccf373e 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/CBUtil.java +++ b/driver-core/src/main/java/com/datastax/driver/core/CBUtil.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,16 @@ import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; /** ByteBuf utility methods. */ + +// Implementation note: in order to facilitate loop optimizations by the JIT compiler, this class +// favors indexed loops over "foreach" loops. +@SuppressWarnings("ForLoopReplaceableByForEach") abstract class CBUtil { // TODO rename private CBUtil() {} @@ -49,7 +54,7 @@ private static String readString(ByteBuf cb, int length) { } } - public static String readString(ByteBuf cb) { + static String readString(ByteBuf cb) { try { int length = cb.readUnsignedShort(); return readString(cb, length); @@ -59,13 +64,13 @@ public static String readString(ByteBuf cb) { } } - public static void writeString(String str, ByteBuf cb) { + private static void writeString(String str, ByteBuf cb) { byte[] bytes = str.getBytes(CharsetUtil.UTF_8); cb.writeShort(bytes.length); cb.writeBytes(bytes); } - public static int sizeOfString(String str) { + static int sizeOfString(String str) { return 2 + encodedUTF8Length(str); } @@ -81,27 +86,17 @@ private static int encodedUTF8Length(String st) { return utflen; } - public static String readLongString(ByteBuf cb) { - try { - int length = cb.readInt(); - return readString(cb, length); - } catch (IndexOutOfBoundsException e) { - throw new DriverInternalError( - "Not enough bytes to read an UTF8 serialized string preceded by it's 4 bytes length"); - } - } - - public static void writeLongString(String str, ByteBuf cb) { + static void writeLongString(String str, ByteBuf cb) { byte[] bytes = str.getBytes(CharsetUtil.UTF_8); cb.writeInt(bytes.length); cb.writeBytes(bytes); } - public static int sizeOfLongString(String str) { + static int sizeOfLongString(String str) { return 4 + str.getBytes(CharsetUtil.UTF_8).length; } - public static byte[] readBytes(ByteBuf cb) { + static byte[] readBytes(ByteBuf cb) { try { int length = cb.readUnsignedShort(); byte[] bytes = new byte[length]; @@ -113,20 +108,20 @@ public static byte[] readBytes(ByteBuf cb) { } } - public static void writeShortBytes(byte[] bytes, ByteBuf cb) { + static void writeShortBytes(byte[] bytes, ByteBuf cb) { cb.writeShort(bytes.length); cb.writeBytes(bytes); } - public static int sizeOfShortBytes(byte[] bytes) { + static int sizeOfShortBytes(byte[] bytes) { return 2 + bytes.length; } - public static int sizeOfBytes(ByteBuffer bytes) { + private static int sizeOfBytes(ByteBuffer bytes) { return 4 + bytes.remaining(); } - public static Map readBytesMap(ByteBuf cb) { + static Map readBytesMap(ByteBuf cb) { int length = cb.readUnsignedShort(); ImmutableMap.Builder builder = ImmutableMap.builder(); for (int i = 0; i < length; i++) { @@ -138,7 +133,7 @@ public static Map readBytesMap(ByteBuf cb) { return builder.build(); } - public static void writeBytesMap(Map m, ByteBuf cb) { + static void writeBytesMap(Map m, ByteBuf cb) { cb.writeShort(m.size()); for (Map.Entry entry : m.entrySet()) { writeString(entry.getKey(), cb); @@ -148,7 +143,7 @@ public static void writeBytesMap(Map m, ByteBuf cb) { } } - public static int sizeOfBytesMap(Map m) { + static int sizeOfBytesMap(Map m) { int size = 2; for (Map.Entry entry : m.entrySet()) { size += sizeOfString(entry.getKey()); @@ -157,19 +152,19 @@ public static int sizeOfBytesMap(Map m) { return size; } - public static ConsistencyLevel readConsistencyLevel(ByteBuf cb) { + static ConsistencyLevel readConsistencyLevel(ByteBuf cb) { return ConsistencyLevel.fromCode(cb.readUnsignedShort()); } - public static void writeConsistencyLevel(ConsistencyLevel consistency, ByteBuf cb) { + static void writeConsistencyLevel(ConsistencyLevel consistency, ByteBuf cb) { cb.writeShort(consistency.code); } - public static int sizeOfConsistencyLevel(ConsistencyLevel consistency) { + static int sizeOfConsistencyLevel(@SuppressWarnings("unused") ConsistencyLevel consistency) { return 2; } - public static > T readEnumValue(Class enumType, ByteBuf cb) { + static > T readEnumValue(Class enumType, ByteBuf cb) { String value = CBUtil.readString(cb); try { return Enum.valueOf(enumType, value.toUpperCase()); @@ -179,59 +174,30 @@ public static > T readEnumValue(Class enumType, ByteBuf cb) } } - public static > void writeEnumValue(T enumValue, ByteBuf cb) { + static > void writeEnumValue(T enumValue, ByteBuf cb) { writeString(enumValue.toString(), cb); } - public static > int sizeOfEnumValue(T enumValue) { + static > int sizeOfEnumValue(T enumValue) { return sizeOfString(enumValue.toString()); } - public static UUID readUUID(ByteBuf cb) { + static UUID readUUID(ByteBuf cb) { long msb = cb.readLong(); long lsb = cb.readLong(); return new UUID(msb, lsb); } - public static void writeUUID(UUID uuid, ByteBuf cb) { - cb.writeLong(uuid.getMostSignificantBits()); - cb.writeLong(uuid.getLeastSignificantBits()); - } - - public static int sizeOfUUID(UUID uuid) { - return 16; - } - - public static List readStringList(ByteBuf cb) { + static List readStringList(ByteBuf cb) { int length = cb.readUnsignedShort(); List l = new ArrayList(length); - for (int i = 0; i < length; i++) l.add(readString(cb)); - return l; - } - - public static void writeStringList(List l, ByteBuf cb) { - cb.writeShort(l.size()); - for (String str : l) writeString(str, cb); - } - - public static int sizeOfStringList(List l) { - int size = 2; - for (String str : l) size += sizeOfString(str); - return size; - } - - public static Map readStringMap(ByteBuf cb) { - int length = cb.readUnsignedShort(); - Map m = new HashMap(length); for (int i = 0; i < length; i++) { - String k = readString(cb).toUpperCase(); - String v = readString(cb); - m.put(k, v); + l.add(readString(cb)); } - return m; + return l; } - public static void writeStringMap(Map m, ByteBuf cb) { + static void writeStringMap(Map m, ByteBuf cb) { cb.writeShort(m.size()); for (Map.Entry entry : m.entrySet()) { writeString(entry.getKey(), cb); @@ -239,7 +205,7 @@ public static void writeStringMap(Map m, ByteBuf cb) { } } - public static int sizeOfStringMap(Map m) { + static int sizeOfStringMap(Map m) { int size = 2; for (Map.Entry entry : m.entrySet()) { size += sizeOfString(entry.getKey()); @@ -248,7 +214,7 @@ public static int sizeOfStringMap(Map m) { return size; } - public static Map> readStringToStringListMap(ByteBuf cb) { + static Map> readStringToStringListMap(ByteBuf cb) { int length = cb.readUnsignedShort(); Map> m = new HashMap>(length); for (int i = 0; i < length; i++) { @@ -259,24 +225,7 @@ public static Map> readStringToStringListMap(ByteBuf cb) { return m; } - public static void writeStringToStringListMap(Map> m, ByteBuf cb) { - cb.writeShort(m.size()); - for (Map.Entry> entry : m.entrySet()) { - writeString(entry.getKey(), cb); - writeStringList(entry.getValue(), cb); - } - } - - public static int sizeOfStringToStringListMap(Map> m) { - int size = 2; - for (Map.Entry> entry : m.entrySet()) { - size += sizeOfString(entry.getKey()); - size += sizeOfStringList(entry.getValue()); - } - return size; - } - - public static ByteBuffer readValue(ByteBuf cb) { + static ByteBuffer readValue(ByteBuf cb) { int length = cb.readInt(); if (length < 0) return null; ByteBuf slice = cb.readSlice(length); @@ -284,7 +233,7 @@ public static ByteBuffer readValue(ByteBuf cb) { return ByteBuffer.wrap(readRawBytes(slice)); } - public static void writeValue(byte[] bytes, ByteBuf cb) { + static void writeValue(byte[] bytes, ByteBuf cb) { if (bytes == null) { cb.writeInt(-1); return; @@ -294,7 +243,7 @@ public static void writeValue(byte[] bytes, ByteBuf cb) { cb.writeBytes(bytes); } - public static void writeValue(ByteBuffer bytes, ByteBuf cb) { + static void writeValue(ByteBuffer bytes, ByteBuf cb) { if (bytes == null) { cb.writeInt(-1); return; @@ -309,35 +258,32 @@ public static void writeValue(ByteBuffer bytes, ByteBuf cb) { cb.writeBytes(bytes.duplicate()); } - public static int sizeOfValue(byte[] bytes) { + static int sizeOfValue(byte[] bytes) { return 4 + (bytes == null ? 0 : bytes.length); } - public static int sizeOfValue(ByteBuffer bytes) { + static int sizeOfValue(ByteBuffer bytes) { return 4 + (bytes == null ? 0 : bytes.remaining()); } - public static List readValueList(ByteBuf cb) { - int size = cb.readUnsignedShort(); - if (size == 0) return Collections.emptyList(); - - List l = new ArrayList(size); - for (int i = 0; i < size; i++) l.add(readValue(cb)); - return l; - } - - public static void writeValueList(List values, ByteBuf cb) { - cb.writeShort(values.size()); - for (ByteBuffer value : values) CBUtil.writeValue(value, cb); + static void writeValueList(ByteBuffer[] values, ByteBuf cb) { + cb.writeShort(values.length); + for (int i = 0; i < values.length; i++) { + ByteBuffer value = values[i]; + CBUtil.writeValue(value, cb); + } } - public static int sizeOfValueList(List values) { + static int sizeOfValueList(ByteBuffer[] values) { int size = 2; - for (ByteBuffer value : values) size += CBUtil.sizeOfValue(value); + for (int i = 0; i < values.length; i++) { + ByteBuffer value = values[i]; + size += CBUtil.sizeOfValue(value); + } return size; } - public static void writeNamedValueList(Map namedValues, ByteBuf cb) { + static void writeNamedValueList(Map namedValues, ByteBuf cb) { cb.writeShort(namedValues.size()); for (Map.Entry entry : namedValues.entrySet()) { CBUtil.writeString(entry.getKey(), cb); @@ -345,7 +291,7 @@ public static void writeNamedValueList(Map namedValues, Byte } } - public static int sizeOfNamedValueList(Map namedValues) { + static int sizeOfNamedValueList(Map namedValues) { int size = 2; for (Map.Entry entry : namedValues.entrySet()) { size += CBUtil.sizeOfString(entry.getKey()); @@ -354,7 +300,7 @@ public static int sizeOfNamedValueList(Map namedValues) { return size; } - public static InetSocketAddress readInet(ByteBuf cb) { + static InetSocketAddress readInet(ByteBuf cb) { int addrSize = cb.readByte() & 0xFF; byte[] address = new byte[addrSize]; cb.readBytes(address); @@ -369,7 +315,7 @@ public static InetSocketAddress readInet(ByteBuf cb) { } } - public static InetAddress readInetWithoutPort(ByteBuf cb) { + static InetAddress readInetWithoutPort(ByteBuf cb) { int addrSize = cb.readByte() & 0xFF; byte[] address = new byte[addrSize]; cb.readBytes(address); @@ -383,24 +329,11 @@ public static InetAddress readInetWithoutPort(ByteBuf cb) { } } - public static void writeInet(InetSocketAddress inet, ByteBuf cb) { - byte[] address = inet.getAddress().getAddress(); - - cb.writeByte(address.length); - cb.writeBytes(address); - cb.writeInt(inet.getPort()); - } - - public static int sizeOfInet(InetSocketAddress inet) { - byte[] address = inet.getAddress().getAddress(); - return 1 + address.length + 4; - } - /* * Reads *all* readable bytes from {@code cb} and return them. * If {@code cb} is backed by an array, this will return the underlying array directly, without copy. */ - public static byte[] readRawBytes(ByteBuf cb) { + private static byte[] readRawBytes(ByteBuf cb) { if (cb.hasArray() && cb.readableBytes() == cb.array().length) { // Move the readerIndex just so we consistently consume the input cb.readerIndex(cb.writerIndex()); diff --git a/driver-core/src/main/java/com/datastax/driver/core/CancelledSpeculativeExecutionException.java b/driver-core/src/main/java/com/datastax/driver/core/CancelledSpeculativeExecutionException.java index c92ff7e8efd..6cb77040b85 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/CancelledSpeculativeExecutionException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/CancelledSpeculativeExecutionException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/ChainedResultSetFuture.java b/driver-core/src/main/java/com/datastax/driver/core/ChainedResultSetFuture.java index 47d7767d332..8876cfb0ab1 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ChainedResultSetFuture.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ChainedResultSetFuture.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/Clock.java b/driver-core/src/main/java/com/datastax/driver/core/Clock.java index b9bdc27547d..aad701d5887 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Clock.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, diff --git a/driver-core/src/main/java/com/datastax/driver/core/CloseFuture.java b/driver-core/src/main/java/com/datastax/driver/core/CloseFuture.java index 9a6d4b5084e..de5961965f8 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/CloseFuture.java +++ b/driver-core/src/main/java/com/datastax/driver/core/CloseFuture.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/CloudConfig.java b/driver-core/src/main/java/com/datastax/driver/core/CloudConfig.java new file mode 100644 index 00000000000..332ed7fd62a --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/CloudConfig.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.driver.core; + +import com.google.common.collect.ImmutableList; +import java.net.InetSocketAddress; +import java.util.List; + +class CloudConfig { + + private final InetSocketAddress proxyAddress; + private final List endPoints; + private final String localDatacenter; + private final SSLOptions sslOptions; + private final AuthProvider authProvider; + + CloudConfig( + InetSocketAddress proxyAddress, + List endPoints, + String localDatacenter, + SSLOptions sslOptions, + AuthProvider authProvider) { + this.proxyAddress = proxyAddress; + this.endPoints = ImmutableList.copyOf(endPoints); + this.localDatacenter = localDatacenter; + this.sslOptions = sslOptions; + this.authProvider = authProvider; + } + + /** @return not null proxy Address */ + InetSocketAddress getProxyAddress() { + return proxyAddress; + } + + /** @return not null endpoints */ + List getEndPoints() { + return endPoints; + } + + /** @return not null local data center */ + String getLocalDatacenter() { + return localDatacenter; + } + + /** @return not null ssl options that can be used to connect to SniProxy */ + SSLOptions getSslOptions() { + return sslOptions; + } + + /** + * @return nullable AuthProvider that can be used to connect to proxy or null if there was not + * username/password provided in the secure bundle + */ + AuthProvider getAuthProvider() { + return authProvider; + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/CloudConfigFactory.java b/driver-core/src/main/java/com/datastax/driver/core/CloudConfigFactory.java new file mode 100644 index 00000000000..d2181cc3e77 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/CloudConfigFactory.java @@ -0,0 +1,268 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +import static com.google.common.base.Charsets.UTF_8; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Throwables; +import com.google.common.io.ByteStreams; +import com.google.common.net.HostAndPort; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.InetSocketAddress; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +class CloudConfigFactory { + + /** + * Creates a {@link CloudConfig} with information fetched from the specified {@link InputStream}. + * + *

The stream must contain a valid secure connect bundle archive in ZIP format. Note that the + * stream will be closed after a call to that method and cannot be used anymore. + * + * @param cloudConfig the stream to read the Cloud configuration from; cannot be null. + * @throws IOException If the Cloud configuration cannot be read. + * @throws GeneralSecurityException If the Cloud SSL context cannot be created. + */ + CloudConfig createCloudConfig(InputStream cloudConfig) + throws IOException, GeneralSecurityException { + checkNotNull(cloudConfig, "cloudConfig cannot be null"); + JsonNode configJson = null; + ByteArrayOutputStream keyStoreOutputStream = null; + ByteArrayOutputStream trustStoreOutputStream = null; + ObjectMapper mapper = new ObjectMapper().configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false); + ZipInputStream zipInputStream = null; + try { + zipInputStream = new ZipInputStream(cloudConfig); + ZipEntry entry; + while ((entry = zipInputStream.getNextEntry()) != null) { + String fileName = entry.getName(); + if (fileName.equals("config.json")) { + configJson = mapper.readTree(zipInputStream); + } else if (fileName.equals("identity.jks")) { + keyStoreOutputStream = new ByteArrayOutputStream(); + ByteStreams.copy(zipInputStream, keyStoreOutputStream); + } else if (fileName.equals("trustStore.jks")) { + trustStoreOutputStream = new ByteArrayOutputStream(); + ByteStreams.copy(zipInputStream, trustStoreOutputStream); + } + } + } finally { + if (zipInputStream != null) { + zipInputStream.close(); + } + } + + if (configJson == null) { + throw new IllegalStateException("Invalid bundle: missing file config.json"); + } + if (keyStoreOutputStream == null) { + throw new IllegalStateException("Invalid bundle: missing file identity.jks"); + } + if (trustStoreOutputStream == null) { + throw new IllegalStateException("Invalid bundle: missing file trustStore.jks"); + } + char[] keyStorePassword = getKeyStorePassword(configJson); + char[] trustStorePassword = getTrustStorePassword(configJson); + ByteArrayInputStream keyStoreInputStream = + new ByteArrayInputStream(keyStoreOutputStream.toByteArray()); + ByteArrayInputStream trustStoreInputStream = + new ByteArrayInputStream(trustStoreOutputStream.toByteArray()); + SSLContext sslContext = + createSslContext( + keyStoreInputStream, keyStorePassword, trustStoreInputStream, trustStorePassword); + URL metadataServiceUrl = getMetadataServiceUrl(configJson); + JsonNode proxyMetadataJson; + BufferedReader proxyMetadata = null; + try { + proxyMetadata = fetchProxyMetadata(metadataServiceUrl, sslContext); + proxyMetadataJson = mapper.readTree(proxyMetadata); + } finally { + if (proxyMetadata != null) { + proxyMetadata.close(); + } + } + InetSocketAddress sniProxyAddress = getSniProxyAddress(proxyMetadataJson); + List endPoints = getEndPoints(proxyMetadataJson, sniProxyAddress); + String localDatacenter = getLocalDatacenter(proxyMetadataJson); + SSLOptions sslOptions = getSSLOptions(sslContext); + AuthProvider authProvider = getAuthProvider(configJson); + return new CloudConfig(sniProxyAddress, endPoints, localDatacenter, sslOptions, authProvider); + } + + protected char[] getKeyStorePassword(JsonNode configFile) { + if (configFile.has("keyStorePassword")) { + return configFile.get("keyStorePassword").asText().toCharArray(); + } else { + throw new IllegalStateException("Invalid config.json: missing field keyStorePassword"); + } + } + + protected char[] getTrustStorePassword(JsonNode configFile) { + if (configFile.has("trustStorePassword")) { + return configFile.get("trustStorePassword").asText().toCharArray(); + } else { + throw new IllegalStateException("Invalid config.json: missing field trustStorePassword"); + } + } + + protected URL getMetadataServiceUrl(JsonNode configFile) throws MalformedURLException { + if (configFile.has("host")) { + String metadataServiceHost = configFile.get("host").asText(); + if (configFile.has("port")) { + int metadataServicePort = configFile.get("port").asInt(); + return new URL("https", metadataServiceHost, metadataServicePort, "/metadata"); + } else { + throw new IllegalStateException("Invalid config.json: missing field port"); + } + } else { + throw new IllegalStateException("Invalid config.json: missing field host"); + } + } + + protected AuthProvider getAuthProvider(JsonNode configFile) { + if (configFile.has("username")) { + String username = configFile.get("username").asText(); + if (configFile.has("password")) { + String password = configFile.get("password").asText(); + return new PlainTextAuthProvider(username, password); + } + } + return null; + } + + protected SSLContext createSslContext( + ByteArrayInputStream keyStoreInputStream, + char[] keyStorePassword, + ByteArrayInputStream trustStoreInputStream, + char[] trustStorePassword) + throws IOException, GeneralSecurityException { + KeyManagerFactory kmf = createKeyManagerFactory(keyStoreInputStream, keyStorePassword); + TrustManagerFactory tmf = createTrustManagerFactory(trustStoreInputStream, trustStorePassword); + SSLContext sslContext = SSLContext.getInstance("SSL"); + sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); + return sslContext; + } + + protected KeyManagerFactory createKeyManagerFactory( + InputStream keyStoreInputStream, char[] keyStorePassword) + throws IOException, GeneralSecurityException { + KeyStore ks = KeyStore.getInstance("JKS"); + ks.load(keyStoreInputStream, keyStorePassword); + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(ks, keyStorePassword); + Arrays.fill(keyStorePassword, (char) 0); + return kmf; + } + + protected TrustManagerFactory createTrustManagerFactory( + InputStream trustStoreInputStream, char[] trustStorePassword) + throws IOException, GeneralSecurityException { + KeyStore ts = KeyStore.getInstance("JKS"); + ts.load(trustStoreInputStream, trustStorePassword); + TrustManagerFactory tmf = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(ts); + Arrays.fill(trustStorePassword, (char) 0); + return tmf; + } + + protected BufferedReader fetchProxyMetadata(URL metadataServiceUrl, SSLContext sslContext) + throws IOException { + HttpsURLConnection connection = (HttpsURLConnection) metadataServiceUrl.openConnection(); + connection.setSSLSocketFactory(sslContext.getSocketFactory()); + connection.setRequestMethod("GET"); + return new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF_8)); + } + + protected String getLocalDatacenter(JsonNode proxyMetadata) { + JsonNode contactInfo = getContactInfo(proxyMetadata); + if (contactInfo.has("local_dc")) { + return contactInfo.get("local_dc").asText(); + } else { + throw new IllegalStateException("Invalid proxy metadata: missing field local_dc"); + } + } + + protected InetSocketAddress getSniProxyAddress(JsonNode proxyMetadata) { + JsonNode contactInfo = getContactInfo(proxyMetadata); + if (contactInfo.has("sni_proxy_address")) { + HostAndPort sniProxyHostAndPort = + HostAndPort.fromString(contactInfo.get("sni_proxy_address").asText()); + if (!sniProxyHostAndPort.hasPort()) { + throw new IllegalStateException( + "Invalid proxy metadata: missing port from field sni_proxy_address"); + } + String host = GuavaCompatibility.INSTANCE.getHost(sniProxyHostAndPort); + return InetSocketAddress.createUnresolved(host, sniProxyHostAndPort.getPort()); + } else { + throw new IllegalStateException("Invalid proxy metadata: missing field sni_proxy_address"); + } + } + + protected List getEndPoints(JsonNode proxyMetadata, InetSocketAddress sniProxyAddress) { + JsonNode contactInfo = getContactInfo(proxyMetadata); + if (contactInfo.has("contact_points")) { + List endPoints = new ArrayList(); + JsonNode hostIdsJson = contactInfo.get("contact_points"); + for (int i = 0; i < hostIdsJson.size(); i++) { + endPoints.add(new SniEndPoint(sniProxyAddress, hostIdsJson.get(i).asText())); + } + return endPoints; + } else { + throw new IllegalStateException("Invalid proxy metadata: missing field contact_points"); + } + } + + protected JsonNode getContactInfo(JsonNode proxyMetadata) { + if (proxyMetadata.has("contact_info")) { + return proxyMetadata.get("contact_info"); + } else { + throw new IllegalStateException("Invalid proxy metadata: missing field contact_info"); + } + } + + protected SSLOptions getSSLOptions(SSLContext sslContext) { + try { + return SniSSLOptions.builder().withSSLContext(sslContext).build(); + } catch (Exception e) { + throw Throwables.propagate(e); + } + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/Cluster.java b/driver-core/src/main/java/com/datastax/driver/core/Cluster.java index b89e4c71c88..9c95f391ed5 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Cluster.java +++ b/driver-core/src/main/java/com/datastax/driver/core/Cluster.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -53,14 +55,21 @@ import com.google.common.util.concurrent.SettableFuture; import com.google.common.util.concurrent.Uninterruptibles; import java.io.Closeable; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; import java.net.InetAddress; import java.net.InetSocketAddress; +import java.net.MalformedURLException; +import java.net.URL; import java.net.UnknownHostException; +import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -141,8 +150,7 @@ public class Cluster implements Closeable { * @param contactPoints the list of contact points to use for the new cluster. * @param configuration the configuration for the new cluster. */ - protected Cluster( - String name, List contactPoints, Configuration configuration) { + protected Cluster(String name, List contactPoints, Configuration configuration) { this(name, contactPoints, configuration, Collections.emptySet()); } @@ -164,7 +172,7 @@ protected Cluster(Initializer initializer) { initializer.getInitialListeners()); } - private static List checkNotEmpty(List contactPoints) { + private static List checkNotEmpty(List contactPoints) { if (contactPoints.isEmpty()) throw new IllegalArgumentException("Cannot build a cluster without contact points"); return contactPoints; @@ -172,7 +180,7 @@ private static List checkNotEmpty(List con private Cluster( String name, - List contactPoints, + List contactPoints, Configuration configuration, Collection listeners) { this.manager = new Manager(name, contactPoints, configuration, listeners); @@ -258,7 +266,7 @@ public static String getDriverVersion() { */ public static void logDriverVersion() { Logger core = LoggerFactory.getLogger("com.datastax.driver.core"); - core.info("DataStax Java driver {} for Apache Cassandra", getDriverVersion()); + core.info("Java Driver {} for Apache Cassandra", getDriverVersion()); } /** @@ -342,6 +350,10 @@ public Session connect(String keyspace) { * happens synchronously on the thread that called this method. Therefore it is recommended to * initialize the cluster at application startup, and not rely on this method to do it. * + *

Note that if a {@linkplain Configuration#getDefaultKeyspace() default keyspace} has been + * configured for use with a DBaaS cluster, this method will attempt to set the session keyspace + * to that keyspace, effectively behaving like {@link #connect(String)}. + * * @return a future that will complete when the session is fully initialized. * @throws NoHostAvailableException if the Cluster has not been initialized yet ({@link #init} has * not been called and this is the first connect call) and no host amongst the contact points @@ -352,7 +364,8 @@ public Session connect(String keyspace) { * @see #connect() */ public ListenableFuture connectAsync() { - return connectAsync(null); + String defaultKeyspace = getConfiguration().getDefaultKeyspace(); + return connectAsync(defaultKeyspace); } /** @@ -402,7 +415,7 @@ public ListenableFuture apply(Throwable t) throws Exception { SyntaxError e = (SyntaxError) t; t = new SyntaxError( - e.getAddress(), + e.getEndPoint(), String.format( "Error executing \"%s\" (%s). Check that your keyspace name is valid", useQuery, e.getMessage())); @@ -671,7 +684,7 @@ public interface Initializer { * @return the initial Cassandra contact points. See {@link Builder#addContactPoint} for more * details on contact points. */ - public List getContactPoints(); + public List getContactPoints(); /** * The configuration to use for the new cluster. @@ -707,8 +720,10 @@ public interface Initializer { public static class Builder implements Initializer { private String clusterName; - private final List addresses = new ArrayList(); - private final List rawAddresses = new ArrayList(); + private final List rawHostAndPortContactPoints = + new ArrayList(); + private final List rawHostContactPoints = new ArrayList(); + private final List contactPoints = new ArrayList(); private int port = ProtocolOptions.DEFAULT_PORT; private int maxSchemaAgreementWaitSeconds = ProtocolOptions.DEFAULT_MAX_SCHEMA_AGREEMENT_WAIT_SECONDS; @@ -724,6 +739,7 @@ public static class Builder implements Initializer { private boolean jmxEnabled = true; private boolean allowBetaProtocolVersion = false; private boolean noCompact = false; + private boolean isCloud = false; private Collection listeners; @@ -733,13 +749,18 @@ public String getClusterName() { } @Override - public List getContactPoints() { - if (rawAddresses.isEmpty()) return addresses; - - List allAddresses = new ArrayList(addresses); - for (InetAddress address : rawAddresses) - allAddresses.add(new InetSocketAddress(address, port)); - return allAddresses; + public List getContactPoints() { + // Use a set to remove duplicate endpoints + Set allContactPoints = new LinkedHashSet(contactPoints); + // If contact points were provided as InetAddress/InetSocketAddress, assume the default + // endpoint factory is used. + for (InetAddress address : rawHostContactPoints) { + allContactPoints.add(new TranslatedAddressEndPoint(new InetSocketAddress(address, port))); + } + for (InetSocketAddress socketAddress : rawHostAndPortContactPoints) { + allContactPoints.add(new TranslatedAddressEndPoint(socketAddress)); + } + return new ArrayList(allContactPoints); } /** @@ -913,16 +934,31 @@ public Builder addContactPoint(String address) { // We explicitly check for nulls because InetAdress.getByName() will happily // accept it and use localhost (while a null here almost likely mean a user error, // not "connect to localhost") + failIfCloud(); if (address == null) throw new NullPointerException(); try { - addContactPoints(InetAddress.getAllByName(address)); + InetAddress[] allByName = InetAddress.getAllByName(address); + Collections.addAll(this.rawHostContactPoints, allByName); return this; } catch (UnknownHostException e) { throw new IllegalArgumentException("Failed to add contact point: " + address, e); } } + /** + * Adds a contact point using the given connection information. + * + *

You only need this method if you use a custom connection mechanism and have configured a + * custom {@link EndPointFactory}; otherwise, you can safely ignore it and use the higher level, + * host-and-port-based variants such as {@link #addContactPoint(String)}. + */ + public Builder addContactPoint(EndPoint contactPoint) { + failIfCloud(); + contactPoints.add(contactPoint); + return this; + } + /** * Adds contact points. * @@ -959,7 +995,8 @@ public Builder addContactPoints(String... addresses) { * @see Builder#addContactPoint */ public Builder addContactPoints(InetAddress... addresses) { - Collections.addAll(this.rawAddresses, addresses); + failIfCloud(); + Collections.addAll(this.rawHostContactPoints, addresses); return this; } @@ -973,7 +1010,8 @@ public Builder addContactPoints(InetAddress... addresses) { * @see Builder#addContactPoint */ public Builder addContactPoints(Collection addresses) { - this.rawAddresses.addAll(addresses); + failIfCloud(); + this.rawHostContactPoints.addAll(addresses); return this; } @@ -996,7 +1034,8 @@ public Builder addContactPoints(Collection addresses) { * @see Builder#addContactPoint */ public Builder addContactPointsWithPorts(InetSocketAddress... addresses) { - Collections.addAll(this.addresses, addresses); + failIfCloud(); + Collections.addAll(this.rawHostAndPortContactPoints, addresses); return this; } @@ -1019,7 +1058,8 @@ public Builder addContactPointsWithPorts(InetSocketAddress... addresses) { * @see Builder#addContactPoint */ public Builder addContactPointsWithPorts(Collection addresses) { - this.addresses.addAll(addresses); + failIfCloud(); + this.rawHostAndPortContactPoints.addAll(addresses); return this; } @@ -1112,6 +1152,18 @@ public Builder withSpeculativeExecutionPolicy(SpeculativeExecutionPolicy policy) return this; } + /** + * Configures the endpoint factory to use for the new cluster. + * + *

This is a low-level component for advanced scenarios where connecting to a node requires + * more than its socket address. If you're simply using host+port, the default factory is + * sufficient. + */ + public Builder withEndPointFactory(EndPointFactory endPointFactory) { + policiesBuilder.withEndPointFactory(endPointFactory); + return this; + } + /** * Configures the {@link CodecRegistry} instance to use for the new cluster. * @@ -1325,6 +1377,122 @@ public Builder withNoCompact() { return this; } + /** + * Configures this Builder for Cloud deployments by retrieving connection information from the + * provided {@link String}. + * + *

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. + * + *

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

Note that the provided stream will be consumed and closed when this method will + * return; attempting to reuse it afterwards will result in an error being thrown. + * + * @param cloudConfigFile File that contains secure connect bundle zip file. + * @see #withCloudSecureConnectBundle(URL) + * @see #withCloudSecureConnectBundle(InputStream) + */ + public Builder withCloudSecureConnectBundle(File cloudConfigFile) { + try { + return withCloudSecureConnectBundle(cloudConfigFile.toURI().toURL()); + } catch (MalformedURLException e) { + throw new IllegalArgumentException( + "The cloudConfigFile URL " + cloudConfigFile + " is in the wrong format.", e); + } + } + + /** + * Configures this Builder for Cloud deployments by retrieving connection information from 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. + * + *

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

Note that the provided stream will be consumed and closed when this method will + * return; attempting to reuse it afterwards will result in an error being thrown. + * + * @param cloudConfigUrl URL to the secure connect bundle zip file. + * @see #withCloudSecureConnectBundle(File) + * @see #withCloudSecureConnectBundle(InputStream) + */ + public Builder withCloudSecureConnectBundle(URL cloudConfigUrl) { + CloudConfig cloudConfig; + try { + cloudConfig = new CloudConfigFactory().createCloudConfig(cloudConfigUrl.openStream()); + } catch (GeneralSecurityException e) { + throw new IllegalStateException( + "Cannot construct cloud config from the cloudConfigUrl: " + cloudConfigUrl, e); + } catch (IOException e) { + throw new IllegalStateException( + "Cannot construct cloud config from the cloudConfigUrl: " + cloudConfigUrl, e); + } + + return addCloudConfigToBuilder(cloudConfig); + } + + /** + * Configures this Builder for Cloud deployments by retrieving connection information from 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. + * + *

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

Note that the provided stream will be consumed and closed when this method will + * return; attempting to reuse it afterwards will result in an error being thrown. + * + * @param cloudConfigInputStream A stream containing the secure connect bundle zip file. + * @see #withCloudSecureConnectBundle(File) + * @see #withCloudSecureConnectBundle(URL) + */ + public Builder withCloudSecureConnectBundle(InputStream cloudConfigInputStream) { + CloudConfig cloudConfig; + try { + cloudConfig = new CloudConfigFactory().createCloudConfig(cloudConfigInputStream); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("Cannot construct cloud config from the InputStream.", e); + } catch (IOException e) { + throw new IllegalStateException("Cannot construct cloud config from the InputStream.", e); + } + + return addCloudConfigToBuilder(cloudConfig); + } + + private Builder addCloudConfigToBuilder(CloudConfig cloudConfig) { + Builder builder = + withEndPointFactory(new SniEndPointFactory(cloudConfig.getProxyAddress())) + .withSSL(cloudConfig.getSslOptions()); + + if (cloudConfig.getAuthProvider() != null) { + builder = builder.withAuthProvider(cloudConfig.getAuthProvider()); + } + if (builder.rawHostContactPoints.size() > 0 + || builder.rawHostAndPortContactPoints.size() > 0 + || builder.contactPoints.size() > 0) { + throw new IllegalStateException( + "Can't use withCloudSecureConnectBundle if you've already called addContactPoint(s)"); + } + for (EndPoint endPoint : cloudConfig.getEndPoints()) { + builder.addContactPoint(endPoint); + } + isCloud = true; + return builder; + } + + private void failIfCloud() { + if (isCloud) { + throw new IllegalStateException( + "Can't use addContactPoint(s) if you've already called withCloudSecureConnectBundle"); + } + } + /** * The configuration that will be used for the new cluster. * @@ -1394,7 +1562,7 @@ class Manager implements Connection.DefaultResponseHandler { private volatile boolean isFullyInit; private Exception initException; // Initial contacts point - final List contactPoints; + final List contactPoints; final Set sessions = new CopyOnWriteArraySet(); Metadata metadata; @@ -1440,7 +1608,7 @@ class Manager implements Connection.DefaultResponseHandler { private Manager( String clusterName, - List contactPoints, + List contactPoints, Configuration configuration, Collection listeners) { this.clusterName = clusterName == null ? generateClusterName() : clusterName; @@ -1553,39 +1721,34 @@ long delayMs() { this.scheduledTasksExecutor.scheduleWithFixedDelay( new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS); - for (InetSocketAddress address : contactPoints) { - // We don't want to signal -- call onAdd() -- because nothing is ready - // yet (loadbalancing policy, control connection, ...). All we want is - // create the Host object so we can initialize the control connection. - metadata.addIfAbsent(metadata.newHost(address)); + for (EndPoint contactPoint : contactPoints) { + metadata.addContactPoint(contactPoint); } - - Collection allHosts = metadata.allHosts(); - - // At this stage, metadata.allHosts() only contains the contact points, that's what we want - // to - // pass to LBP.init(). - // But the control connection will initialize first and discover more hosts, so make a copy. - Set contactPointHosts = Sets.newHashSet(allHosts); - + // Initialize the control connection: negotiateProtocolVersionAndConnect(); - - // The control connection can mark hosts down if it failed to connect to them, or remove - // them if they weren't found - // in the control host's system.peers. Separate them: + if (controlConnection.isCloud() && !configuration.getQueryOptions().isConsistencySet()) { + configuration.getQueryOptions().setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM); + } + // The control connection: + // - marked contact points down if they couldn't be reached + // - triggered an initial full refresh of metadata.allHosts. If any contact points weren't + // valid, they won't appear in it. Set downContactPointHosts = Sets.newHashSet(); Set removedContactPointHosts = Sets.newHashSet(); - for (Host host : contactPointHosts) { - if (!allHosts.contains(host)) removedContactPointHosts.add(host); - else if (host.state == Host.State.DOWN) downContactPointHosts.add(host); + for (Host contactPoint : metadata.getContactPoints()) { + if (!metadata.allHosts().contains(contactPoint)) { + removedContactPointHosts.add(contactPoint); + } else if (contactPoint.state == Host.State.DOWN) { + downContactPointHosts.add(contactPoint); + } } - contactPointHosts.removeAll(removedContactPointHosts); - contactPointHosts.removeAll(downContactPointHosts); // Now that the control connection is ready, we have all the information we need about the - // nodes (datacenter, - // rack...) to initialize the load balancing policy - loadBalancingPolicy().init(Cluster.this, contactPointHosts); + // nodes (datacenter, rack...) to initialize the load balancing policy + Set lbpContactPoints = Sets.newHashSet(metadata.getContactPoints()); + lbpContactPoints.removeAll(removedContactPointHosts); + lbpContactPoints.removeAll(downContactPointHosts); + loadBalancingPolicy().init(Cluster.this, lbpContactPoints); speculativeExecutionPolicy().init(Cluster.this); configuration.getPolicies().getRetryPolicy().init(Cluster.this); @@ -1606,7 +1769,7 @@ long delayMs() { configuration.getPoolingOptions().setProtocolVersion(protocolVersion()); - for (Host host : allHosts) { + for (Host host : metadata.allHosts()) { // If the host is down at this stage, it's a contact point that the control connection // failed to reach. // Reconnection attempts are already scheduled, and the LBP and listeners have been @@ -1625,7 +1788,7 @@ long delayMs() { continue; } - if (!contactPointHosts.contains(host)) loadBalancingPolicy().onAdd(host); + if (!lbpContactPoints.contains(host)) loadBalancingPolicy().onAdd(host); host.setUp(); @@ -1717,10 +1880,22 @@ boolean removeSession(Session session) { void reportQuery(Host host, Statement statement, Exception exception, long latencyNanos) { for (LatencyTracker tracker : latencyTrackers) { - tracker.update(host, statement, exception, latencyNanos); + try { + tracker.update(host, statement, exception, latencyNanos); + } catch (Exception e) { + logger.error("Call to latency tracker failed", e); + } } } + ControlConnection getControlConnection() { + return controlConnection; + } + + List getContactPoints() { + return contactPoints; + } + boolean isClosed() { return closeFuture.get() != null; } @@ -2565,30 +2740,31 @@ public void handle(Message.Response response) { switch (event.type) { case TOPOLOGY_CHANGE: ProtocolEvent.TopologyChange tpc = (ProtocolEvent.TopologyChange) event; - InetSocketAddress tpAddr = translateAddress(tpc.node.getAddress()); - Host.statesLogger.debug("[{}] received event {}", tpAddr, tpc.change); + Host.statesLogger.debug("[{}] received event {}", tpc.node, tpc.change); + // Do NOT translate the address, it will be matched against Host.getBroadcastRpcAddress() + // to find the target host. switch (tpc.change) { - case NEW_NODE: - submitNodeRefresh(tpAddr, HostEvent.ADDED); - break; case REMOVED_NODE: - submitNodeRefresh(tpAddr, HostEvent.REMOVED); + submitNodeRefresh(tpc.node, HostEvent.REMOVED); break; - case MOVED_NODE: + default: + // If a node was added, we don't have enough information to create a new Host (we are + // missing it's ID) so trigger a full refresh submitNodeListRefresh(); break; } break; case STATUS_CHANGE: ProtocolEvent.StatusChange stc = (ProtocolEvent.StatusChange) event; - InetSocketAddress stAddr = translateAddress(stc.node.getAddress()); - Host.statesLogger.debug("[{}] received event {}", stAddr, stc.status); + Host.statesLogger.debug("[{}] received event {}", stc.node, stc.status); + // Do NOT translate the address, it will be matched against Host.getBroadcastRpcAddress() + // to find the target host. switch (stc.status) { case UP: - submitNodeRefresh(stAddr, HostEvent.UP); + submitNodeRefresh(stc.node, HostEvent.UP); break; case DOWN: - submitNodeRefresh(stAddr, HostEvent.DOWN); + submitNodeRefresh(stc.node, HostEvent.DOWN); break; } break; @@ -2909,27 +3085,13 @@ public ListenableFuture deliver(List events) { case UP: Host upHost = metadata.getHost(address); if (upHost == null) { - upHost = metadata.newHost(address); - Host previous = metadata.addIfAbsent(upHost); - if (previous != null) { - // We got beat by another thread at adding the host. Let it win and ignore the - // notification here. - continue; - } - futures.add(schedule(hostAdded(upHost))); + // We don't have enough information to create a new Host (we are missing it's ID) + // so trigger a full node refresh + submitNodeListRefresh(); } else { futures.add(schedule(hostUp(upHost))); } break; - case ADDED: - Host newHost = metadata.newHost(address); - Host previous = metadata.addIfAbsent(newHost); - if (previous == null) { - futures.add(schedule(hostAdded(newHost))); - } else if (!previous.isUp()) { - futures.add(schedule(hostUp(previous))); - } - break; case DOWN: // Note that there is a slight risk we can receive the event late and thus // mark the host down even though we already had reconnected successfully. @@ -3000,28 +3162,13 @@ public void onFailure(Throwable t) { } } - // Make sure we call controlConnection.refreshNodeInfo(host) - // so that we have up-to-date infos on that host before adding it (so we typically - // catch that an upgraded node uses a new cassandra version). - - private ExceptionCatchingRunnable hostAdded(final Host host) { - return new ExceptionCatchingRunnable() { - @Override - public void runMayThrow() throws Exception { - if (controlConnection.refreshNodeInfo(host)) { - onAdd(host, null); - submitNodeListRefresh(); - } else { - logger.debug("Not enough info for {}, ignoring host", host); - } - } - }; - } - private ExceptionCatchingRunnable hostUp(final Host host) { return new ExceptionCatchingRunnable() { @Override public void runMayThrow() throws Exception { + // Make sure we call controlConnection.refreshNodeInfo(host) + // so that we have up-to-date infos on that host before recreating the pools (so we + // typically catch that an upgraded node uses a new cassandra version). if (controlConnection.refreshNodeInfo(host)) { onUp(host, null); } else { @@ -3082,7 +3229,6 @@ public void runMayThrow() throws InterruptedException, ExecutionException { private enum HostEvent { UP, DOWN, - ADDED, REMOVED } diff --git a/driver-core/src/main/java/com/datastax/driver/core/ClusterNameMismatchException.java b/driver-core/src/main/java/com/datastax/driver/core/ClusterNameMismatchException.java index 219cd6975f8..b7154cf5b68 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ClusterNameMismatchException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -15,8 +17,6 @@ */ package com.datastax.driver.core; -import java.net.InetSocketAddress; - /** * Indicates that we've attempted to connect to a node which cluster name doesn't match that of the * other nodes known to the driver. @@ -25,17 +25,17 @@ class ClusterNameMismatchException extends Exception { private static final long serialVersionUID = 0; - public final InetSocketAddress address; + public final EndPoint endPoint; public final String expectedClusterName; public final String actualClusterName; public ClusterNameMismatchException( - InetSocketAddress address, String actualClusterName, String expectedClusterName) { + EndPoint endPoint, String actualClusterName, String expectedClusterName) { super( String.format( "[%s] Host %s reports cluster name '%s' that doesn't match our cluster name '%s'. This host will be ignored.", - address, address, actualClusterName, expectedClusterName)); - this.address = address; + endPoint, endPoint, actualClusterName, expectedClusterName)); + this.endPoint = endPoint; this.expectedClusterName = expectedClusterName; this.actualClusterName = actualClusterName; } diff --git a/driver-core/src/main/java/com/datastax/driver/core/ClusterWidePercentileTracker.java b/driver-core/src/main/java/com/datastax/driver/core/ClusterWidePercentileTracker.java index bc0dd7ecd37..dca97e12300 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ClusterWidePercentileTracker.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ClusterWidePercentileTracker.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/ClusteringOrder.java b/driver-core/src/main/java/com/datastax/driver/core/ClusteringOrder.java index 0cf79e64300..38309ee64af 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ClusteringOrder.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/CodecRegistry.java b/driver-core/src/main/java/com/datastax/driver/core/CodecRegistry.java index 701d2e9a09a..04208576924 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/CodecRegistry.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -460,7 +462,7 @@ public CodecRegistry register(Iterable> codecs) { * *

Furthermore, this method returns the first matching codec, regardless of its accepted CQL * type. It should be reserved for situations where the target CQL type is not available or - * unknown. In the Java driver, this happens mainly when serializing a value in a {@link + * unknown. In the Java Driver, this happens mainly when serializing a value in a {@link * SimpleStatement#SimpleStatement(String, Object...) SimpleStatement} or in the {@link * com.datastax.driver.core.querybuilder.QueryBuilder}, where no CQL type information is * available. diff --git a/driver-core/src/main/java/com/datastax/driver/core/CodecUtils.java b/driver-core/src/main/java/com/datastax/driver/core/CodecUtils.java index 94295a0bb14..6f9ee1e58a8 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/CodecUtils.java +++ b/driver-core/src/main/java/com/datastax/driver/core/CodecUtils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,6 +66,7 @@ public static int readSize(ByteBuffer input, ProtocolVersion version) { case V3: case V4: case V5: + case V6: return input.getInt(); default: throw version.unsupported(); @@ -92,6 +95,7 @@ public static void writeSize(ByteBuffer output, int size, ProtocolVersion versio case V3: case V4: case V5: + case V6: output.putInt(size); break; default: @@ -131,6 +135,7 @@ public static void writeValue(ByteBuffer output, ByteBuffer value, ProtocolVersi case V3: case V4: case V5: + case V6: if (value == null) { output.putInt(-1); } else { @@ -217,6 +222,7 @@ private static int sizeOfCollectionSize(ProtocolVersion version) { case V3: case V4: case V5: + case V6: return 4; default: throw version.unsupported(); @@ -237,6 +243,7 @@ private static int sizeOfValue(ByteBuffer value, ProtocolVersion version) { case V3: case V4: case V5: + case V6: return value == null ? 4 : 4 + value.remaining(); default: throw version.unsupported(); diff --git a/driver-core/src/main/java/com/datastax/driver/core/ColumnDefinitions.java b/driver-core/src/main/java/com/datastax/driver/core/ColumnDefinitions.java index e2ed07fe16c..0b3317e3caf 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ColumnDefinitions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java b/driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java index cd27231010c..67e05ecdc43 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/Configuration.java b/driver-core/src/main/java/com/datastax/driver/core/Configuration.java index 26fc9b8d6ad..e500e3c3167 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Configuration.java +++ b/driver-core/src/main/java/com/datastax/driver/core/Configuration.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,9 @@ package com.datastax.driver.core; import com.datastax.driver.core.policies.Policies; +import com.google.common.base.Joiner; +import java.util.ArrayList; +import java.util.List; /** * The configuration of the cluster. It configures the following: @@ -55,6 +60,7 @@ public static Builder builder() { private final ThreadingOptions threadingOptions; private final NettyOptions nettyOptions; private final CodecRegistry codecRegistry; + private final String defaultKeyspace; private Configuration( Policies policies, @@ -65,7 +71,8 @@ private Configuration( QueryOptions queryOptions, ThreadingOptions threadingOptions, NettyOptions nettyOptions, - CodecRegistry codecRegistry) { + CodecRegistry codecRegistry, + String defaultKeyspace) { this.policies = policies; this.protocolOptions = protocolOptions; this.poolingOptions = poolingOptions; @@ -75,6 +82,7 @@ private Configuration( this.threadingOptions = threadingOptions; this.nettyOptions = nettyOptions; this.codecRegistry = codecRegistry; + this.defaultKeyspace = defaultKeyspace; } /** @@ -92,13 +100,45 @@ protected Configuration(Configuration toCopy) { toCopy.getQueryOptions(), toCopy.getThreadingOptions(), toCopy.getNettyOptions(), - toCopy.getCodecRegistry()); + toCopy.getCodecRegistry(), + toCopy.getDefaultKeyspace()); } void register(Cluster.Manager manager) { protocolOptions.register(manager); poolingOptions.register(manager); queryOptions.register(manager); + policies.getEndPointFactory().init(manager.getCluster()); + + checkPoliciesIfSni(); + } + + // If using SNI endpoints, the SSL options and auth provider MUST be the "extended" versions, the + // base versions work with IP addresses that might not be unique to a node. + // Throw now since that's probably a configuration error. + private void checkPoliciesIfSni() { + if (policies.getEndPointFactory() instanceof SniEndPointFactory) { + SSLOptions sslOptions = protocolOptions.getSSLOptions(); + List errors = new ArrayList(); + if (sslOptions != null && !(sslOptions instanceof ExtendedRemoteEndpointAwareSslOptions)) { + errors.add( + String.format( + "the configured %s must implement %s", + SSLOptions.class.getSimpleName(), + ExtendedRemoteEndpointAwareSslOptions.class.getSimpleName())); + } + AuthProvider authProvider = protocolOptions.getAuthProvider(); + if (authProvider != null && !(authProvider instanceof ExtendedAuthProvider)) { + errors.add( + String.format( + "the configured %s must implement %s", + AuthProvider.class.getSimpleName(), ExtendedAuthProvider.class.getSimpleName())); + } + if (!errors.isEmpty()) { + throw new IllegalStateException( + "Configuration error: if SNI endpoints are in use, " + Joiner.on(',').join(errors)); + } + } } /** @@ -172,6 +212,9 @@ public NettyOptions getNettyOptions() { return nettyOptions; } + public String getDefaultKeyspace() { + return defaultKeyspace; + } /** * Returns the {@link CodecRegistry} instance for this configuration. * @@ -197,6 +240,7 @@ public static class Builder { private ThreadingOptions threadingOptions; private NettyOptions nettyOptions; private CodecRegistry codecRegistry; + private String defaultKeyspace; /** * Sets the policies for this cluster. @@ -301,6 +345,11 @@ public Builder withCodecRegistry(CodecRegistry codecRegistry) { return this; } + public Builder withDefaultKeyspace(String keyspace) { + this.defaultKeyspace = keyspace; + return this; + } + /** * Builds the final object from this builder. * @@ -318,7 +367,8 @@ public Configuration build() { queryOptions != null ? queryOptions : new QueryOptions(), threadingOptions != null ? threadingOptions : new ThreadingOptions(), nettyOptions != null ? nettyOptions : NettyOptions.DEFAULT_INSTANCE, - codecRegistry != null ? codecRegistry : CodecRegistry.DEFAULT_INSTANCE); + codecRegistry != null ? codecRegistry : CodecRegistry.DEFAULT_INSTANCE, + defaultKeyspace); } } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/Connection.java b/driver-core/src/main/java/com/datastax/driver/core/Connection.java index bf9c4ab5f84..b75d31dc29c 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Connection.java +++ b/driver-core/src/main/java/com/datastax/driver/core/Connection.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 @@ import com.datastax.driver.core.exceptions.AuthenticationException; import com.datastax.driver.core.exceptions.BusyConnectionException; import com.datastax.driver.core.exceptions.ConnectionException; +import com.datastax.driver.core.exceptions.CrcMismatchException; import com.datastax.driver.core.exceptions.DriverException; import com.datastax.driver.core.exceptions.DriverInternalError; import com.datastax.driver.core.exceptions.FrameTooLongException; @@ -65,7 +68,6 @@ import io.netty.util.TimerTask; import io.netty.util.concurrent.GlobalEventExecutor; import java.lang.ref.WeakReference; -import java.net.InetSocketAddress; import java.util.HashSet; import java.util.Iterator; import java.util.List; @@ -96,8 +98,6 @@ class Connection { SystemProperties.getBoolean("com.datastax.driver.DISABLE_COALESCING", false); private static final int FLUSHER_SCHEDULE_PERIOD_NS = SystemProperties.getInt("com.datastax.driver.FLUSHER_SCHEDULE_PERIOD_NS", 10000); - private static final int FLUSHER_RUN_WITHOUT_WORK_TIMES = - SystemProperties.getInt("com.datastax.driver.FLUSHER_RUN_WITHOUT_WORK_TIMES", 5); enum State { OPEN, @@ -110,7 +110,7 @@ enum State { volatile long maxIdleTime; - final InetSocketAddress address; + final EndPoint endPoint; private final String name; @VisibleForTesting volatile Channel channel; @@ -139,13 +139,13 @@ enum State { * Create a new connection to a Cassandra node and associate it with the given pool. * * @param name the connection name - * @param address the remote address + * @param endPoint the information to connect to the node * @param factory the connection factory to use * @param owner the component owning this connection (may be null). Note that an existing * connection can also be associated to an owner later with {@link #setOwner(Owner)}. */ - protected Connection(String name, InetSocketAddress address, Factory factory, Owner owner) { - this.address = address; + protected Connection(String name, EndPoint endPoint, Factory factory, Owner owner) { + this.endPoint = endPoint; this.factory = factory; this.dispatcher = new Dispatcher(); this.name = name; @@ -156,14 +156,14 @@ protected Connection(String name, InetSocketAddress address, Factory factory, Ow } /** Create a new connection to a Cassandra node. */ - Connection(String name, InetSocketAddress address, Factory factory) { - this(name, address, factory, null); + Connection(String name, EndPoint endPoint, Factory factory) { + this(name, endPoint, factory, null); } ListenableFuture initAsync() { if (factory.isShutdown) return Futures.immediateFailedFuture( - new ConnectionException(address, "Connection factory is shut down")); + new ConnectionException(endPoint, "Connection factory is shut down")); ProtocolVersion protocolVersion = factory.protocolVersion == null @@ -187,7 +187,7 @@ ListenableFuture initAsync() { ? factory.manager.metrics : null)); - ChannelFuture future = bootstrap.connect(address); + ChannelFuture future = bootstrap.connect(endPoint.resolve()); writer.incrementAndGet(); future.addListener( @@ -195,8 +195,10 @@ ListenableFuture initAsync() { @Override public void operationComplete(ChannelFuture future) throws Exception { writer.decrementAndGet(); + // Note: future.channel() can be null in some error cases, so we need to guard against + // it in the rest of the code below. channel = future.channel(); - if (isClosed()) { + if (isClosed() && channel != null) { channel .close() .addListener( @@ -205,24 +207,27 @@ public void operationComplete(ChannelFuture future) throws Exception { public void operationComplete(ChannelFuture future) throws Exception { channelReadyFuture.setException( new TransportException( - Connection.this.address, + Connection.this.endPoint, "Connection closed during initialization.")); } }); } else { - Connection.this.factory.allChannels.add(channel); + if (channel != null) { + Connection.this.factory.allChannels.add(channel); + } if (!future.isSuccess()) { if (logger.isDebugEnabled()) logger.debug( String.format( "%s Error connecting to %s%s", Connection.this, - Connection.this.address, + Connection.this.endPoint, extractMessage(future.cause()))); channelReadyFuture.setException( new TransportException( - Connection.this.address, "Cannot connect", future.cause())); + Connection.this.endPoint, "Cannot connect", future.cause())); } else { + assert channel != null; logger.debug( "{} Connection established, initializing transport", Connection.this); channel.closeFuture().addListener(new ChannelCloseListener()); @@ -266,7 +271,7 @@ public ListenableFuture apply(Throwable t) throws Exception { || t instanceof Error) ? t : new ConnectionException( - Connection.this.address, + Connection.this.endPoint, String.format( "Unexpected error during transport initialization (%s)", t), t); @@ -299,6 +304,12 @@ private static String extractMessage(Throwable t) { return " (" + msg + ')'; } + public ListenableFuture optionsQuery() { + Future startupOptionsFuture = write(new Requests.Options()); + + return GuavaCompatibility.INSTANCE.transformAsync(startupOptionsFuture, onSupportedResponse()); + } + private AsyncFunction onChannelReady( final ProtocolVersion protocolVersion, final Executor initExecutor) { return new AsyncFunction() { @@ -315,6 +326,28 @@ public ListenableFuture apply(Void input) throws Exception { }; } + private AsyncFunction onSupportedResponse() { + return new AsyncFunction() { + @Override + public ListenableFuture apply(Message.Response response) throws Exception { + switch (response.type) { + case SUPPORTED: + return getProductType((Responses.Supported) response); + case ERROR: + Responses.Error error = (Responses.Error) response; + throw new TransportException( + endPoint, String.format("Error initializing connection: %s", error.message)); + default: + throw new TransportException( + endPoint, + String.format( + "Unexpected %s response message from server to a STARTUP message", + response.type)); + } + } + }; + } + private AsyncFunction onStartupResponse( final ProtocolVersion protocolVersion, final Executor initExecutor) { return new AsyncFunction() { @@ -329,13 +362,20 @@ public ListenableFuture apply(Message.Response response) throws Exception throw unsupportedProtocolVersionException( protocolVersion, error.serverProtocolVersion); throw new TransportException( - address, String.format("Error initializing connection: %s", error.message)); + endPoint, String.format("Error initializing connection: %s", error.message)); case AUTHENTICATE: Responses.Authenticate authenticate = (Responses.Authenticate) response; Authenticator authenticator; try { - authenticator = - factory.authProvider.newAuthenticator(address, authenticate.authenticator); + if (factory.authProvider instanceof ExtendedAuthProvider) { + authenticator = + ((ExtendedAuthProvider) factory.authProvider) + .newAuthenticator(endPoint, authenticate.authenticator); + } else { + authenticator = + factory.authProvider.newAuthenticator( + endPoint.resolve(), authenticate.authenticator); + } } catch (AuthenticationException e) { incrementAuthErrorMetric(); throw e; @@ -351,13 +391,14 @@ public ListenableFuture apply(Message.Response response) throws Exception case V3: case V4: case V5: + case V6: return authenticateV2(authenticator, protocolVersion, initExecutor); default: throw defunct(protocolVersion.unsupported()); } default: throw new TransportException( - address, + endPoint, String.format( "Unexpected %s response message from server to a STARTUP message", response.type)); @@ -382,7 +423,9 @@ private ListenableFuture checkClusterName( DefaultResultSetFuture clusterNameFuture = new DefaultResultSetFuture( - null, protocolVersion, new Requests.Query("select cluster_name from system.local")); + null, + protocolVersion, + new Requests.Query("select cluster_name from system.local where key = 'local'")); try { write(clusterNameFuture); return GuavaCompatibility.INSTANCE.transformAsync( @@ -393,7 +436,7 @@ public ListenableFuture apply(ResultSet rs) throws Exception { Row row = rs.one(); String actual = row.getString("cluster_name"); if (!expected.equals(actual)) - throw new ClusterNameMismatchException(address, actual, expected); + throw new ClusterNameMismatchException(endPoint, actual, expected); markInitialized(); return MoreFutures.VOID_SUCCESS; } @@ -404,9 +447,18 @@ public ListenableFuture apply(ResultSet rs) throws Exception { } } + private ListenableFuture getProductType(Responses.Supported response) { + if (response.supported.containsKey("PRODUCT_TYPE") + && response.supported.get("PRODUCT_TYPE").size() > 0) { + return Futures.immediateFuture(response.supported.get("PRODUCT_TYPE").get(0)); + } else { + return Futures.immediateFuture(""); + } + } + private void markInitialized() { isInitialized = true; - Host.statesLogger.debug("[{}] {} Transport initialized, connection ready", address, this); + Host.statesLogger.debug("[{}] {} Transport initialized, connection ready", endPoint, this); } private ListenableFuture authenticateV1( @@ -426,10 +478,10 @@ public ListenableFuture apply(Message.Response authResponse) throws Except case ERROR: incrementAuthErrorMetric(); throw new AuthenticationException( - address, ((Responses.Error) authResponse).message); + endPoint, ((Responses.Error) authResponse).message); default: throw new TransportException( - address, + endPoint, String.format( "Unexpected %s response message from server to a CREDENTIALS message", authResponse.type)); @@ -500,10 +552,10 @@ public ListenableFuture apply(Message.Response authResponse) throws Except + "only plain text authentication is supported with this protocol version", authenticator); incrementAuthErrorMetric(); - throw new AuthenticationException(address, message); + throw new AuthenticationException(endPoint, message); default: throw new TransportException( - address, + endPoint, String.format( "Unexpected %s response message from server to authentication message", authResponse.type)); @@ -522,13 +574,15 @@ private boolean isUnsupportedProtocolVersion(Responses.Error error) { // Testing for a specific string is a tad fragile but well, we don't have much choice // C* 2.1 reports a server error instead of protocol error, see CASSANDRA-9451 return (error.code == ExceptionCode.PROTOCOL_ERROR || error.code == ExceptionCode.SERVER_ERROR) - && error.message.contains("Invalid or unsupported protocol version"); + && (error.message.contains("Invalid or unsupported protocol version") + // JAVA-2924: server is behind driver and considers the proposed version as beta + || error.message.contains("Beta version of the protocol used")); } private UnsupportedProtocolVersionException unsupportedProtocolVersionException( ProtocolVersion triedVersion, ProtocolVersion serverProtocolVersion) { UnsupportedProtocolVersionException e = - new UnsupportedProtocolVersionException(address, triedVersion, serverProtocolVersion); + new UnsupportedProtocolVersionException(endPoint, triedVersion, serverProtocolVersion); logger.debug(e.getMessage()); return e; } @@ -548,7 +602,7 @@ E defunct(E e) { else if (Host.statesLogger.isDebugEnabled()) Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage()); - Host host = factory.manager.metadata.getHost(address); + Host host = getHost(); if (host != null) { // Sometimes close() can be called before defunct(); avoid decrementing the connection count // twice, but @@ -599,7 +653,7 @@ void setKeyspace(String keyspace) throws ConnectionException { "Tried to set the keyspace on busy {}. " + "This should not happen but is not critical (it will be retried)", this); - throw new ConnectionException(address, "Tried to set the keyspace on busy connection"); + throw new ConnectionException(endPoint, "Tried to set the keyspace on busy connection"); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof OperationTimedOutException) { @@ -609,9 +663,9 @@ void setKeyspace(String keyspace) throws ConnectionException { "Timeout while setting keyspace on {}. " + "This should not happen but is not critical (it will be retried)", this); - throw new ConnectionException(address, "Timeout while setting keyspace on connection"); + throw new ConnectionException(endPoint, "Timeout while setting keyspace on connection"); } else { - throw defunct(new ConnectionException(address, "Error while setting keyspace", cause)); + throw defunct(new ConnectionException(endPoint, "Error while setting keyspace", cause)); } } } @@ -662,7 +716,7 @@ public void onSuccess(Message.Response response) { targetKeyspace.compareAndSet(attempt, defaultKeyspaceAttempt); if (response.type == ERROR) { Responses.Error error = (Responses.Error) response; - ksFuture.setException(defunct(error.asException(address))); + ksFuture.setException(defunct(error.asException(endPoint))); } else { ksFuture.setException( defunct( @@ -721,12 +775,12 @@ ResponseHandler write( */ if (isDefunct.get()) { dispatcher.removeHandler(handler, true); - throw new ConnectionException(address, "Write attempt on defunct connection"); + throw new ConnectionException(endPoint, "Write attempt on defunct connection"); } if (isClosed()) { dispatcher.removeHandler(handler, true); - throw new ConnectionException(address, "Connection has been closed"); + throw new ConnectionException(endPoint, "Connection has been closed"); } logger.trace("{}, stream {}, writing request {}", this, request.getStreamId(), request); @@ -762,9 +816,9 @@ public void operationComplete(ChannelFuture writeFuture) { final ConnectionException ce; if (writeFuture.cause() instanceof java.nio.channels.ClosedChannelException) { - ce = new TransportException(address, "Error writing: Closed channel"); + ce = new TransportException(endPoint, "Error writing: Closed channel"); } else { - ce = new TransportException(address, "Error writing", writeFuture.cause()); + ce = new TransportException(endPoint, "Error writing", writeFuture.cause()); } final long latency = System.nanoTime() - handler.startTime; // This handler is executed while holding the writeLock of the channel. @@ -805,9 +859,14 @@ boolean setOwner(Owner owner) { * If the connection is part of a pool, return it to the pool. The connection should generally not * be reused after that. */ - void release() { + void release(boolean busy) { Owner owner = ownerRef.get(); - if (owner instanceof HostConnectionPool) ((HostConnectionPool) owner).returnConnection(this); + if (owner instanceof HostConnectionPool) + ((HostConnectionPool) owner).returnConnection(this, busy); + } + + void release() { + release(false); } boolean isClosed() { @@ -836,7 +895,7 @@ CloseFuture closeAsync() { // Only signal if defunct hasn't done it already if (signaled.compareAndSet(false, true)) { - Host host = factory.manager.metadata.getHost(address); + Host host = getHost(); if (host != null) { host.convictionPolicy.signalConnectionClosed(this); } @@ -855,6 +914,16 @@ CloseFuture closeAsync() { return future; } + private Host getHost() { + Metadata metadata = factory.manager.metadata; + Host host = metadata.getHost(endPoint); + // During init the host might not be in metatada.hosts yet, try the contact points + if (host == null) { + host = metadata.getContactPoint(endPoint); + } + return host; + } + /** * Tries to terminate a closed connection, i.e. release system resources. * @@ -950,12 +1019,12 @@ int getPort() { Connection open(Host host) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { - InetSocketAddress address = host.getSocketAddress(); + EndPoint endPoint = host.getEndPoint(); - if (isShutdown) throw new ConnectionException(address, "Connection factory is shut down"); + if (isShutdown) throw new ConnectionException(endPoint, "Connection factory is shut down"); host.convictionPolicy.signalConnectionsOpening(1); - Connection connection = new Connection(buildConnectionName(host), address, this); + Connection connection = new Connection(buildConnectionName(host), endPoint, this); // This method opens the connection synchronously, so wait until it's initialized try { connection.initAsync().get(); @@ -971,7 +1040,7 @@ Connection open(HostConnectionPool pool) ClusterNameMismatchException { pool.host.convictionPolicy.signalConnectionsOpening(1); Connection connection = - new Connection(buildConnectionName(pool.host), pool.host.getSocketAddress(), this, pool); + new Connection(buildConnectionName(pool.host), pool.host.getEndPoint(), this, pool); try { connection.initAsync().get(); return connection; @@ -989,13 +1058,12 @@ List newConnections(HostConnectionPool pool, int count) { List connections = Lists.newArrayListWithCapacity(count); for (int i = 0; i < count; i++) connections.add( - new Connection( - buildConnectionName(pool.host), pool.host.getSocketAddress(), this, pool)); + new Connection(buildConnectionName(pool.host), pool.host.getEndPoint(), this, pool)); return connections; } private String buildConnectionName(Host host) { - return host.getSocketAddress().toString() + '-' + getIdGenerator(host).getAndIncrement(); + return host.getEndPoint().toString() + '-' + getIdGenerator(host).getAndIncrement(); } static RuntimeException launderAsyncInitException(ExecutionException e) @@ -1069,7 +1137,6 @@ private static final class Flusher implements Runnable { final Queue queued = new ConcurrentLinkedQueue(); final AtomicBoolean running = new AtomicBoolean(false); final HashSet channels = new HashSet(); - int runsWithNoWork = 0; private Flusher(EventLoop eventLoop) { this.eventLoopRef = new WeakReference(eventLoop); @@ -1085,14 +1152,12 @@ void start() { @Override public void run() { - boolean doneWork = false; FlushItem flush; while (null != (flush = queued.poll())) { Channel channel = flush.channel; if (channel.isActive()) { channels.add(channel); channel.write(flush.request).addListener(flush.listener); - doneWork = true; } } @@ -1100,15 +1165,9 @@ public void run() { for (Channel channel : channels) channel.flush(); channels.clear(); - if (doneWork) { - runsWithNoWork = 0; - } else { - // either reschedule or cancel - if (++runsWithNoWork > FLUSHER_RUN_WITHOUT_WORK_TIMES) { - running.set(false); - if (queued.isEmpty() || !running.compareAndSet(false, true)) return; - } - } + // either reschedule or cancel + running.set(false); + if (queued.isEmpty() || !running.compareAndSet(false, true)) return; EventLoop eventLoop = eventLoopRef.get(); if (eventLoop != null && !eventLoop.isShuttingDown()) { @@ -1277,7 +1336,7 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E // Special case, if we encountered a FrameTooLongException, raise exception on handler and // don't defunct it since // the connection is in an ok state. - if (error != null && error instanceof FrameTooLongException) { + if (error instanceof FrameTooLongException) { FrameTooLongException ftle = (FrameTooLongException) error; int streamId = ftle.getStreamId(); ResponseHandler handler = pending.remove(streamId); @@ -1296,11 +1355,14 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E handler.callback.onException( Connection.this, ftle, System.nanoTime() - handler.startTime, handler.retryCount); return; + } else if (error instanceof CrcMismatchException) { + // Fall back to the defunct call below, but we want a clear warning in the logs + logger.warn("CRC mismatch while decoding a response, dropping the connection", error); } } defunct( new TransportException( - address, String.format("Unexpected exception triggered (%s)", cause), cause)); + endPoint, String.format("Unexpected exception triggered (%s)", cause), cause)); } void errorOutAllHandler(ConnectionException ce) { @@ -1322,10 +1384,10 @@ public void operationComplete(ChannelFuture future) throws Exception { // connection, but // if there is remaining thread waiting on us, we still want to wake them up if (!isInitialized || isClosed()) { - dispatcher.errorOutAllHandler(new TransportException(address, "Channel has been closed")); + dispatcher.errorOutAllHandler(new TransportException(endPoint, "Channel has been closed")); // we still want to force so that the future completes Connection.this.closeAsync().force(); - } else defunct(new TransportException(address, "Channel has been closed")); + } else defunct(new TransportException(endPoint, "Channel has been closed")); } } @@ -1353,7 +1415,7 @@ public void onSet( fail( connection, new ConnectionException( - connection.address, "Unexpected heartbeat response: " + response)); + connection.endPoint, "Unexpected heartbeat response: " + response)); } } @@ -1366,7 +1428,8 @@ public void onException( @Override public boolean onTimeout(Connection connection, long latency, int retryCount) { fail( - connection, new ConnectionException(connection.address, "Heartbeat query timed out")); + connection, + new ConnectionException(connection.endPoint, "Heartbeat query timed out")); return true; } @@ -1394,7 +1457,7 @@ public ConnectionCloseFuture force() { // forever. In general this won't happen since we get there only when all ongoing query are // done, but this can happen // if the shutdown is forced. This is a no-op if there is no handler set anymore. - dispatcher.errorOutAllHandler(new TransportException(address, "Connection has been closed")); + dispatcher.errorOutAllHandler(new TransportException(endPoint, "Connection has been closed")); ChannelFuture future = channel.close(); future.addListener( @@ -1440,7 +1503,7 @@ public int hashCode() { static class Future extends AbstractFuture implements RequestHandler.Callback { private final Message.Request request; - private volatile InetSocketAddress address; + private volatile EndPoint endPoint; Future(Message.Request request) { this.request = request; @@ -1475,7 +1538,7 @@ public void onSet( @Override public void onSet( Connection connection, Message.Response response, long latency, int retryCount) { - this.address = connection.address; + this.endPoint = connection.endPoint; super.set(response); } @@ -1484,7 +1547,7 @@ public void onException( Connection connection, Exception exception, long latency, int retryCount) { // If all nodes are down, we will get a null connection here. This is fine, if we have // an exception, consumers shouldn't assume the address is not null. - if (connection != null) this.address = connection.address; + if (connection != null) this.endPoint = connection.endPoint; super.setException(exception); } @@ -1492,12 +1555,12 @@ public void onException( public boolean onTimeout(Connection connection, long latency, int retryCount) { assert connection != null; // We always timeout on a specific connection, so this shouldn't be null - this.address = connection.address; - return super.setException(new OperationTimedOutException(connection.address)); + this.endPoint = connection.endPoint; + return super.setException(new OperationTimedOutException(connection.endPoint)); } - InetSocketAddress getAddress() { - return address; + EndPoint getEndPoint() { + return endPoint; } } @@ -1535,7 +1598,7 @@ static class ResponseHandler { ? statementReadTimeoutMillis : connection.factory.getReadTimeoutMillis(); this.streamId = connection.dispatcher.streamIdHandler.next(); - if (streamId == -1) throw new BusyConnectionException(connection.address); + if (streamId == -1) throw new BusyConnectionException(connection.endPoint); this.callback = callback; this.retryCount = callback.retryCount(); @@ -1596,6 +1659,8 @@ private static class Initializer extends ChannelInitializer { new Message.ProtocolEncoder(ProtocolVersion.V4); private static final Message.ProtocolEncoder messageEncoderV5 = new Message.ProtocolEncoder(ProtocolVersion.V5); + private static final Message.ProtocolEncoder messageEncoderV6 = + new Message.ProtocolEncoder(ProtocolVersion.V6); private static final Frame.Encoder frameEncoder = new Frame.Encoder(); private final ProtocolVersion protocolVersion; @@ -1635,16 +1700,20 @@ protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); if (sslOptions != null) { - if (sslOptions instanceof RemoteEndpointAwareSSLOptions) { - SslHandler handler = + SslHandler handler; + if (sslOptions instanceof ExtendedRemoteEndpointAwareSslOptions) { + handler = + ((ExtendedRemoteEndpointAwareSslOptions) sslOptions) + .newSSLHandler(channel, connection.endPoint); + + } else if (sslOptions instanceof RemoteEndpointAwareSSLOptions) { + handler = ((RemoteEndpointAwareSSLOptions) sslOptions) - .newSSLHandler(channel, connection.address); - pipeline.addLast("ssl", handler); + .newSSLHandler(channel, connection.endPoint.resolve()); } else { - @SuppressWarnings("deprecation") - SslHandler handler = sslOptions.newSSLHandler(channel); - pipeline.addLast("ssl", handler); + handler = sslOptions.newSSLHandler(channel); } + pipeline.addLast("ssl", handler); } // pipeline.addLast("debug", new LoggingHandler(LogLevel.INFO)); @@ -1658,7 +1727,13 @@ protected void initChannel(SocketChannel channel) throws Exception { pipeline.addLast("frameDecoder", new Frame.Decoder()); pipeline.addLast("frameEncoder", frameEncoder); - if (compressor != null) { + pipeline.addLast("framingFormatHandler", new FramingFormatHandler(connection.factory)); + + if (compressor != null + // Frame-level compression is only done in legacy protocol versions. In V5 and above, it + // happens at a higher level ("segment" that groups multiple frames), so never install + // those handlers. + && protocolVersion.compareTo(ProtocolVersion.V5) < 0) { pipeline.addLast("frameDecompressor", new Frame.Decompressor(compressor)); pipeline.addLast("frameCompressor", new Frame.Compressor(compressor)); } @@ -1685,6 +1760,8 @@ private Message.ProtocolEncoder messageEncoderFor(ProtocolVersion version) { return messageEncoderV4; case V5: return messageEncoderV5; + case V6: + return messageEncoderV6; default: throw new DriverInternalError("Unsupported protocol version " + protocolVersion); } diff --git a/driver-core/src/main/java/com/datastax/driver/core/ConsistencyLevel.java b/driver-core/src/main/java/com/datastax/driver/core/ConsistencyLevel.java index fbe378fc263..cba174772ed 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ConsistencyLevel.java +++ b/driver-core/src/main/java/com/datastax/driver/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/driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java b/driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java index 84e6bfad56f..b5fd7689d67 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -73,9 +75,11 @@ class ControlConnection implements Connection.Owner { private static final String SELECT_LOCAL = "SELECT * FROM system.local WHERE key='local'"; private static final String SELECT_SCHEMA_PEERS = - "SELECT peer, rpc_address, schema_version FROM system.peers"; + "SELECT peer, rpc_address, schema_version, host_id FROM system.peers"; private static final String SELECT_SCHEMA_LOCAL = - "SELECT schema_version FROM system.local WHERE key='local'"; + "SELECT schema_version, host_id FROM system.local WHERE key='local'"; + + private static final VersionNumber _3_11 = VersionNumber.parse("3.11.0"); @VisibleForTesting final AtomicReference connectionRef = new AtomicReference(); @@ -90,6 +94,7 @@ class ControlConnection implements Connection.Owner { // set to true initially, if ever fails will be set to false and peers table will be used // from here on out. private volatile boolean isPeersV2 = true; + private volatile boolean isCloud = false; public ControlConnection(Cluster.Manager manager) { this.cluster = manager; @@ -99,8 +104,7 @@ public ControlConnection(Cluster.Manager manager) { void connect() throws UnsupportedProtocolVersionException { if (isShutdown) return; - // NB: at this stage, allHosts() only contains the initial contact points - List hosts = new ArrayList(cluster.metadata.allHosts()); + List hosts = new ArrayList(cluster.metadata.getContactPoints()); // shuffle so that multiple clients with the same contact points don't all pick the same control // host Collections.shuffle(hosts); @@ -123,7 +127,7 @@ CloseFuture closeAsync() { Host connectedHost() { Connection current = connectionRef.get(); - return (current == null) ? null : cluster.metadata.getHost(current.address); + return (current == null) ? null : cluster.metadata.getHost(current.endPoint); } void triggerReconnect() { @@ -213,7 +217,7 @@ private void signalError() { } private void setNewConnection(Connection newConnection) { - Host.statesLogger.debug("[Control connection] established to {}", newConnection.address); + Host.statesLogger.debug("[Control connection] established to {}", newConnection.endPoint); newConnection.setOwner(this); Connection old = connectionRef.getAndSet(newConnection); if (old != null && !old.isClosed()) old.closeAsync().force(); @@ -222,7 +226,7 @@ private void setNewConnection(Connection newConnection) { private Connection reconnectInternal(Iterator iter, boolean isInitialConnection) throws UnsupportedProtocolVersionException { - Map errors = null; + Map errors = null; Host host = null; try { @@ -265,17 +269,14 @@ private Connection reconnectInternal(Iterator iter, boolean isInitialConne iter.next(), new DriverException("Connection thread interrupted"), errors, iter); } throw new NoHostAvailableException( - errors == null ? Collections.emptyMap() : errors); + errors == null ? Collections.emptyMap() : errors); } - private static Map logError( - Host host, - Throwable exception, - Map errors, - Iterator iter) { - if (errors == null) errors = new HashMap(); + private static Map logError( + Host host, Throwable exception, Map errors, Iterator iter) { + if (errors == null) errors = new HashMap(); - errors.put(host.getSocketAddress(), exception); + errors.put(host.getEndPoint(), exception); if (logger.isDebugEnabled()) { if (iter.hasNext()) { @@ -295,7 +296,10 @@ private Connection tryConnect(Host host, boolean isInitialConnection) throws ConnectionException, ExecutionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { Connection connection = cluster.connectionFactory.open(host); - + String productType = connection.optionsQuery().get(); + if (productType.equals("DATASTAX_APOLLO")) { + isCloud = true; + } // If no protocol version was specified, set the default as soon as a connection succeeds (it's // needed to parse UDTs in refreshSchema) if (cluster.connectionFactory.protocolVersion == null) @@ -377,7 +381,7 @@ static void refreshSchema( Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { - Host host = cluster.metadata.getHost(connection.address); + Host host = cluster.metadata.getHost(connection.endPoint); // Neither host, nor it's version should be null. But instead of dying if there is a race or // something, we can kind of try to infer // a Cassandra version from the protocol version (this is not full proof, we can have the @@ -390,19 +394,26 @@ static void refreshSchema( logger.warn( "Cannot find Cassandra version for host {} to parse the schema, using {} based on protocol version in use. " + "If parsing the schema fails, this could be the cause", - connection.address, + connection.endPoint, cassandraVersion); } else { cassandraVersion = host.getCassandraVersion(); } - VersionNumber dseVersion; SchemaParser schemaParser; - // If using DSE, derive parser from DSE version. - if (host == null || host.getDseVersion() == null) { + if (host == null) { schemaParser = SchemaParser.forVersion(cassandraVersion); } else { - dseVersion = host.getDseVersion(); - schemaParser = SchemaParser.forDseVersion(dseVersion); + @SuppressWarnings("deprecation") + VersionNumber dseVersion = host.getDseVersion(); + // If using DSE, derive parser from DSE version. + schemaParser = + dseVersion == null + ? SchemaParser.forVersion(cassandraVersion) + : SchemaParser.forDseVersion(dseVersion); + if (dseVersion != null && dseVersion.getMajor() == 6 && dseVersion.getMinor() < 8) { + // DSE 6.0 and 6.7 report C* 4.0, but consider it C* 3.11 for schema parsing purposes + cassandraVersion = _3_11; + } } schemaParser.refresh( @@ -444,52 +455,27 @@ void refreshNodeListAndTokenMap() { } } - private static InetSocketAddress nativeAddressForPeerHost( - Row peersRow, InetSocketAddress connectedHost, Cluster.Manager cluster) { - // if native_address is present, this comes from the peers_v2 table. - if (peersRow.getColumnDefinitions().contains("native_address")) { - InetAddress nativeAddress = peersRow.getInet("native_address"); - int nativePort = peersRow.getInt("native_port"); - return cluster.translateAddress(new InetSocketAddress(nativeAddress, nativePort)); - } else { - // after CASSANDRA-9436, system.peers contains the following inet columns: - // - peer: this is actually broadcast_address - // - rpc_address: the address we are looking for (this corresponds to broadcast_rpc_address in - // the peer's cassandra yaml file; - // if this setting if unset, it defaults to the value for rpc_address or - // rpc_interface) - // - preferred_ip: used by Ec2MultiRegionSnitch and GossipingPropertyFileSnitch, possibly - // others; contents unclear - InetAddress broadcastAddress = peersRow.getInet("peer"); - InetAddress rpcAddress = peersRow.getInet("rpc_address"); - - if (broadcastAddress == null) { - return null; - } else if (broadcastAddress.equals(connectedHost.getAddress()) - || (rpcAddress != null && rpcAddress.equals(connectedHost.getAddress()))) { - // Some DSE versions were inserting a line for the local node in peers (with mostly null - // values). This has been fixed, but if we - // detect that's the case, ignore it as it's not really a big deal. - logger.debug( - "System.peers on node {} has a line for itself. This is not normal but is a known problem of some DSE version. Ignoring the entry.", - connectedHost); - return null; - } else if (rpcAddress == null) { - return null; - } else if (rpcAddress.equals(bindAllAddress)) { - logger.warn( - "Found host with 0.0.0.0 as rpc_address, using broadcast_address ({}) to contact it instead. If this is incorrect you should avoid the use of 0.0.0.0 server side.", - broadcastAddress); - rpcAddress = broadcastAddress; - } - return cluster.translateAddress(rpcAddress); + private static EndPoint endPointForPeerHost( + Row peersRow, EndPoint connectedEndPoint, Cluster.Manager cluster) { + EndPoint endPoint = cluster.configuration.getPolicies().getEndPointFactory().create(peersRow); + if (connectedEndPoint.equals(endPoint)) { + // Some DSE versions were inserting a line for the local node in peers (with mostly null + // values). This has been fixed, but if we detect that's the case, ignore it as it's not + // really a big deal. + logger.debug( + "System.peers on node {} has a line for itself. " + + "This is not normal but is a known problem of some DSE versions. " + + "Ignoring the entry.", + connectedEndPoint); + return null; } + return endPoint; } private Row fetchNodeInfo(Host host, Connection c) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { - boolean isConnectedHost = c.address.equals(host.getSocketAddress()); + boolean isConnectedHost = c.endPoint.equals(host.getEndPoint()); if (isConnectedHost || host.getBroadcastSocketAddress() != null) { String query; if (isConnectedHost) { @@ -531,8 +517,10 @@ private Row fetchNodeInfo(Host host, Connection c) // We have to fetch the whole peers table and find the host we're looking for ListenableFuture future = selectPeersFuture(c); for (Row row : future.get()) { - InetSocketAddress addr = nativeAddressForPeerHost(row, c.address, cluster); - if (addr != null && addr.equals(host.getSocketAddress())) return row; + UUID rowId = row.getUUID("host_id"); + if (host.getHostId().equals(rowId)) { + return row; + } } return null; } @@ -558,9 +546,9 @@ boolean refreshNodeInfo(Host host) { } else { logger.warn( "No row found for host {} in {}'s peers system table. {} will be ignored.", - host.getAddress(), - c.address, - host.getAddress()); + host.getEndPoint(), + c.endPoint, + host.getEndPoint()); return false; } // Ignore hosts with a null rpc_address, as this is most likely a phantom row in @@ -568,7 +556,7 @@ boolean refreshNodeInfo(Host host) { // Don't test this for the control host since we're already connected to it anyway, and we // read the info from system.local // which didn't have an rpc_address column (JAVA-546) until CASSANDRA-9436 - } else if (!c.address.equals(host.getSocketAddress()) && !isValidPeer(row, true)) { + } else if (!c.endPoint.equals(host.getEndPoint()) && !isValidPeer(row, true)) { return false; } @@ -620,17 +608,47 @@ private static void updateInfo( // - broadcast_port // - listen_port - InetSocketAddress broadcastAddress = null; + InetSocketAddress broadcastRpcAddress = null; + if (row.getColumnDefinitions().contains("native_address")) { + InetAddress nativeAddress = row.getInet("native_address"); + int nativePort = row.getInt("native_port"); + broadcastRpcAddress = new InetSocketAddress(nativeAddress, nativePort); + } else if (row.getColumnDefinitions().contains("native_transport_address")) { + // DSE 6.8 introduced native_transport_address and native_transport_port for the + // listen address. Also included is native_transport_port_ssl (in case users + // want to setup a different port for SSL and non-SSL conns). + InetAddress nativeAddress = row.getInet("native_transport_address"); + int nativePort = row.getInt("native_transport_port"); + if (cluster.getCluster().getConfiguration().getProtocolOptions().getSSLOptions() != null + && !row.isNull("native_transport_port_ssl")) { + nativePort = row.getInt("native_transport_port_ssl"); + } + broadcastRpcAddress = new InetSocketAddress(nativeAddress, nativePort); + } else if (row.getColumnDefinitions().contains("rpc_address")) { + InetAddress rpcAddress = row.getInet("rpc_address"); + int nativePort = cluster.connectionFactory.getPort(); + if (row.getColumnDefinitions().contains("rpc_port")) { + nativePort = row.getInt("rpc_port"); + } + broadcastRpcAddress = new InetSocketAddress(rpcAddress, nativePort); + } + // Before CASSANDRA-9436, system.local doesn't have rpc_address, so this might be null. It's not + // a big deal because we only use this for server events, and the control node doesn't receive + // events for itself. + host.setBroadcastRpcAddress(broadcastRpcAddress); + + InetSocketAddress broadcastSocketAddress = null; if (row.getColumnDefinitions().contains("peer")) { // system.peers int broadcastPort = row.getColumnDefinitions().contains("peer_port") ? row.getInt("peer_port") : 0; - broadcastAddress = new InetSocketAddress(row.getInet("peer"), broadcastPort); + broadcastSocketAddress = new InetSocketAddress(row.getInet("peer"), broadcastPort); } else if (row.getColumnDefinitions().contains("broadcast_address")) { // system.local int broadcastPort = row.getColumnDefinitions().contains("broadcast_port") ? row.getInt("broadcast_port") : 0; - broadcastAddress = new InetSocketAddress(row.getInet("broadcast_address"), broadcastPort); + broadcastSocketAddress = + new InetSocketAddress(row.getInet("broadcast_address"), broadcastPort); } - host.setBroadcastSocketAddress(broadcastAddress); + host.setBroadcastSocketAddress(broadcastSocketAddress); // in system.local only for C* versions >= 2.0.17, 2.1.8, 2.2.0 rc2, // not yet in system.peers as of C* 3.2 @@ -757,39 +775,53 @@ private void refreshNodeListAndTokenMap( // Update cluster name, DC and rack for the one node we are connected to Row localRow = localFuture.get().one(); - if (localRow != null) { - String clusterName = localRow.getString("cluster_name"); - if (clusterName != null) cluster.metadata.clusterName = clusterName; - - partitioner = localRow.getString("partitioner"); - if (partitioner != null) { - cluster.metadata.partitioner = partitioner; - factory = Token.getFactory(partitioner); - } + if (localRow == null) { + throw new IllegalStateException( + String.format( + "system.local is empty on %s, this should not happen", connection.endPoint)); + } + String clusterName = localRow.getString("cluster_name"); + if (clusterName != null) cluster.metadata.clusterName = clusterName; - Host host = cluster.metadata.getHost(connection.address); - // In theory host can't be null. However there is no point in risking a NPE in case we - // have a race between a node removal and this. - if (host == null) { - logger.debug( - "Host in local system table ({}) unknown to us (ok if said host just got removed)", - connection.address); - } else { - updateInfo(host, localRow, cluster, isInitialConnection); - if (metadataEnabled && factory != null) { - Set tokensStr = localRow.getSet("tokens", String.class); - if (!tokensStr.isEmpty()) { - Set tokens = toTokens(factory, tokensStr); - tokenMap.put(host, tokens); - } + partitioner = localRow.getString("partitioner"); + if (partitioner != null) { + cluster.metadata.partitioner = partitioner; + factory = Token.getFactory(partitioner); + } + + // During init, metadata.allHosts is still empty, the contact points are in + // metadata.contactPoints. We need to copy them over, but we can only do it after having + // called updateInfo, because we need to know the host id. + // This is the same for peer hosts (see further down). + Host controlHost = + isInitialConnection + ? cluster.metadata.getContactPoint(connection.endPoint) + : cluster.metadata.getHost(connection.endPoint); + // In theory host can't be null. However there is no point in risking a NPE in case we + // have a race between a node removal and this. + if (controlHost == null) { + logger.debug( + "Host in local system table ({}) unknown to us (ok if said host just got removed)", + connection.endPoint); + } else { + updateInfo(controlHost, localRow, cluster, isInitialConnection); + if (metadataEnabled && factory != null) { + Set tokensStr = localRow.getSet("tokens", String.class); + if (!tokensStr.isEmpty()) { + Set tokens = toTokens(factory, tokensStr); + tokenMap.put(controlHost, tokens); } } + if (isInitialConnection) { + cluster.metadata.addIfAbsent(controlHost); + } } - List foundHosts = new ArrayList(); + List foundHosts = new ArrayList(); List dcs = new ArrayList(); List racks = new ArrayList(); List cassandraVersions = new ArrayList(); + List broadcastRpcAddresses = new ArrayList(); List broadcastAddresses = new ArrayList(); List listenAddresses = new ArrayList(); List> allTokens = new ArrayList>(); @@ -802,13 +834,38 @@ private void refreshNodeListAndTokenMap( for (Row row : peersFuture.get()) { if (!isValidPeer(row, logInvalidPeers)) continue; - InetSocketAddress rpcAddress = nativeAddressForPeerHost(row, connection.address, cluster); - if (rpcAddress == null) continue; - foundHosts.add(rpcAddress); + EndPoint endPoint = endPointForPeerHost(row, connection.endPoint, cluster); + if (endPoint == null) { + continue; + } + foundHosts.add(endPoint); dcs.add(row.getString("data_center")); racks.add(row.getString("rack")); cassandraVersions.add(row.getString("release_version")); + InetSocketAddress broadcastRpcAddress; + if (row.getColumnDefinitions().contains("native_address")) { + InetAddress nativeAddress = row.getInet("native_address"); + int nativePort = row.getInt("native_port"); + broadcastRpcAddress = new InetSocketAddress(nativeAddress, nativePort); + } else if (row.getColumnDefinitions().contains("native_transport_address")) { + InetAddress nativeAddress = row.getInet("native_transport_address"); + int nativePort = row.getInt("native_transport_port"); + if (cluster.getCluster().getConfiguration().getProtocolOptions().getSSLOptions() != null + && !row.isNull("native_transport_port_ssl")) { + nativePort = row.getInt("native_transport_port_ssl"); + } + broadcastRpcAddress = new InetSocketAddress(nativeAddress, nativePort); + } else { + InetAddress rpcAddress = row.getInet("rpc_address"); + int nativePort = cluster.connectionFactory.getPort(); + if (row.getColumnDefinitions().contains("rpc_port")) { + nativePort = row.getInt("rpc_port"); + } + broadcastRpcAddress = new InetSocketAddress(rpcAddress, nativePort); + } + broadcastRpcAddresses.add(broadcastRpcAddress); + int broadcastPort = row.getColumnDefinitions().contains("peer_port") ? row.getInt("peer_port") : 0; InetSocketAddress broadcastAddress = @@ -847,49 +904,60 @@ private void refreshNodeListAndTokenMap( } for (int i = 0; i < foundHosts.size(); i++) { - Host host = cluster.metadata.getHost(foundHosts.get(i)); + Host peerHost = + isInitialConnection + ? cluster.metadata.getContactPoint(foundHosts.get(i)) + : cluster.metadata.getHost(foundHosts.get(i)); boolean isNew = false; - if (host == null) { + if (peerHost == null) { // We don't know that node, create the Host object but wait until we've set the known // info before signaling the addition. Host newHost = cluster.metadata.newHost(foundHosts.get(i)); + newHost.setHostId(hostIds.get(i)); // we need an id to add to the metadata Host previous = cluster.metadata.addIfAbsent(newHost); if (previous == null) { - host = newHost; + peerHost = newHost; isNew = true; } else { - host = previous; + peerHost = previous; isNew = false; } } if (dcs.get(i) != null || racks.get(i) != null) - updateLocationInfo(host, dcs.get(i), racks.get(i), isInitialConnection, cluster); - if (cassandraVersions.get(i) != null) host.setVersion(cassandraVersions.get(i)); + updateLocationInfo(peerHost, dcs.get(i), racks.get(i), isInitialConnection, cluster); + if (cassandraVersions.get(i) != null) peerHost.setVersion(cassandraVersions.get(i)); + if (broadcastRpcAddresses.get(i) != null) + peerHost.setBroadcastRpcAddress(broadcastRpcAddresses.get(i)); if (broadcastAddresses.get(i) != null) - host.setBroadcastSocketAddress(broadcastAddresses.get(i)); - if (listenAddresses.get(i) != null) host.setListenSocketAddress(listenAddresses.get(i)); - - if (dseVersions.get(i) != null) host.setDseVersion(dseVersions.get(i)); - if (dseWorkloads.get(i) != null) host.setDseWorkload(dseWorkloads.get(i)); - if (dseGraphEnabled.get(i) != null) host.setDseGraphEnabled(dseGraphEnabled.get(i)); - if (hostIds.get(i) != null) { - host.setHostId(hostIds.get(i)); - } + peerHost.setBroadcastSocketAddress(broadcastAddresses.get(i)); + if (listenAddresses.get(i) != null) peerHost.setListenSocketAddress(listenAddresses.get(i)); + + if (dseVersions.get(i) != null) peerHost.setDseVersion(dseVersions.get(i)); + if (dseWorkloads.get(i) != null) peerHost.setDseWorkload(dseWorkloads.get(i)); + if (dseGraphEnabled.get(i) != null) peerHost.setDseGraphEnabled(dseGraphEnabled.get(i)); + peerHost.setHostId(hostIds.get(i)); if (schemaVersions.get(i) != null) { - host.setSchemaVersion(schemaVersions.get(i)); + peerHost.setSchemaVersion(schemaVersions.get(i)); } if (metadataEnabled && factory != null && allTokens.get(i) != null) - tokenMap.put(host, allTokens.get(i)); + tokenMap.put(peerHost, allTokens.get(i)); - if (isNew && !isInitialConnection) cluster.triggerOnAdd(host); + if (!isNew && isInitialConnection) { + // If we're at init and the node already existed, it means it was a contact point, so we + // need to copy it over to the regular host list + cluster.metadata.addIfAbsent(peerHost); + } + if (isNew && !isInitialConnection) { + cluster.triggerOnAdd(peerHost); + } } - // Removes all those that seems to have been removed (since we lost the control connection) - Set foundHostsSet = new HashSet(foundHosts); + // Removes all those that seem to have been removed (since we lost the control connection) + Set foundHostsSet = new HashSet(foundHosts); for (Host host : cluster.metadata.allHosts()) - if (!host.getSocketAddress().equals(connection.address) - && !foundHostsSet.contains(host.getSocketAddress())) + if (!host.getEndPoint().equals(connection.endPoint) + && !foundHostsSet.contains(host.getEndPoint())) cluster.removeHost(host, isInitialConnection); if (metadataEnabled && factory != null && !tokenMap.isEmpty()) @@ -906,19 +974,26 @@ private static Set toTokens(Token.Factory factory, Set tokensStr) private boolean isValidPeer(Row peerRow, boolean logIfInvalid) { boolean isValid = - isPeersV2 - ? peerRow.getColumnDefinitions().contains("native_address") - && peerRow.getColumnDefinitions().contains("native_port") - && !peerRow.isNull("native_address") - && !peerRow.isNull("native_port") - : peerRow.getColumnDefinitions().contains("rpc_address") - && !peerRow.isNull("rpc_address"); + peerRow.getColumnDefinitions().contains("host_id") && !peerRow.isNull("host_id"); + + if (isPeersV2) { + isValid &= + peerRow.getColumnDefinitions().contains("native_address") + && peerRow.getColumnDefinitions().contains("native_port") + && !peerRow.isNull("native_address") + && !peerRow.isNull("native_port"); + } else { + isValid &= + (peerRow.getColumnDefinitions().contains("rpc_address") && !peerRow.isNull("rpc_address")) + || (peerRow.getColumnDefinitions().contains("native_transport_address") + && peerRow.getColumnDefinitions().contains("native_transport_port") + && !peerRow.isNull("native_transport_address") + && !peerRow.isNull("native_transport_port")); + } if (EXTENDED_PEER_CHECK) { isValid &= - peerRow.getColumnDefinitions().contains("host_id") - && !peerRow.isNull("host_id") - && peerRow.getColumnDefinitions().contains("data_center") + peerRow.getColumnDefinitions().contains("data_center") && !peerRow.isNull("data_center") && peerRow.getColumnDefinitions().contains("rack") && !peerRow.isNull("rack") @@ -941,6 +1016,9 @@ private String formatInvalidPeer(Row peerRow) { formatMissingOrNullColumn(peerRow, "native_address", sb); formatMissingOrNullColumn(peerRow, "native_port", sb); } else { + formatMissingOrNullColumn(peerRow, "native_transport_address", sb); + formatMissingOrNullColumn(peerRow, "native_transport_port", sb); + formatMissingOrNullColumn(peerRow, "native_transport_port_ssl", sb); formatMissingOrNullColumn(peerRow, "rpc_address", sb); } if (EXTENDED_PEER_CHECK) { @@ -998,10 +1076,10 @@ private static boolean checkSchemaAgreement(Connection connection, Cluster.Manag for (Row row : peersFuture.get()) { - InetSocketAddress addr = nativeAddressForPeerHost(row, connection.address, cluster); - if (addr == null || row.isNull("schema_version")) continue; + UUID hostId = row.getUUID("host_id"); + if (row.isNull("schema_version")) continue; - Host peer = cluster.metadata.getHost(addr); + Host peer = cluster.metadata.getHost(hostId); if (peer != null && peer.isUp()) versions.add(row.getUUID("schema_version")); } logger.debug("Checking for schema agreement: versions are {}", versions); @@ -1022,6 +1100,10 @@ boolean isOpen() { return c != null && !c.isClosed(); } + boolean isCloud() { + return isCloud; + } + public void onUp(Host host) {} public void onAdd(Host host) {} @@ -1037,10 +1119,10 @@ public void onRemove(Host host) { private void onHostGone(Host host) { Connection current = connectionRef.get(); - if (current != null && current.address.equals(host.getSocketAddress())) { + if (current != null && current.endPoint.equals(host.getEndPoint())) { logger.debug( "[Control connection] {} is down/removed and it was the control host, triggering reconnect", - current.address); + current.endPoint); if (!current.isClosed()) current.closeAsync().force(); backgroundReconnect(0); } diff --git a/driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java index 85907629906..7a0c43e0b39 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/Crc.java b/driver-core/src/main/java/com/datastax/driver/core/Crc.java new file mode 100644 index 00000000000..05435d5f452 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/Crc.java @@ -0,0 +1,150 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +import io.netty.buffer.ByteBuf; +import io.netty.util.concurrent.FastThreadLocal; +import java.nio.ByteBuffer; +import java.util.zip.CRC32; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Copied and adapted from the server-side version. */ +class Crc { + + private static final Logger logger = LoggerFactory.getLogger(Crc.class); + + private static final FastThreadLocal crc32 = + new FastThreadLocal() { + @Override + protected CRC32 initialValue() { + return new CRC32(); + } + }; + + private static final byte[] initialBytes = + new byte[] {(byte) 0xFA, (byte) 0x2D, (byte) 0x55, (byte) 0xCA}; + + private static final CrcUpdater CRC_UPDATER = selectCrcUpdater(); + + static int computeCrc32(ByteBuf buffer) { + CRC32 crc = newCrc32(); + CRC_UPDATER.update(crc, buffer); + return (int) crc.getValue(); + } + + private static CRC32 newCrc32() { + CRC32 crc = crc32.get(); + crc.reset(); + crc.update(initialBytes); + return crc; + } + + private static final int CRC24_INIT = 0x875060; + /** + * Polynomial chosen from https://users.ece.cmu.edu/~koopman/crc/index.html, by Philip Koopman + * + *

This webpage claims a copyright to Philip Koopman, which he licenses under the Creative + * Commons Attribution 4.0 International License (https://creativecommons.org/licenses/by/4.0) + * + *

It is unclear if this copyright can extend to a 'fact' such as this specific number, + * particularly as we do not use Koopman's notation to represent the polynomial, but we anyway + * attribute his work and link the terms of his license since they are not incompatible with our + * usage and we greatly appreciate his work. + * + *

This polynomial provides hamming distance of 8 for messages up to length 105 bits; we only + * support 8-64 bits at present, with an expected range of 40-48. + */ + private static final int CRC24_POLY = 0x1974F0B; + + /** + * NOTE: the order of bytes must reach the wire in the same order the CRC is computed, with the + * CRC immediately following in a trailer. Since we read in least significant byte order, if you + * write to a buffer using putInt or putLong, the byte order will be reversed and you will lose + * the guarantee of protection from burst corruptions of 24 bits in length. + * + *

Make sure either to write byte-by-byte to the wire, or to use Integer/Long.reverseBytes if + * you write to a BIG_ENDIAN buffer. + * + *

See http://users.ece.cmu.edu/~koopman/pubs/ray06_crcalgorithms.pdf + * + *

Complain to the ethernet spec writers, for having inverse bit to byte significance order. + * + *

Note we use the most naive algorithm here. We support at most 8 bytes, and typically supply + * 5 or fewer, so any efficiency of a table approach is swallowed by the time to hit L3, even for + * a tiny (4bit) table. + * + * @param bytes an up to 8-byte register containing bytes to compute the CRC over the bytes AND + * bits will be read least-significant to most significant. + * @param len the number of bytes, greater than 0 and fewer than 9, to be read from bytes + * @return the least-significant bit AND byte order crc24 using the CRC24_POLY polynomial + */ + static int computeCrc24(long bytes, int len) { + int crc = CRC24_INIT; + while (len-- > 0) { + crc ^= (bytes & 0xff) << 16; + bytes >>= 8; + + for (int i = 0; i < 8; i++) { + crc <<= 1; + if ((crc & 0x1000000) != 0) crc ^= CRC24_POLY; + } + } + return crc; + } + + private static CrcUpdater selectCrcUpdater() { + try { + CRC32.class.getDeclaredMethod("update", ByteBuffer.class); + return new Java8CrcUpdater(); + } catch (Exception e) { + logger.warn( + "It looks like you are running Java 7 or below. " + + "CRC checks (used in protocol {} and above) will require a memory copy, which can " + + "negatively impact performance. Consider using a more modern VM.", + ProtocolVersion.V5, + e); + return new Java6CrcUpdater(); + } + } + + private interface CrcUpdater { + void update(CRC32 crc, ByteBuf buffer); + } + + private static class Java6CrcUpdater implements CrcUpdater { + @Override + public void update(CRC32 crc, ByteBuf buffer) { + if (buffer.hasArray()) { + crc.update(buffer.array(), buffer.arrayOffset(), buffer.readableBytes()); + } else { + byte[] bytes = new byte[buffer.readableBytes()]; + buffer.getBytes(buffer.readerIndex(), bytes); + crc.update(bytes); + } + } + } + + @IgnoreJDK6Requirement + private static class Java8CrcUpdater implements CrcUpdater { + @Override + public void update(CRC32 crc, ByteBuf buffer) { + crc.update(buffer.internalNioBuffer(buffer.readerIndex(), buffer.readableBytes())); + } + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/DataType.java b/driver-core/src/main/java/com/datastax/driver/core/DataType.java index 352716e2cdc..83260516592 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/DataType.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/DataTypeClassNameParser.java b/driver-core/src/main/java/com/datastax/driver/core/DataTypeClassNameParser.java index ef840356f3c..a352bc72d2d 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/DataTypeClassNameParser.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, diff --git a/driver-core/src/main/java/com/datastax/driver/core/DataTypeCqlNameParser.java b/driver-core/src/main/java/com/datastax/driver/core/DataTypeCqlNameParser.java index 8a63e9a61e1..ee0d6744d76 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/DataTypeCqlNameParser.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -119,8 +121,28 @@ static DataType parse( DataType nativeType = NATIVE_TYPES_MAP.get(type.toLowerCase()); if (nativeType != null) return nativeType; + if (parser.isEOS()) { + // return a custom type for the special empty type + // so that it gets detected later on, see TableMetadata + if (type.equalsIgnoreCase(EMPTY)) return custom(type); + + // We need to remove escaped double quotes within the type name as it is stored unescaped. + // Otherwise it's a UDT. If we only want a shallow definition build it, otherwise search known + // definitions. + if (shallowUserTypes) + return new UserType.Shallow(currentKeyspaceName, Metadata.handleId(type), frozen); + + UserType userType = null; + if (currentUserTypes != null) userType = currentUserTypes.get(Metadata.handleId(type)); + if (userType == null && oldUserTypes != null) + userType = oldUserTypes.get(Metadata.handleId(type)); + + if (userType == null) throw new UnresolvedUserTypeException(currentKeyspaceName, type); + else return userType.copy(frozen); + } + + List parameters = parser.parseTypeParameters(); if (type.equalsIgnoreCase(LIST)) { - List parameters = parser.parseTypeParameters(); if (parameters.size() != 1) throw new DriverInternalError( String.format("Excepting single parameter for list, got %s", parameters)); @@ -137,7 +159,6 @@ static DataType parse( } if (type.equalsIgnoreCase(SET)) { - List parameters = parser.parseTypeParameters(); if (parameters.size() != 1) throw new DriverInternalError( String.format("Excepting single parameter for set, got %s", parameters)); @@ -154,7 +175,6 @@ static DataType parse( } if (type.equalsIgnoreCase(MAP)) { - List parameters = parser.parseTypeParameters(); if (parameters.size() != 2) throw new DriverInternalError( String.format("Excepting two parameters for map, got %s", parameters)); @@ -180,7 +200,6 @@ static DataType parse( } if (type.equalsIgnoreCase(FROZEN)) { - List parameters = parser.parseTypeParameters(); if (parameters.size() != 1) throw new DriverInternalError( String.format("Excepting single parameter for frozen keyword, got %s", parameters)); @@ -195,9 +214,11 @@ static DataType parse( } if (type.equalsIgnoreCase(TUPLE)) { - List rawTypes = parser.parseTypeParameters(); - List types = new ArrayList(rawTypes.size()); - for (String rawType : rawTypes) { + if (parameters.isEmpty()) { + throw new IllegalArgumentException("Expecting at list one parameter for tuple, got none"); + } + List types = new ArrayList(parameters.size()); + for (String rawType : parameters) { types.add( parse( rawType, @@ -211,23 +232,7 @@ static DataType parse( return cluster.getMetadata().newTupleType(types); } - // return a custom type for the special empty type - // so that it gets detected later on, see TableMetadata - if (type.equalsIgnoreCase(EMPTY)) return custom(type); - - // We need to remove escaped double quotes within the type name as it is stored unescaped. - // Otherwise it's a UDT. If we only want a shallow definition build it, otherwise search known - // definitions. - if (shallowUserTypes) - return new UserType.Shallow(currentKeyspaceName, Metadata.handleId(type), frozen); - - UserType userType = null; - if (currentUserTypes != null) userType = currentUserTypes.get(Metadata.handleId(type)); - if (userType == null && oldUserTypes != null) - userType = oldUserTypes.get(Metadata.handleId(type)); - - if (userType == null) throw new UnresolvedUserTypeException(currentKeyspaceName, type); - else return userType.copy(frozen); + throw new IllegalArgumentException("Could not parse type name " + toParse); } private static class Parser { diff --git a/driver-core/src/main/java/com/datastax/driver/core/DefaultEndPointFactory.java b/driver-core/src/main/java/com/datastax/driver/core/DefaultEndPointFactory.java new file mode 100644 index 00000000000..367532edd5d --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/DefaultEndPointFactory.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DefaultEndPointFactory implements EndPointFactory { + + private static final Logger logger = LoggerFactory.getLogger(ControlConnection.class); + private static final InetAddress BIND_ALL_ADDRESS; + + static { + try { + BIND_ALL_ADDRESS = InetAddress.getByAddress(new byte[4]); + } catch (UnknownHostException e) { + throw new RuntimeException(e); + } + } + + private volatile Cluster cluster; + + @Override + public void init(Cluster cluster) { + this.cluster = cluster; + } + + @Override + public EndPoint create(Row peersRow) { + if (peersRow.getColumnDefinitions().contains("native_address")) { + InetAddress nativeAddress = peersRow.getInet("native_address"); + int nativePort = peersRow.getInt("native_port"); + InetSocketAddress translateAddress = + cluster.manager.translateAddress(new InetSocketAddress(nativeAddress, nativePort)); + return new TranslatedAddressEndPoint(translateAddress); + } else if (peersRow.getColumnDefinitions().contains("native_transport_address")) { + InetAddress nativeAddress = peersRow.getInet("native_transport_address"); + int nativePort = peersRow.getInt("native_transport_port"); + if (cluster.getConfiguration().getProtocolOptions().getSSLOptions() != null + && !peersRow.isNull("native_transport_port_ssl")) { + nativePort = peersRow.getInt("native_transport_port_ssl"); + } + InetSocketAddress translateAddress = + cluster.manager.translateAddress(new InetSocketAddress(nativeAddress, nativePort)); + return new TranslatedAddressEndPoint(translateAddress); + } else { + InetAddress broadcastAddress = peersRow.getInet("peer"); + InetAddress rpcAddress = peersRow.getInet("rpc_address"); + if (broadcastAddress == null || rpcAddress == null) { + return null; + } else if (rpcAddress.equals(BIND_ALL_ADDRESS)) { + logger.warn( + "Found host with 0.0.0.0 as rpc_address, " + + "using broadcast_address ({}) to contact it instead. " + + "If this is incorrect you should avoid the use of 0.0.0.0 server side.", + broadcastAddress); + rpcAddress = broadcastAddress; + } + InetSocketAddress translateAddress = cluster.manager.translateAddress(rpcAddress); + return new TranslatedAddressEndPoint(translateAddress); + } + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/DefaultPreparedStatement.java b/driver-core/src/main/java/com/datastax/driver/core/DefaultPreparedStatement.java index 6ce183fbea3..7a75e9f57e2 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/DefaultPreparedStatement.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java b/driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java index 068cb582717..b26c69ffaae 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +++ b/driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -212,24 +214,24 @@ public void run() { } break; case ERROR: - setException(((Responses.Error) response).asException(connection.address)); + setException(((Responses.Error) response).asException(connection.endPoint)); break; default: // This mean we have probably have a bad node, so defunct the connection connection.defunct( new ConnectionException( - connection.address, String.format("Got unexpected %s response", response.type))); + connection.endPoint, String.format("Got unexpected %s response", response.type))); setException( new DriverInternalError( String.format( - "Got unexpected %s response from %s", response.type, connection.address))); + "Got unexpected %s response from %s", response.type, connection.endPoint))); break; } } catch (Throwable e) { // If we get a bug here, the client will not get it, so better forwarding the error setException( new DriverInternalError( - "Unexpected error while processing response from " + connection.address, e)); + "Unexpected error while processing response from " + connection.endPoint, e)); } } @@ -254,7 +256,7 @@ public boolean onTimeout(Connection connection, long latency, int retryCount) { // RequestHandler). // So just set an exception for the final result, which should be handled correctly by said // internal call. - setException(new OperationTimedOutException(connection.address)); + setException(new OperationTimedOutException(connection.endPoint)); return true; } diff --git a/driver-core/src/main/java/com/datastax/driver/core/DelegatingCluster.java b/driver-core/src/main/java/com/datastax/driver/core/DelegatingCluster.java index 881a9ca8633..30ee4274071 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/DelegatingCluster.java +++ b/driver-core/src/main/java/com/datastax/driver/core/DelegatingCluster.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,6 @@ package com.datastax.driver.core; import com.google.common.util.concurrent.ListenableFuture; -import java.net.InetSocketAddress; import java.util.Collections; /** @@ -47,7 +48,7 @@ protected DelegatingCluster() { // Construct parent class with dummy parameters that will never get used (since super.init() is // never called). - super("delegating_cluster", Collections.emptyList(), null); + super("delegating_cluster", Collections.emptyList(), null); // Immediately close the parent class's internal Manager, to make sure that it will fail fast if // it's ever diff --git a/driver-core/src/main/java/com/datastax/driver/core/DirectedGraph.java b/driver-core/src/main/java/com/datastax/driver/core/DirectedGraph.java index 81265bc7046..4a28063d27a 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/DirectedGraph.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/DriverThrowables.java b/driver-core/src/main/java/com/datastax/driver/core/DriverThrowables.java index 3a3898e2a6d..582aa7107ab 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/DriverThrowables.java +++ b/driver-core/src/main/java/com/datastax/driver/core/DriverThrowables.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/Duration.java b/driver-core/src/main/java/com/datastax/driver/core/Duration.java index 530de022af8..f097f8e38fa 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Duration.java +++ b/driver-core/src/main/java/com/datastax/driver/core/Duration.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/EndPoint.java b/driver-core/src/main/java/com/datastax/driver/core/EndPoint.java new file mode 100644 index 00000000000..4900084c2d3 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/EndPoint.java @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +import java.net.InetSocketAddress; + +/** Encapsulates the information needed by the driver to open connections to a node. */ +public interface EndPoint { + + /** + * Resolves this instance to a socket address. + * + *

This will be called each time the driver opens a new connection to the node. The returned + * address cannot be null. + */ + InetSocketAddress resolve(); +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/EndPointFactory.java b/driver-core/src/main/java/com/datastax/driver/core/EndPointFactory.java new file mode 100644 index 00000000000..0941720ea5a --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/EndPointFactory.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.datastax.driver.core; + +/** + * Produces {@link EndPoint} instances representing the connection information to every node. + * + *

This component is reserved for advanced use cases where the driver needs more than an IP + * address to connect. + * + *

Note that if endpoints do not translate to addresses 1-to-1, the auth provider and SSL options + * should be instances of {@link ExtendedAuthProvider} and {@link + * ExtendedRemoteEndpointAwareSslOptions} respectively. + */ +public interface EndPointFactory { + + void init(Cluster cluster); + + /** + * Creates an instance from a row in {@code system.peers}, or returns {@code null} if there is no + * sufficient information. + */ + EndPoint create(Row peersRow); +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/EventDebouncer.java b/driver-core/src/main/java/com/datastax/driver/core/EventDebouncer.java index 430a80ebbd6..d3ac3e8c452 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/EventDebouncer.java +++ b/driver-core/src/main/java/com/datastax/driver/core/EventDebouncer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -117,6 +119,12 @@ void stop() { break; } } + while (true) { + DeliveryAttempt previous = cancelImmediateDelivery(); + if (immediateDelivery.compareAndSet(previous, null)) { + break; + } + } completeAllPendingFutures(); @@ -205,14 +213,21 @@ private void scheduleDelayedDelivery() { } private DeliveryAttempt cancelDelayedDelivery() { - DeliveryAttempt previous = delayedDelivery.get(); + return cancelDelivery(delayedDelivery.get()); + } + + private DeliveryAttempt cancelImmediateDelivery() { + return cancelDelivery(immediateDelivery.get()); + } + + private DeliveryAttempt cancelDelivery(DeliveryAttempt previous) { if (previous != null) { previous.cancel(); } return previous; } - void deliverEvents() { + private void deliverEvents() { if (state == State.STOPPED) { completeAllPendingFutures(); return; diff --git a/driver-core/src/main/java/com/datastax/driver/core/ExceptionCatchingRunnable.java b/driver-core/src/main/java/com/datastax/driver/core/ExceptionCatchingRunnable.java index 345e26d2b17..9e2d136100b 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ExceptionCatchingRunnable.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ExceptionCatchingRunnable.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/ExceptionCode.java b/driver-core/src/main/java/com/datastax/driver/core/ExceptionCode.java index b6c6d0af50f..7b5b91237fb 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ExceptionCode.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ExceptionCode.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,8 @@ enum ExceptionCode { READ_FAILURE(0x1300), FUNCTION_FAILURE(0x1400), WRITE_FAILURE(0x1500), + CDC_WRITE_FAILURE(0x1600), + CAS_WRITE_UNKNOWN(0x1700), // 2xx: problem validating the request SYNTAX_ERROR(0x2000), diff --git a/driver-core/src/main/java/com/datastax/driver/core/ExecutionInfo.java b/driver-core/src/main/java/com/datastax/driver/core/ExecutionInfo.java index 5459b0a592c..6b1c606782b 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ExecutionInfo.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/ExtendedAuthProvider.java b/driver-core/src/main/java/com/datastax/driver/core/ExtendedAuthProvider.java new file mode 100644 index 00000000000..d381c6210c0 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/ExtendedAuthProvider.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.driver.core; + +import com.datastax.driver.core.exceptions.AuthenticationException; +import java.net.InetSocketAddress; + +/** + * An auth provider that represents the host as an {@link EndPoint} instead of a raw {@link + * InetSocketAddress}. + * + *

This interface exists solely for backward compatibility: it wasn't possible to change {@link + * AuthProvider} directly, because it would have broken every 3rd-party implementation. + * + *

All built-in providers now implement this interface, and it is recommended that new + * implementations do too. + * + *

When the driver calls an auth provider, it will check if it implements this interface. If so, + * it will call {@link #newAuthenticator(EndPoint, String)}; otherwise it will convert the endpoint + * into an address with {@link EndPoint#resolve()} and call {@link + * AuthProvider#newAuthenticator(InetSocketAddress, String)}. + */ +public interface ExtendedAuthProvider extends AuthProvider { + + /** + * The {@code Authenticator} to use when connecting to {@code endpoint}. + * + * @param endPoint the Cassandra host to connect to. + * @param authenticator the configured authenticator on the host. + * @return The authentication implementation to use. + */ + Authenticator newAuthenticator(EndPoint endPoint, String authenticator) + throws AuthenticationException; + + /** + * @deprecated the driver will never call this method on {@link ExtendedAuthProvider} instances. + * Implementors should throw {@link AssertionError}. + */ + @Override + @Deprecated + Authenticator newAuthenticator(InetSocketAddress host, String authenticator) + throws AuthenticationException; + + class NoAuthProvider implements ExtendedAuthProvider { + + private static final String DSE_AUTHENTICATOR = + "com.datastax.bdp.cassandra.auth.DseAuthenticator"; + + static final String NO_AUTHENTICATOR_MESSAGE = + "Host %s requires authentication, but no authenticator found in Cluster configuration"; + + @Override + public Authenticator newAuthenticator(EndPoint endPoint, String authenticator) { + if (authenticator.equals(DSE_AUTHENTICATOR)) { + return new TransitionalModePlainTextAuthenticator(); + } + throw new AuthenticationException( + endPoint, String.format(NO_AUTHENTICATOR_MESSAGE, endPoint)); + } + + @Override + public Authenticator newAuthenticator(InetSocketAddress host, String authenticator) + throws AuthenticationException { + throw new AssertionError( + "The driver should never call this method on an object that implements " + + this.getClass().getSimpleName()); + } + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/ExtendedRemoteEndpointAwareSslOptions.java b/driver-core/src/main/java/com/datastax/driver/core/ExtendedRemoteEndpointAwareSslOptions.java new file mode 100644 index 00000000000..e7826c5fe15 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/ExtendedRemoteEndpointAwareSslOptions.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +import io.netty.channel.socket.SocketChannel; +import io.netty.handler.ssl.SslHandler; + +public interface ExtendedRemoteEndpointAwareSslOptions extends RemoteEndpointAwareSSLOptions { + + /** + * Creates a new SSL handler for the given Netty channel and the given remote endpoint. + * + *

This gets called each time the driver opens a new connection to a Cassandra host. The newly + * created handler will be added to the channel's pipeline to provide SSL support for the + * connection. + * + *

You don't necessarily need to implement this method directly; see the provided + * implementations: {@link RemoteEndpointAwareJdkSSLOptions} and {@link + * RemoteEndpointAwareNettySSLOptions}. + * + * @param channel the channel. + * @param remoteEndpoint the remote endpoint information. + * @return a newly-created {@link SslHandler}. + */ + SslHandler newSSLHandler(SocketChannel channel, EndPoint remoteEndpoint); +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/Frame.java b/driver-core/src/main/java/com/datastax/driver/core/Frame.java index 36d6ee37e7b..2221130cc56 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Frame.java +++ b/driver-core/src/main/java/com/datastax/driver/core/Frame.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -87,33 +89,18 @@ class Frame { final Header header; final ByteBuf body; - private Frame(Header header, ByteBuf body) { + Frame(Header header, ByteBuf body) { this.header = header; this.body = body; } private static Frame create(ByteBuf fullFrame) { - assert fullFrame.readableBytes() >= 1 - : String.format("Frame too short (%d bytes)", fullFrame.readableBytes()); - - int versionBytes = fullFrame.readByte(); - // version first byte is the "direction" of the frame (request or response) - ProtocolVersion version = ProtocolVersion.fromInt(versionBytes & 0x7F); - int hdrLen = Header.lengthFor(version); - assert fullFrame.readableBytes() >= (hdrLen - 1) - : String.format("Frame too short (%d bytes)", fullFrame.readableBytes()); - - int flags = fullFrame.readByte(); - int streamId = readStreamid(fullFrame, version); - int opcode = fullFrame.readByte(); - int length = fullFrame.readInt(); - assert length == fullFrame.readableBytes(); - - Header header = new Header(version, flags, streamId, opcode); + Header header = Header.decode(fullFrame); + assert header.bodyLength == fullFrame.readableBytes(); return new Frame(header, fullFrame); } - private static int readStreamid(ByteBuf fullFrame, ProtocolVersion version) { + private static int readStreamId(ByteBuf fullFrame, ProtocolVersion version) { switch (version) { case V1: case V2: @@ -121,6 +108,7 @@ private static int readStreamid(ByteBuf fullFrame, ProtocolVersion version) { case V3: case V4: case V5: + case V6: return fullFrame.readShort(); default: throw version.unsupported(); @@ -129,7 +117,7 @@ private static int readStreamid(ByteBuf fullFrame, ProtocolVersion version) { static Frame create( ProtocolVersion version, int opcode, int streamId, EnumSet flags, ByteBuf body) { - Header header = new Header(version, flags, streamId, opcode); + Header header = new Header(version, flags, streamId, opcode, body.readableBytes()); return new Frame(header, body); } @@ -139,16 +127,22 @@ static class Header { final EnumSet flags; final int streamId; final int opcode; + final int bodyLength; - private Header(ProtocolVersion version, int flags, int streamId, int opcode) { - this(version, Flag.deserialize(flags), streamId, opcode); + private Header(ProtocolVersion version, int flags, int streamId, int opcode, int bodyLength) { + this(version, Flag.deserialize(flags), streamId, opcode, bodyLength); } - private Header(ProtocolVersion version, EnumSet flags, int streamId, int opcode) { + Header(ProtocolVersion version, EnumSet flags, int streamId, int opcode, int bodyLength) { this.version = version; this.flags = flags; this.streamId = streamId; this.opcode = opcode; + this.bodyLength = bodyLength; + } + + Header withNewBodyLength(int newBodyLength) { + return new Header(version, flags, streamId, opcode, newBodyLength); } /** @@ -165,12 +159,54 @@ static int lengthFor(ProtocolVersion version) { case V3: case V4: case V5: + case V6: return 9; default: throw version.unsupported(); } } + public void encodeInto(ByteBuf destination) { + // Don't bother with the direction, we only send requests. + destination.writeByte(version.toInt()); + destination.writeByte(Flag.serialize(flags)); + switch (version) { + case V1: + case V2: + destination.writeByte(streamId); + break; + case V3: + case V4: + case V5: + case V6: + destination.writeShort(streamId); + break; + default: + throw version.unsupported(); + } + destination.writeByte(opcode); + destination.writeInt(bodyLength); + } + + static Header decode(ByteBuf buffer) { + assert buffer.readableBytes() >= 1 + : String.format("Frame too short (%d bytes)", buffer.readableBytes()); + + int versionBytes = buffer.readByte(); + // version first byte is the "direction" of the frame (request or response) + ProtocolVersion version = ProtocolVersion.fromInt(versionBytes & 0x7F); + int hdrLen = Header.lengthFor(version); + assert buffer.readableBytes() >= (hdrLen - 1) + : String.format("Frame too short (%d bytes)", buffer.readableBytes()); + + int flags = buffer.readByte(); + int streamId = readStreamId(buffer, version); + int opcode = buffer.readByte(); + int length = buffer.readInt(); + + return new Header(version, flags, streamId, opcode, length); + } + enum Flag { // The order of that enum matters!! COMPRESSED, @@ -197,7 +233,7 @@ static int serialize(EnumSet flags) { } Frame with(ByteBuf newBody) { - return new Frame(header, newBody); + return new Frame(header.withNewBodyLength(newBody.readableBytes()), newBody); } static final class Decoder extends ByteToMessageDecoder { @@ -273,32 +309,11 @@ protected void encode(ChannelHandlerContext ctx, Frame frame, List out) throws Exception { ProtocolVersion protocolVersion = frame.header.version; ByteBuf header = ctx.alloc().ioBuffer(Frame.Header.lengthFor(protocolVersion)); - // We don't bother with the direction, we only send requests. - header.writeByte(frame.header.version.toInt()); - header.writeByte(Header.Flag.serialize(frame.header.flags)); - writeStreamId(frame.header.streamId, header, protocolVersion); - header.writeByte(frame.header.opcode); - header.writeInt(frame.body.readableBytes()); + frame.header.encodeInto(header); out.add(header); out.add(frame.body); } - - private void writeStreamId(int streamId, ByteBuf header, ProtocolVersion protocolVersion) { - switch (protocolVersion) { - case V1: - case V2: - header.writeByte(streamId); - break; - case V3: - case V4: - case V5: - header.writeShort(streamId); - break; - default: - throw protocolVersion.unsupported(); - } - } } static class Decompressor extends MessageToMessageDecoder { diff --git a/driver-core/src/main/java/com/datastax/driver/core/FrameCompressor.java b/driver-core/src/main/java/com/datastax/driver/core/FrameCompressor.java index d38e230d7d2..4063b131ddc 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/FrameCompressor.java +++ b/driver-core/src/main/java/com/datastax/driver/core/FrameCompressor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,17 @@ abstract class FrameCompressor { abstract Frame compress(Frame frame) throws IOException; + /** + * Unlike {@link #compress(Frame)}, this variant does not store the uncompressed length if the + * underlying algorithm does not do it natively (like LZ4). It must be stored separately and + * passed back to {@link #decompress(ByteBuf, int)}. + */ + abstract ByteBuf compress(ByteBuf buffer) throws IOException; + abstract Frame decompress(Frame frame) throws IOException; + abstract ByteBuf decompress(ByteBuf buffer, int uncompressedLength) throws IOException; + protected static ByteBuffer inputNioBuffer(ByteBuf buf) { // Using internalNioBuffer(...) as we only hold the reference in this method and so can // reduce Object allocations. diff --git a/driver-core/src/main/java/com/datastax/driver/core/FramingFormatHandler.java b/driver-core/src/main/java/com/datastax/driver/core/FramingFormatHandler.java new file mode 100644 index 00000000000..c59343df26e --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/FramingFormatHandler.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.driver.core; + +import com.datastax.driver.core.Message.Response.Type; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPipeline; +import io.netty.handler.codec.MessageToMessageDecoder; +import java.util.List; + +/** + * A handler to deal with different protocol framing formats. + * + *

This handler detects when a handshake is successful; then, if necessary, adapts the pipeline + * to the modern framing format introduced in protocol v5. + */ +public class FramingFormatHandler extends MessageToMessageDecoder { + + private final Connection.Factory factory; + + FramingFormatHandler(Connection.Factory factory) { + this.factory = factory; + } + + @Override + protected void decode(ChannelHandlerContext ctx, Frame frame, List out) throws Exception { + boolean handshakeSuccessful = + frame.header.opcode == Type.READY.opcode || frame.header.opcode == Type.AUTHENTICATE.opcode; + if (handshakeSuccessful) { + // By default, the pipeline is configured for legacy framing since this is the format used + // by all protocol versions until handshake; after handshake however, we need to switch to + // modern framing for protocol v5 and higher. + if (frame.header.version.compareTo(ProtocolVersion.V5) >= 0) { + switchToModernFraming(ctx); + } + // once the handshake is successful, the framing format cannot change anymore; + // we can safely remove ourselves from the pipeline. + ctx.pipeline().remove("framingFormatHandler"); + } + out.add(frame); + } + + private void switchToModernFraming(ChannelHandlerContext ctx) { + ChannelPipeline pipeline = ctx.pipeline(); + SegmentCodec segmentCodec = + new SegmentCodec( + ctx.channel().alloc(), factory.configuration.getProtocolOptions().getCompression()); + + // Outbound: "message -> segment -> bytes" instead of "message -> frame -> bytes" + Message.ProtocolEncoder requestEncoder = + (Message.ProtocolEncoder) pipeline.get("messageEncoder"); + pipeline.replace( + "messageEncoder", + "messageToSegmentEncoder", + new MessageToSegmentEncoder(ctx.channel().alloc(), requestEncoder)); + pipeline.replace( + "frameEncoder", "segmentToBytesEncoder", new SegmentToBytesEncoder(segmentCodec)); + + // Inbound: "frame <- segment <- bytes" instead of "frame <- bytes" + pipeline.replace( + "frameDecoder", "bytesToSegmentDecoder", new BytesToSegmentDecoder(segmentCodec)); + pipeline.addAfter( + "bytesToSegmentDecoder", "segmentToFrameDecoder", new SegmentToFrameDecoder()); + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/FunctionMetadata.java b/driver-core/src/main/java/com/datastax/driver/core/FunctionMetadata.java index 55ed77053dd..f246e59bce2 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/FunctionMetadata.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/GettableByIndexData.java b/driver-core/src/main/java/com/datastax/driver/core/GettableByIndexData.java index c6fcf4c81bc..7a10bc8c558 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/GettableByIndexData.java +++ b/driver-core/src/main/java/com/datastax/driver/core/GettableByIndexData.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/GettableByNameData.java b/driver-core/src/main/java/com/datastax/driver/core/GettableByNameData.java index 7bc7b5bbec4..e74fa49e611 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/GettableByNameData.java +++ b/driver-core/src/main/java/com/datastax/driver/core/GettableByNameData.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/GettableData.java b/driver-core/src/main/java/com/datastax/driver/core/GettableData.java index e52aa6ca1fc..90fdaa2a730 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/GettableData.java +++ b/driver-core/src/main/java/com/datastax/driver/core/GettableData.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/GuavaCompatibility.java b/driver-core/src/main/java/com/datastax/driver/core/GuavaCompatibility.java index c4626ca539f..ec53806b7f7 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/GuavaCompatibility.java +++ b/driver-core/src/main/java/com/datastax/driver/core/GuavaCompatibility.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,10 +21,10 @@ import com.google.common.base.Function; import com.google.common.collect.BiMap; import com.google.common.collect.Maps; +import com.google.common.net.HostAndPort; import com.google.common.reflect.TypeToken; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.FutureFallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; @@ -71,7 +73,7 @@ public static void init() { * Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the * primary input fails, from the {@code Future} provided by the {@code fallback}. * - * @see Futures#withFallback(ListenableFuture, FutureFallback) + * @see Futures#withFallback(ListenableFuture, com.google.common.util.concurrent.FutureFallback) * @see Futures#catchingAsync(ListenableFuture, Class, AsyncFunction) */ public abstract ListenableFuture withFallback( @@ -81,7 +83,8 @@ public abstract ListenableFuture withFallback( * Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the * primary input fails, from the {@code Future} provided by the {@code fallback}. * - * @see Futures#withFallback(ListenableFuture, FutureFallback, Executor) + * @see Futures#withFallback(ListenableFuture, com.google.common.util.concurrent.FutureFallback, + * Executor) * @see Futures#catchingAsync(ListenableFuture, Class, AsyncFunction, Executor) */ public abstract ListenableFuture withFallback( @@ -180,6 +183,24 @@ public abstract ListenableFuture transformAsync( */ public abstract Executor sameThreadExecutor(); + /** + * Returns the portion of the given {@link HostAndPort} instance that should represent the + * hostname or IPv4/IPv6 literal. + * + *

The method {@code HostAndPort.getHostText} has been replaced with {@code + * HostAndPort.getHost} starting with Guava 20.0; it has been completely removed in Guava 22.0. + */ + @SuppressWarnings("JavaReflectionMemberAccess") + public String getHost(HostAndPort hostAndPort) { + try { + // Guava >= 20.0 + return (String) HostAndPort.class.getMethod("getHost").invoke(hostAndPort); + } catch (Exception e) { + // Guava < 22.0 + return hostAndPort.getHostText(); + } + } + private static GuavaCompatibility selectImplementation() { if (isGuava_19_0_OrHigher()) { logger.info("Detected Guava >= 19 in the classpath, using modern compatibility layer"); @@ -201,7 +222,7 @@ public ListenableFuture withFallback( ListenableFuture input, final AsyncFunction fallback) { return Futures.withFallback( input, - new FutureFallback() { + new com.google.common.util.concurrent.FutureFallback() { @Override public ListenableFuture create(Throwable t) throws Exception { return fallback.apply(t); @@ -216,7 +237,7 @@ public ListenableFuture withFallback( Executor executor) { return Futures.withFallback( input, - new FutureFallback() { + new com.google.common.util.concurrent.FutureFallback() { @Override public ListenableFuture create(Throwable t) throws Exception { return fallback.apply(t); diff --git a/driver-core/src/main/java/com/datastax/driver/core/Host.java b/driver-core/src/main/java/com/datastax/driver/core/Host.java index fea67bade97..c904f7957eb 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Host.java +++ b/driver-core/src/main/java/com/datastax/driver/core/Host.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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.driver.core; -import com.datastax.driver.core.policies.AddressTranslator; import com.google.common.util.concurrent.ListenableFuture; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -38,7 +39,11 @@ public class Host { static final Logger statesLogger = LoggerFactory.getLogger(Host.class.getName() + ".STATES"); // The address we'll use to connect to the node - private final InetSocketAddress address; + private final EndPoint endPoint; + + // The broadcast RPC address, as reported in system tables. + // Note that, unlike previous versions of the driver, this address is NOT TRANSLATED. + private volatile InetSocketAddress broadcastRpcAddress; // The broadcast_address as known by Cassandra. // We use that internally because @@ -84,16 +89,13 @@ enum State { private volatile boolean dseGraphEnabled; private volatile VersionNumber dseVersion; - // ClusterMetadata keeps one Host object per inet address and we rely on this (more precisely, - // we rely on the fact that we can use Object equality as a valid equality), so don't use - // that constructor but ClusterMetadata.getHost instead. Host( - InetSocketAddress address, + EndPoint endPoint, ConvictionPolicy.Factory convictionPolicyFactory, Cluster.Manager manager) { - if (address == null || convictionPolicyFactory == null) throw new NullPointerException(); + if (endPoint == null || convictionPolicyFactory == null) throw new NullPointerException(); - this.address = address; + this.endPoint = endPoint; this.convictionPolicy = convictionPolicyFactory.create(this, manager.reconnectionPolicy()); this.manager = manager; this.defaultExecutionInfo = new ExecutionInfo(this); @@ -118,6 +120,10 @@ void setVersion(String cassandraVersion) { this.cassandraVersion = versionNumber; } + void setBroadcastRpcAddress(InetSocketAddress broadcastRpcAddress) { + this.broadcastRpcAddress = broadcastRpcAddress; + } + void setBroadcastSocketAddress(InetSocketAddress broadcastAddress) { this.broadcastSocketAddress = broadcastAddress; } @@ -159,38 +165,56 @@ boolean supports(ProtocolVersion version) { || version.minCassandraVersion().compareTo(getCassandraVersion().nextStable()) <= 0; } + /** Returns information to connect to the node. */ + public EndPoint getEndPoint() { + return endPoint; + } + /** * Returns the address that the driver will use to connect to the node. * - *

This is a shortcut for {@code getSocketAddress().getAddress()}. - * - * @return the address. - * @see #getSocketAddress() + * @deprecated This is exposed mainly for historical reasons. Internally, the driver uses {@link + * #getEndPoint()} to establish connections. This is a shortcut for {@code + * getEndPoint().resolve().getAddress()}. */ + @Deprecated public InetAddress getAddress() { - return address.getAddress(); + return endPoint.resolve().getAddress(); } /** * Returns the address and port that the driver will use to connect to the node. * - *

This is the node's broadcast RPC address, possibly translated if an {@link - * AddressTranslator} has been configured for this cluster. - * - *

The broadcast RPC address is inferred from the following cassandra.yaml file settings: - * - *

    - *
  1. {@code rpc_address}, {@code rpc_interface} or {@code broadcast_rpc_address} - *
  2. {@code native_transport_port} - *
- * - * @return the address and port. + * @deprecated This is exposed mainly for historical reasons. Internally, the driver uses {@link + * #getEndPoint()} to establish connections. This is a shortcut for {@code + * getEndPoint().resolve()}. * @see The * cassandra.yaml configuration file */ + @Deprecated public InetSocketAddress getSocketAddress() { - return address; + return endPoint.resolve(); + } + + /** + * Returns the broadcast RPC address, as reported by the node. + * + *

This is address reported in {@code system.peers.rpc_address} (Cassandra 3) or {@code + * system.peers_v2.native_address/native_port} (Cassandra 4+). + * + *

Note that this is not necessarily the address that the driver will use to connect: if the + * node is accessed through a proxy, a translation might be necessary; this is handled by {@link + * #getEndPoint()}. + * + *

For versions of Cassandra less than 2.0.16, 2.1.6 or 2.2.0-rc1, this will be {@code null} + * for the control host. It will get updated if the control connection switches to another host. + * + * @see CASSANDRA-9436 (where the + * information was added for the control host) + */ + public InetSocketAddress getBroadcastRpcAddress() { + return broadcastRpcAddress; } /** @@ -319,7 +343,7 @@ public VersionNumber getCassandraVersion() { * {@code null}, and the caller should always be aware of this possibility. * * @return the DSE version the host is running. - * @deprecated Please use the Java driver + * @deprecated Please use the Java Driver * for DSE if you are connecting to a DataStax Enterprise (DSE) cluster. This method might * not function properly with future versions of DSE. */ @@ -335,9 +359,9 @@ public VersionNumber getDseVersion() { * {@code null}, and the caller should always be aware of this possibility. * * @return the DSE workload the host is running. - * @deprecated Please use the Java driver - * for DSE if you are connecting to a DataStax Enterprise (DSE) cluster. This method might - * not function properly with future versions of DSE. + * @deprecated Please use the Java + * Driver for DSE if you are connecting to a DataStax Enterprise (DSE) cluster. This + * method might not function properly with future versions of DSE. */ @Deprecated public String getDseWorkload() { @@ -348,9 +372,9 @@ public String getDseWorkload() { * Returns whether the host is running DSE Graph. * * @return whether the node is running DSE Graph. - * @deprecated Please use the Java driver - * for DSE if you are connecting to a DataStax Enterprise (DSE) cluster. This method might - * not function properly with future versions of DSE. + * @deprecated Please use the Java + * Driver for DSE if you are connecting to a DataStax Enterprise (DSE) cluster. This + * method might not function properly with future versions of DSE. */ @Deprecated public boolean isDseGraphEnabled() { @@ -463,14 +487,14 @@ public void tryReconnectOnce() { public boolean equals(Object other) { if (other instanceof Host) { Host that = (Host) other; - return this.address.equals(that.address); + return this.endPoint.equals(that.endPoint); } return false; } @Override public int hashCode() { - return address.hashCode(); + return endPoint.hashCode(); } boolean wasJustAdded() { @@ -479,7 +503,7 @@ boolean wasJustAdded() { @Override public String toString() { - return address.toString(); + return endPoint.toString(); } void setDown() { diff --git a/driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java b/driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java index aa17a0ea2b1..82ba3963a6e 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +++ b/driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 +172,7 @@ public void onSuccess(List l) { if (isClosed()) { initFuture.setException( new ConnectionException( - host.getSocketAddress(), "Pool was closed during initialization")); + host.getEndPoint(), "Pool was closed during initialization")); // we're not sure if closeAsync() saw the connections, so ensure they get closed forceClose(connections); } else { @@ -238,7 +240,7 @@ ListenableFuture borrowConnection(long timeout, TimeUnit unit, int m Phase phase = this.phase.get(); if (phase != Phase.READY) return Futures.immediateFailedFuture( - new ConnectionException(host.getSocketAddress(), "Pool is " + phase)); + new ConnectionException(host.getEndPoint(), "Pool is " + phase)); if (connections.isEmpty()) { if (host.convictionPolicy.canReconnectNow()) { @@ -270,7 +272,7 @@ ListenableFuture borrowConnection(long timeout, TimeUnit unit, int m // We could have raced with a shutdown since the last check if (isClosed()) return Futures.immediateFailedFuture( - new ConnectionException(host.getSocketAddress(), "Pool is shutdown")); + new ConnectionException(host.getEndPoint(), "Pool is shutdown")); // This might maybe happen if the number of core connections per host is 0 and a connection // was trashed between // the previous check to connections and now. But in that case, the line above will have @@ -316,14 +318,14 @@ ListenableFuture borrowConnection(long timeout, TimeUnit unit, int m private ListenableFuture enqueue(long timeout, TimeUnit unit, int maxQueueSize) { if (timeout == 0 || maxQueueSize == 0) { - return Futures.immediateFailedFuture(new BusyPoolException(host.getSocketAddress(), 0)); + return Futures.immediateFailedFuture(new BusyPoolException(host.getEndPoint(), 0)); } while (true) { int count = pendingBorrowCount.get(); if (count >= maxQueueSize) { return Futures.immediateFailedFuture( - new BusyPoolException(host.getSocketAddress(), maxQueueSize)); + new BusyPoolException(host.getEndPoint(), maxQueueSize)); } if (pendingBorrowCount.compareAndSet(count, count + 1)) { break; @@ -337,14 +339,13 @@ private ListenableFuture enqueue(long timeout, TimeUnit unit, int ma // was properly // handled in closeAsync. if (phase.get() == Phase.CLOSING) { - pendingBorrow.setException( - new ConnectionException(host.getSocketAddress(), "Pool is shutdown")); + pendingBorrow.setException(new ConnectionException(host.getEndPoint(), "Pool is shutdown")); } return pendingBorrow.future; } - void returnConnection(Connection connection) { + void returnConnection(Connection connection, boolean busy) { connection.inFlight.decrementAndGet(); totalInFlight.decrementAndGet(); @@ -362,7 +363,7 @@ void returnConnection(Connection connection) { if (connection.state.get() != TRASHED) { if (connection.maxAvailableStreams() < minAllowedStreams) { replaceConnection(connection); - } else { + } else if (!busy) { dequeue(connection); } } @@ -658,8 +659,7 @@ final CloseFuture closeAsync() { phase.set(Phase.CLOSING); for (PendingBorrow pendingBorrow : pendingBorrows) { - pendingBorrow.setException( - new ConnectionException(host.getSocketAddress(), "Pool is shutdown")); + pendingBorrow.setException(new ConnectionException(host.getEndPoint(), "Pool is shutdown")); } future = new CloseFuture.Forwarding(discardAvailableConnections()); @@ -743,8 +743,7 @@ private class PendingBorrow { new Runnable() { @Override public void run() { - future.setException( - new BusyPoolException(host.getSocketAddress(), timeout, unit)); + future.setException(new BusyPoolException(host.getEndPoint(), timeout, unit)); } }, timeout, diff --git a/driver-core/src/main/java/com/datastax/driver/core/HostDistance.java b/driver-core/src/main/java/com/datastax/driver/core/HostDistance.java index b04d4a7a5b0..7056d429618 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/HostDistance.java +++ b/driver-core/src/main/java/com/datastax/driver/core/HostDistance.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/IgnoreJDK6Requirement.java b/driver-core/src/main/java/com/datastax/driver/core/IgnoreJDK6Requirement.java new file mode 100644 index 00000000000..4a870970f93 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/IgnoreJDK6Requirement.java @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +/** + * Annotation used to mark classes in this project as excluded from JDK 6 signature check performed + * by animal-sniffer + * Maven plugin as they require JDK 8 or higher. + */ +public @interface IgnoreJDK6Requirement {} diff --git a/driver-core/src/main/java/com/datastax/driver/core/InboundTrafficMeter.java b/driver-core/src/main/java/com/datastax/driver/core/InboundTrafficMeter.java index 872ebac1b1d..18e5cf3e562 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/InboundTrafficMeter.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/IndexMetadata.java b/driver-core/src/main/java/com/datastax/driver/core/IndexMetadata.java index 7a1c9ee86ca..395b94fba9b 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/IndexMetadata.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/JdkSSLOptions.java b/driver-core/src/main/java/com/datastax/driver/core/JdkSSLOptions.java index e61db79ab8b..a4f7cdf5c95 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/JdkSSLOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/JdkSSLOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java b/driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java index 2f893cf42c8..b4b8b8eec5f 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/LZ4Compressor.java b/driver-core/src/main/java/com/datastax/driver/core/LZ4Compressor.java index 2a0a3d15b11..d639b8272fc 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/LZ4Compressor.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -59,24 +61,41 @@ private LZ4Compressor() { @Override Frame compress(Frame frame) throws IOException { ByteBuf input = frame.body; - - // TODO: JAVA-1306: Use the same API calls for direct and heap buffers when LZ4 updated. - ByteBuf frameBody = input.isDirect() ? compressDirect(input) : compressHeap(input); + ByteBuf frameBody = compress(input, true); return frame.with(frameBody); } - private ByteBuf compressDirect(ByteBuf input) throws IOException { + @Override + ByteBuf compress(ByteBuf buffer) throws IOException { + return compress(buffer, false); + } + + private ByteBuf compress(ByteBuf buffer, boolean prependWithUncompressedLength) + throws IOException { + return buffer.isDirect() + ? compressDirect(buffer, prependWithUncompressedLength) + : compressHeap(buffer, prependWithUncompressedLength); + } + + private ByteBuf compressDirect(ByteBuf input, boolean prependWithUncompressedLength) + throws IOException { int maxCompressedLength = compressor.maxCompressedLength(input.readableBytes()); // If the input is direct we will allocate a direct output buffer as well as this will allow us // to use // LZ4Compressor.compress and so eliminate memory copies. - ByteBuf output = input.alloc().directBuffer(INTEGER_BYTES + maxCompressedLength); + ByteBuf output = + input + .alloc() + .directBuffer( + (prependWithUncompressedLength ? INTEGER_BYTES : 0) + maxCompressedLength); try { ByteBuffer in = inputNioBuffer(input); // Increase reader index. input.readerIndex(input.writerIndex()); - output.writeInt(in.remaining()); + if (prependWithUncompressedLength) { + output.writeInt(in.remaining()); + } ByteBuffer out = outputNioBuffer(output); int written = @@ -92,7 +111,8 @@ private ByteBuf compressDirect(ByteBuf input) throws IOException { return output; } - private ByteBuf compressHeap(ByteBuf input) throws IOException { + private ByteBuf compressHeap(ByteBuf input, boolean prependWithUncompressedLength) + throws IOException { int maxCompressedLength = compressor.maxCompressedLength(input.readableBytes()); // Not a direct buffer so use byte arrays... @@ -105,9 +125,14 @@ private ByteBuf compressHeap(ByteBuf input) throws IOException { // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and // so // can eliminate the overhead of allocate a new byte[]. - ByteBuf output = input.alloc().heapBuffer(INTEGER_BYTES + maxCompressedLength); + ByteBuf output = + input + .alloc() + .heapBuffer((prependWithUncompressedLength ? INTEGER_BYTES : 0) + maxCompressedLength); try { - output.writeInt(len); + if (prependWithUncompressedLength) { + output.writeInt(len); + } // calculate the correct offset. int offset = output.arrayOffset() + output.writerIndex(); byte[] out = output.array(); @@ -126,18 +151,23 @@ private ByteBuf compressHeap(ByteBuf input) throws IOException { @Override Frame decompress(Frame frame) throws IOException { ByteBuf input = frame.body; - - // TODO: JAVA-1306: Use the same API calls for direct and heap buffers when LZ4 updated. - ByteBuf frameBody = input.isDirect() ? decompressDirect(input) : decompressHeap(input); + int uncompressedLength = input.readInt(); + ByteBuf frameBody = decompress(input, uncompressedLength); return frame.with(frameBody); } - private ByteBuf decompressDirect(ByteBuf input) throws IOException { + @Override + ByteBuf decompress(ByteBuf buffer, int uncompressedLength) throws IOException { + return buffer.isDirect() + ? decompressDirect(buffer, uncompressedLength) + : decompressHeap(buffer, uncompressedLength); + } + + private ByteBuf decompressDirect(ByteBuf input, int uncompressedLength) throws IOException { // If the input is direct we will allocate a direct output buffer as well as this will allow us // to use // LZ4Compressor.decompress and so eliminate memory copies. int readable = input.readableBytes(); - int uncompressedLength = input.readInt(); ByteBuffer in = inputNioBuffer(input); // Increase reader index. input.readerIndex(input.writerIndex()); @@ -145,7 +175,7 @@ private ByteBuf decompressDirect(ByteBuf input) throws IOException { try { ByteBuffer out = outputNioBuffer(output); int read = decompressor.decompress(in, in.position(), out, out.position(), out.remaining()); - if (read != readable - INTEGER_BYTES) throw new IOException("Compressed lengths mismatch"); + if (read != readable) throw new IOException("Compressed lengths mismatch"); // Set the writer index so the amount of written bytes is reflected output.writerIndex(output.writerIndex() + uncompressedLength); @@ -157,11 +187,10 @@ private ByteBuf decompressDirect(ByteBuf input) throws IOException { return output; } - private ByteBuf decompressHeap(ByteBuf input) throws IOException { + private ByteBuf decompressHeap(ByteBuf input, int uncompressedLength) throws IOException { // Not a direct buffer so use byte arrays... byte[] in = input.array(); int len = input.readableBytes(); - int uncompressedLength = input.readInt(); int inOffset = input.arrayOffset() + input.readerIndex(); // Increase reader index. input.readerIndex(input.writerIndex()); @@ -174,7 +203,7 @@ private ByteBuf decompressHeap(ByteBuf input) throws IOException { int offset = output.arrayOffset() + output.writerIndex(); byte out[] = output.array(); int read = decompressor.decompress(in, inOffset, out, offset, uncompressedLength); - if (read != len - INTEGER_BYTES) throw new IOException("Compressed lengths mismatch"); + if (read != len) throw new IOException("Compressed lengths mismatch"); // Set the writer index so the amount of written bytes is reflected output.writerIndex(output.writerIndex() + uncompressedLength); diff --git a/driver-core/src/main/java/com/datastax/driver/core/LatencyTracker.java b/driver-core/src/main/java/com/datastax/driver/core/LatencyTracker.java index 27a248629cf..6dec2f9db96 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/LatencyTracker.java +++ b/driver-core/src/main/java/com/datastax/driver/core/LatencyTracker.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/LocalDate.java b/driver-core/src/main/java/com/datastax/driver/core/LocalDate.java index 8b6bb33a317..271b53f581d 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/LocalDate.java +++ b/driver-core/src/main/java/com/datastax/driver/core/LocalDate.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/LoggingMonotonicTimestampGenerator.java b/driver-core/src/main/java/com/datastax/driver/core/LoggingMonotonicTimestampGenerator.java index 1667af3fc84..676e01da47a 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/LoggingMonotonicTimestampGenerator.java +++ b/driver-core/src/main/java/com/datastax/driver/core/LoggingMonotonicTimestampGenerator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/MD5Digest.java b/driver-core/src/main/java/com/datastax/driver/core/MD5Digest.java index 1edef4421a9..8665e11d794 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/MD5Digest.java +++ b/driver-core/src/main/java/com/datastax/driver/core/MD5Digest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/MaterializedViewMetadata.java b/driver-core/src/main/java/com/datastax/driver/core/MaterializedViewMetadata.java index aa948d34a5a..ca87a6c126b 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/MaterializedViewMetadata.java +++ b/driver-core/src/main/java/com/datastax/driver/core/MaterializedViewMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/Message.java b/driver-core/src/main/java/com/datastax/driver/core/Message.java index 74e3adb3270..05e9ef3500c 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Message.java +++ b/driver-core/src/main/java/com/datastax/driver/core/Message.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,8 +274,13 @@ static class ProtocolDecoder extends MessageToMessageDecoder { protected void decode(ChannelHandlerContext ctx, Frame frame, List out) throws Exception { boolean isTracing = frame.header.flags.contains(Frame.Header.Flag.TRACING); + boolean hasWarnings = frame.header.flags.contains(Frame.Header.Flag.WARNING); boolean isCustomPayload = frame.header.flags.contains(Frame.Header.Flag.CUSTOM_PAYLOAD); UUID tracingId = isTracing ? CBUtil.readUUID(frame.body) : null; + + List warnings = + hasWarnings ? CBUtil.readStringList(frame.body) : Collections.emptyList(); + Map customPayload = isCustomPayload ? CBUtil.readBytesMap(frame.body) : null; @@ -284,10 +291,6 @@ protected void decode(ChannelHandlerContext ctx, Frame frame, List out) CBUtil.sizeOfBytesMap(customPayload)); } - boolean hasWarnings = frame.header.flags.contains(Frame.Header.Flag.WARNING); - List warnings = - hasWarnings ? CBUtil.readStringList(frame.body) : Collections.emptyList(); - try { CodecRegistry codecRegistry = ctx.channel().attr(CODEC_REGISTRY_ATTRIBUTE_KEY).get(); assert codecRegistry != null; @@ -310,15 +313,33 @@ protected void decode(ChannelHandlerContext ctx, Frame frame, List out) @ChannelHandler.Sharable static class ProtocolEncoder extends MessageToMessageEncoder { - private final ProtocolVersion protocolVersion; + final ProtocolVersion protocolVersion; ProtocolEncoder(ProtocolVersion version) { this.protocolVersion = version; } @Override - protected void encode(ChannelHandlerContext ctx, Request request, List out) - throws Exception { + protected void encode(ChannelHandlerContext ctx, Request request, List out) { + EnumSet flags = computeFlags(request); + int messageSize = encodedSize(request); + ByteBuf body = ctx.alloc().buffer(messageSize); + encode(request, body); + + if (body.capacity() != messageSize) { + logger.debug( + "Detected buffer resizing while encoding {} message ({} => {}), " + + "this is a driver bug " + + "(ultimately it does not affect the query, but leads to a small inefficiency)", + request.type, + messageSize, + body.capacity()); + } + out.add( + Frame.create(protocolVersion, request.type.opcode, request.getStreamId(), flags, body)); + } + + EnumSet computeFlags(Request request) { EnumSet flags = EnumSet.noneOf(Frame.Header.Flag.class); if (request.isTracingRequested()) flags.add(Frame.Header.Flag.TRACING); if (protocolVersion == ProtocolVersion.NEWEST_BETA) flags.add(Frame.Header.Flag.USE_BETA); @@ -329,36 +350,37 @@ protected void encode(ChannelHandlerContext ctx, Request request, List o protocolVersion, "Custom payloads are only supported since native protocol V4"); flags.add(Frame.Header.Flag.CUSTOM_PAYLOAD); } + return flags; + } + int encodedSize(Request request) { @SuppressWarnings("unchecked") Coder coder = (Coder) request.type.coder; int messageSize = coder.encodedSize(request, protocolVersion); int payloadLength = -1; - if (customPayload != null) { - payloadLength = CBUtil.sizeOfBytesMap(customPayload); + if (request.getCustomPayload() != null) { + payloadLength = CBUtil.sizeOfBytesMap(request.getCustomPayload()); messageSize += payloadLength; } - ByteBuf body = ctx.alloc().buffer(messageSize); + return messageSize; + } + + void encode(Request request, ByteBuf destination) { + @SuppressWarnings("unchecked") + Coder coder = (Coder) request.type.coder; + + Map customPayload = request.getCustomPayload(); if (customPayload != null) { - CBUtil.writeBytesMap(customPayload, body); + CBUtil.writeBytesMap(customPayload, destination); if (logger.isTraceEnabled()) { logger.trace( - "Sending payload: {} ({} bytes total)", printPayload(customPayload), payloadLength); + "Sending payload: {} ({} bytes total)", + printPayload(customPayload), + CBUtil.sizeOfBytesMap(customPayload)); } } - coder.encode(request, body, protocolVersion); - if (body.capacity() != messageSize) { - logger.debug( - "Detected buffer resizing while encoding {} message ({} => {}), " - + "this is a driver bug " - + "(ultimately it does not affect the query, but leads to a small inefficiency)", - request.type, - messageSize, - body.capacity()); - } - out.add( - Frame.create(protocolVersion, request.type.opcode, request.getStreamId(), flags, body)); + coder.encode(request, destination, protocolVersion); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/MessageToSegmentEncoder.java b/driver-core/src/main/java/com/datastax/driver/core/MessageToSegmentEncoder.java new file mode 100644 index 00000000000..bad9e8fefb7 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/MessageToSegmentEncoder.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.driver.core; + +import io.netty.buffer.ByteBufAllocator; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelOutboundHandlerAdapter; +import io.netty.channel.ChannelPromise; + +class MessageToSegmentEncoder extends ChannelOutboundHandlerAdapter { + + private final ByteBufAllocator allocator; + private final Message.ProtocolEncoder requestEncoder; + + private SegmentBuilder segmentBuilder; + + MessageToSegmentEncoder(ByteBufAllocator allocator, Message.ProtocolEncoder requestEncoder) { + this.allocator = allocator; + this.requestEncoder = requestEncoder; + } + + @Override + public void handlerAdded(ChannelHandlerContext ctx) throws Exception { + super.handlerAdded(ctx); + this.segmentBuilder = new SegmentBuilder(ctx, allocator, requestEncoder); + } + + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) + throws Exception { + if (msg instanceof Message.Request) { + segmentBuilder.addRequest(((Message.Request) msg), promise); + } else { + super.write(ctx, msg, promise); + } + } + + @Override + public void flush(ChannelHandlerContext ctx) throws Exception { + segmentBuilder.flush(); + super.flush(ctx); + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/Metadata.java b/driver-core/src/main/java/com/datastax/driver/core/Metadata.java index 7ef5d9b2b8e..cb9a8821962 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Metadata.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -31,8 +33,10 @@ import java.util.Map; import java.util.Set; import java.util.TreeSet; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,8 +49,10 @@ public class Metadata { final Cluster.Manager cluster; volatile String clusterName; volatile String partitioner; - private final ConcurrentMap hosts = - new ConcurrentHashMap(); + // Holds the contact points until we have a connection to the cluster + private final List contactPoints = new CopyOnWriteArrayList(); + // The hosts, keyed by their host_id + private final ConcurrentMap hosts = new ConcurrentHashMap(); final ConcurrentMap keyspaces = new ConcurrentHashMap(); private volatile TokenMap tokenMap; @@ -146,24 +152,62 @@ void rebuildTokenMap(Token.Factory factory, Map> allTokens) { } } - Host newHost(InetSocketAddress address) { - return new Host(address, cluster.convictionPolicyFactory, cluster); + Host newHost(EndPoint endPoint) { + return new Host(endPoint, cluster.convictionPolicyFactory, cluster); + } + + void addContactPoint(EndPoint contactPoint) { + contactPoints.add(newHost(contactPoint)); + } + + List getContactPoints() { + return contactPoints; + } + + Host getContactPoint(EndPoint endPoint) { + for (Host host : contactPoints) { + if (host.getEndPoint().equals(endPoint)) { + return host; + } + } + return null; } /** - * @return the previous host associated with this socket address, or {@code null} if there was no - * such host. + * @return the previous host associated with this id, or {@code null} if there was no such host. */ Host addIfAbsent(Host host) { - return hosts.putIfAbsent(host.getSocketAddress(), host); + return hosts.putIfAbsent(host.getHostId(), host); } boolean remove(Host host) { - return hosts.remove(host.getSocketAddress()) != null; + return hosts.remove(host.getHostId()) != null; + } + + Host getHost(UUID hostId) { + return hosts.get(hostId); + } + + /** + * @param broadcastRpcAddress the untranslated broadcast RPC address, as indicated in + * server events. + */ + Host getHost(InetSocketAddress broadcastRpcAddress) { + for (Host host : hosts.values()) { + if (broadcastRpcAddress.equals(host.getBroadcastRpcAddress())) { + return host; + } + } + return null; } - Host getHost(InetSocketAddress address) { - return hosts.get(address); + Host getHost(EndPoint endPoint) { + for (Host host : hosts.values()) { + if (host.getEndPoint().equals(endPoint)) { + return host; + } + } + return null; } // For internal use only @@ -241,11 +285,16 @@ public static String quoteIfNecessary(String id) { /** * We don't need to escape an identifier if it matches non-quoted CQL3 ids ([a-z][a-z0-9_]*), and * if it's not a CQL reserved keyword. + * + *

When 'Migrating from compact storage' after DROP COMPACT STORAGE on the table, it can have a + * column with an empty name. (See JAVA-2174 for the reference) For that case, we need to escape + * empty column name. */ private static boolean needsQuote(String s) { // this method should only be called for C*-provided identifiers, - // so we expect it to be non-null and non-empty. - assert s != null && !s.isEmpty(); + // so we expect it to be non-null + assert s != null; + if (s.isEmpty()) return true; char c = s.charAt(0); if (!(c >= 97 && c <= 122)) // a-z return true; diff --git a/driver-core/src/main/java/com/datastax/driver/core/Metrics.java b/driver-core/src/main/java/com/datastax/driver/core/Metrics.java index 8f4498be490..744035b6885 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Metrics.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/MetricsOptions.java b/driver-core/src/main/java/com/datastax/driver/core/MetricsOptions.java index 71cd5405539..f069cf808bb 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/MetricsOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/MetricsOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/MetricsUtil.java b/driver-core/src/main/java/com/datastax/driver/core/MetricsUtil.java index 712244d3646..0c3d39eae22 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/MetricsUtil.java +++ b/driver-core/src/main/java/com/datastax/driver/core/MetricsUtil.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,25 @@ */ package com.datastax.driver.core; +import java.net.InetAddress; + public class MetricsUtil { public static String hostMetricName(String prefix, Host host) { + EndPoint endPoint = host.getEndPoint(); + if (endPoint instanceof TranslatedAddressEndPoint) { + InetAddress address = endPoint.resolve().getAddress(); + return hostMetricNameFromAddress(prefix, address); + } else { + // We have no guarantee that endpoints resolve to unique addresses + return prefix + endPoint.toString(); + } + } + + private static String hostMetricNameFromAddress(String prefix, InetAddress address) { StringBuilder result = new StringBuilder(prefix); boolean first = true; - for (byte b : host.getSocketAddress().getAddress().getAddress()) { + for (byte b : address.getAddress()) { if (first) { first = false; } else { diff --git a/driver-core/src/main/java/com/datastax/driver/core/Native.java b/driver-core/src/main/java/com/datastax/driver/core/Native.java index 9a28cb2ed6e..00f6a271e52 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Native.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java b/driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java index d75ed103c9c..8b2919ec836 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/NettySSLOptions.java b/driver-core/src/main/java/com/datastax/driver/core/NettySSLOptions.java index e1bf1217a37..295e3fd12de 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/NettySSLOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/NettySSLOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/NettyUtil.java b/driver-core/src/main/java/com/datastax/driver/core/NettyUtil.java index c551be5f6b6..1587169ea13 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/NettyUtil.java +++ b/driver-core/src/main/java/com/datastax/driver/core/NettyUtil.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/OutboundTrafficMeter.java b/driver-core/src/main/java/com/datastax/driver/core/OutboundTrafficMeter.java index 6855d0cac7a..701b3eb13cb 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/OutboundTrafficMeter.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/PagingIterable.java b/driver-core/src/main/java/com/datastax/driver/core/PagingIterable.java index 9e5af114dbf..606adf3be67 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/PagingIterable.java +++ b/driver-core/src/main/java/com/datastax/driver/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/driver-core/src/main/java/com/datastax/driver/core/PagingState.java b/driver-core/src/main/java/com/datastax/driver/core/PagingState.java index 477f72131c6..9f9398513b2 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/PagingState.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/ParseUtils.java b/driver-core/src/main/java/com/datastax/driver/core/ParseUtils.java index eff44740038..8bc9272d3b3 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ParseUtils.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/PerHostPercentileTracker.java b/driver-core/src/main/java/com/datastax/driver/core/PerHostPercentileTracker.java index 828a77698d0..7ea076d1c5f 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/PerHostPercentileTracker.java +++ b/driver-core/src/main/java/com/datastax/driver/core/PerHostPercentileTracker.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/PercentileTracker.java b/driver-core/src/main/java/com/datastax/driver/core/PercentileTracker.java index 1e8be97c5a7..cc60517745c 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/PercentileTracker.java +++ b/driver-core/src/main/java/com/datastax/driver/core/PercentileTracker.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -263,8 +265,9 @@ protected boolean include(Host host, Statement statement, Exception exception) { * errors are not good indicators of the host's responsiveness, and tend to make the host's score * look better than it actually is. */ + @SuppressWarnings("unchecked") private static final Set> EXCLUDED_EXCEPTIONS = - ImmutableSet.>of( + ImmutableSet.of( UnavailableException.class, // this is done via the snitch and is usually very fast OverloadedException.class, BootstrappingException.class, diff --git a/driver-core/src/main/java/com/datastax/driver/core/PlainTextAuthProvider.java b/driver-core/src/main/java/com/datastax/driver/core/PlainTextAuthProvider.java index 341e3d975e4..86f62ea4eab 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/PlainTextAuthProvider.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -15,6 +17,7 @@ */ package com.datastax.driver.core; +import com.datastax.driver.core.exceptions.AuthenticationException; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; import java.net.InetSocketAddress; @@ -27,7 +30,7 @@ * apply to all hosts. The PlainTextAuthenticator instances it returns support SASL authentication * using the PLAIN mechanism for version 2 (or above) of the CQL native protocol. */ -public class PlainTextAuthProvider implements AuthProvider { +public class PlainTextAuthProvider implements ExtendedAuthProvider { private volatile String username; private volatile String password; @@ -74,16 +77,23 @@ public void setPassword(String password) { * behalf of the client */ @Override - public Authenticator newAuthenticator(InetSocketAddress host, String authenticator) { + public Authenticator newAuthenticator(EndPoint host, String authenticator) { return new PlainTextAuthenticator(username, password); } + @Override + public Authenticator newAuthenticator(InetSocketAddress host, String authenticator) + throws AuthenticationException { + throw new AssertionError( + "The driver should never call this method on an object that implements " + + this.getClass().getSimpleName()); + } + /** * Simple implementation of {@link Authenticator} which can perform authentication against * Cassandra servers configured with PasswordAuthenticator. */ - private static class PlainTextAuthenticator extends ProtocolV1Authenticator - implements Authenticator { + static class PlainTextAuthenticator extends ProtocolV1Authenticator implements Authenticator { private final byte[] username; private final byte[] password; diff --git a/driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java b/driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java index 3741ef97ec0..c5de138c6af 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/PreparedId.java b/driver-core/src/main/java/com/datastax/driver/core/PreparedId.java index 7e2e4a66b92..28fef17cf92 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/PreparedId.java +++ b/driver-core/src/main/java/com/datastax/driver/core/PreparedId.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/PreparedStatement.java b/driver-core/src/main/java/com/datastax/driver/core/PreparedStatement.java index 3f2d1cf6cf2..4d324560db0 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/PreparedStatement.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/ProtocolEvent.java b/driver-core/src/main/java/com/datastax/driver/core/ProtocolEvent.java index e72a11e7cdd..a3bf0c244c6 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ProtocolEvent.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ProtocolEvent.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -155,6 +157,7 @@ static SchemaChange deserializeEvent(ByteBuf bb, ProtocolVersion version) { case V3: case V4: case V5: + case V6: change = CBUtil.readEnumValue(Change.class, bb); targetType = CBUtil.readEnumValue(SchemaElement.class, bb); targetKeyspace = CBUtil.readString(bb); diff --git a/driver-core/src/main/java/com/datastax/driver/core/ProtocolFeature.java b/driver-core/src/main/java/com/datastax/driver/core/ProtocolFeature.java index 57f9d6f79b9..b31a4977637 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ProtocolFeature.java +++ b/driver-core/src/main/java/com/datastax/driver/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, @@ -42,7 +44,7 @@ enum ProtocolFeature { boolean isSupportedBy(ProtocolVersion version) { switch (this) { case PREPARED_METADATA_CHANGES: - return version == ProtocolVersion.V5; + return version.compareTo(ProtocolVersion.V5) >= 0; case CUSTOM_PAYLOADS: return version.compareTo(ProtocolVersion.V4) >= 0; case CLIENT_TIMESTAMPS: diff --git a/driver-core/src/main/java/com/datastax/driver/core/ProtocolOptions.java b/driver-core/src/main/java/com/datastax/driver/core/ProtocolOptions.java index 4d4d215a049..853b3a58b14 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ProtocolOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ProtocolOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/ProtocolV1Authenticator.java b/driver-core/src/main/java/com/datastax/driver/core/ProtocolV1Authenticator.java index a5ee8009190..af774b07e12 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ProtocolV1Authenticator.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ProtocolV1Authenticator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/ProtocolVersion.java b/driver-core/src/main/java/com/datastax/driver/core/ProtocolVersion.java index e165c6b17e7..919d666228c 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ProtocolVersion.java +++ b/driver-core/src/main/java/com/datastax/driver/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, @@ -26,13 +28,14 @@ public enum ProtocolVersion { V2("2.0.0", 2, V1), V3("2.1.0", 3, V2), V4("2.2.0", 4, V3), - V5("3.10.0", 5, V4); + V5("4.0.0", 5, V4), + V6("4.0.0", 6, V5); /** The most recent protocol version supported by the driver. */ - public static final ProtocolVersion NEWEST_SUPPORTED = V4; + public static final ProtocolVersion NEWEST_SUPPORTED = V5; /** The most recent beta protocol version supported by the driver. */ - public static final ProtocolVersion NEWEST_BETA = V5; + public static final ProtocolVersion NEWEST_BETA = V6; private final VersionNumber minCassandraVersion; diff --git a/driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java b/driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java index 5cc70a03474..5621d2e8159 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java +++ b/driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -872,9 +874,9 @@ protected int appendParameters(BuiltStatement statement, StringBuilder buffer, i if (remaining == 0) { return 0; } - int numberOfParameters = - statement.getValues(protocolVersion(), cluster.getConfiguration().getCodecRegistry()) - .length; + ByteBuffer[] values = + statement.getValues(protocolVersion(), cluster.getConfiguration().getCodecRegistry()); + int numberOfParameters = values == null ? 0 : values.length; if (numberOfParameters > 0) { int numberOfLoggedParameters; if (remaining == -1) { diff --git a/driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java b/driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java index c1fb785ab04..31e93af4448 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -53,6 +55,7 @@ public class QueryOptions { private volatile int fetchSize = DEFAULT_FETCH_SIZE; private volatile boolean defaultIdempotence = DEFAULT_IDEMPOTENCE; + private volatile boolean consistencySet = false; private volatile boolean metadataEnabled = true; private volatile int maxPendingRefreshNodeListRequests = @@ -89,6 +92,7 @@ void register(Cluster.Manager manager) { * @return this {@code QueryOptions} instance. */ public QueryOptions setConsistencyLevel(ConsistencyLevel consistencyLevel) { + this.consistencySet = true; this.consistency = consistencyLevel; return this; } @@ -515,4 +519,8 @@ public int hashCode() { reprepareOnUp, prepareOnAllHosts); } + + public boolean isConsistencySet() { + return consistencySet; + } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/QueryTrace.java b/driver-core/src/main/java/com/datastax/driver/core/QueryTrace.java index 6ab199fe4b0..49318d363c1 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/QueryTrace.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/RegularStatement.java b/driver-core/src/main/java/com/datastax/driver/core/RegularStatement.java index 534bbc51a34..a9dbed930e8 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/RegularStatement.java +++ b/driver-core/src/main/java/com/datastax/driver/core/RegularStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,6 @@ import com.datastax.driver.core.querybuilder.BuiltStatement; import com.datastax.driver.core.schemabuilder.SchemaStatement; import java.nio.ByteBuffer; -import java.util.Arrays; import java.util.Map; /** @@ -195,14 +196,14 @@ public int requestSizeInBytes(ProtocolVersion protocolVersion, CodecRegistry cod case V3: case V4: case V5: + case V6: size += CBUtil.sizeOfConsistencyLevel(getConsistencyLevel()); size += QueryFlag.serializedSize(protocolVersion); if (hasValues()) { if (usesNamedValues()) { size += CBUtil.sizeOfNamedValueList(getNamedValues(protocolVersion, codecRegistry)); } else { - size += - CBUtil.sizeOfValueList(Arrays.asList(getValues(protocolVersion, codecRegistry))); + size += CBUtil.sizeOfValueList(getValues(protocolVersion, codecRegistry)); } } // Fetch size, serial CL and default timestamp also depend on session-level defaults diff --git a/driver-core/src/main/java/com/datastax/driver/core/RemoteEndpointAwareJdkSSLOptions.java b/driver-core/src/main/java/com/datastax/driver/core/RemoteEndpointAwareJdkSSLOptions.java index 7169a16b710..7a17ec691d2 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/RemoteEndpointAwareJdkSSLOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/RemoteEndpointAwareJdkSSLOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 @@ */ @SuppressWarnings("deprecation") public class RemoteEndpointAwareJdkSSLOptions extends JdkSSLOptions - implements RemoteEndpointAwareSSLOptions { + implements ExtendedRemoteEndpointAwareSslOptions { /** * Creates a builder to create a new instance. @@ -57,11 +59,19 @@ public SslHandler newSSLHandler(SocketChannel channel) { } @Override - public SslHandler newSSLHandler(SocketChannel channel, InetSocketAddress remoteEndpoint) { - SSLEngine engine = newSSLEngine(channel, remoteEndpoint); + public SslHandler newSSLHandler(SocketChannel channel, EndPoint remoteEndpoint) { + SSLEngine engine = + newSSLEngine(channel, remoteEndpoint == null ? null : remoteEndpoint.resolve()); return new SslHandler(engine); } + @Override + public SslHandler newSSLHandler(SocketChannel channel, InetSocketAddress remoteEndpoint) { + throw new AssertionError( + "The driver should never call this method on an object that implements " + + this.getClass().getSimpleName()); + } + /** * Creates an SSL engine each time a connection is established. * @@ -75,10 +85,12 @@ public SslHandler newSSLHandler(SocketChannel channel, InetSocketAddress remoteE */ protected SSLEngine newSSLEngine( @SuppressWarnings("unused") SocketChannel channel, InetSocketAddress remoteEndpoint) { - SSLEngine engine = - remoteEndpoint == null - ? context.createSSLEngine() - : context.createSSLEngine(remoteEndpoint.getHostName(), remoteEndpoint.getPort()); + SSLEngine engine; + if (remoteEndpoint == null) { + engine = context.createSSLEngine(); + } else { + engine = context.createSSLEngine(remoteEndpoint.getHostName(), remoteEndpoint.getPort()); + } engine.setUseClientMode(true); if (cipherSuites != null) engine.setEnabledCipherSuites(cipherSuites); return engine; diff --git a/driver-core/src/main/java/com/datastax/driver/core/RemoteEndpointAwareNettySSLOptions.java b/driver-core/src/main/java/com/datastax/driver/core/RemoteEndpointAwareNettySSLOptions.java index dfc3537ebbd..f2f4a809804 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/RemoteEndpointAwareNettySSLOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/RemoteEndpointAwareNettySSLOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 @@ */ @SuppressWarnings("deprecation") public class RemoteEndpointAwareNettySSLOptions extends NettySSLOptions - implements RemoteEndpointAwareSSLOptions { + implements ExtendedRemoteEndpointAwareSslOptions { /** * Create a new instance from a given context. @@ -49,9 +51,16 @@ public SslHandler newSSLHandler(SocketChannel channel) { "This class implements RemoteEndpointAwareSSLOptions, this method should not be called"); } + @Override + public SslHandler newSSLHandler(SocketChannel channel, EndPoint remoteEndpoint) { + InetSocketAddress address = remoteEndpoint.resolve(); + return context.newHandler(channel.alloc(), address.getHostName(), address.getPort()); + } + @Override public SslHandler newSSLHandler(SocketChannel channel, InetSocketAddress remoteEndpoint) { - return context.newHandler( - channel.alloc(), remoteEndpoint.getHostName(), remoteEndpoint.getPort()); + throw new AssertionError( + "The driver should never call this method on an object that implements " + + this.getClass().getSimpleName()); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/RemoteEndpointAwareSSLOptions.java b/driver-core/src/main/java/com/datastax/driver/core/RemoteEndpointAwareSSLOptions.java index 32d709076a1..41a537a3fca 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/RemoteEndpointAwareSSLOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/RemoteEndpointAwareSSLOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/ReplicationFactor.java b/driver-core/src/main/java/com/datastax/driver/core/ReplicationFactor.java new file mode 100644 index 00000000000..0d217f1092a --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/ReplicationFactor.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +// This class is a subset of server version at org.apache.cassandra.locator.ReplicationFactor + +class ReplicationFactor { + private final int allReplicas; + private final int fullReplicas; + private final int transientReplicas; + + ReplicationFactor(int allReplicas, int transientReplicas) { + this.allReplicas = allReplicas; + this.transientReplicas = transientReplicas; + this.fullReplicas = allReplicas - transientReplicas; + } + + ReplicationFactor(int allReplicas) { + this(allReplicas, 0); + } + + int fullReplicas() { + return fullReplicas; + } + + int transientReplicas() { + return transientReplicas; + } + + boolean hasTransientReplicas() { + return transientReplicas > 0; + } + + static ReplicationFactor fromString(String s) { + if (s.contains("/")) { + int slash = s.indexOf('/'); + String allPart = s.substring(0, slash); + String transientPart = s.substring(slash + 1); + return new ReplicationFactor(Integer.parseInt(allPart), Integer.parseInt(transientPart)); + } else { + return new ReplicationFactor(Integer.parseInt(s), 0); + } + } + + @Override + public String toString() { + return allReplicas + (hasTransientReplicas() ? "/" + transientReplicas() : ""); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof ReplicationFactor)) { + return false; + } + ReplicationFactor that = (ReplicationFactor) o; + return allReplicas == that.allReplicas && transientReplicas == that.transientReplicas; + } + + @Override + public int hashCode() { + return allReplicas ^ transientReplicas; + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/ReplicationStategy.java b/driver-core/src/main/java/com/datastax/driver/core/ReplicationStategy.java index 481d7ebb78a..cfee11b67a8 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ReplicationStategy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ReplicationStategy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,13 @@ static ReplicationStrategy create(Map replicationOptions) { String repFactorString = replicationOptions.get("replication_factor"); return repFactorString == null ? null - : new SimpleStrategy(Integer.parseInt(repFactorString)); + : new SimpleStrategy(ReplicationFactor.fromString(repFactorString)); } else if (strategyClass.contains("NetworkTopologyStrategy")) { - Map dcRfs = new HashMap(); + Map dcRfs = new HashMap(); for (Map.Entry entry : replicationOptions.entrySet()) { if (entry.getKey().equals("class")) continue; - dcRfs.put(entry.getKey(), Integer.parseInt(entry.getValue())); + dcRfs.put(entry.getKey(), ReplicationFactor.fromString(entry.getValue())); } return new NetworkTopologyStrategy(dcRfs); } else { @@ -76,9 +78,9 @@ private static Token getTokenWrapping(int i, List ring) { static class SimpleStrategy extends ReplicationStrategy { - private final int replicationFactor; + private final ReplicationFactor replicationFactor; - private SimpleStrategy(int replicationFactor) { + private SimpleStrategy(ReplicationFactor replicationFactor) { this.replicationFactor = replicationFactor; } @@ -86,7 +88,7 @@ private SimpleStrategy(int replicationFactor) { Map> computeTokenToReplicaMap( String keyspaceName, Map tokenToPrimary, List ring) { - int rf = Math.min(replicationFactor, ring.size()); + int rf = Math.min(replicationFactor.fullReplicas(), ring.size()); Map> replicaMap = new HashMap>(tokenToPrimary.size()); for (int i = 0; i < ring.size(); i++) { @@ -106,21 +108,21 @@ public boolean equals(Object o) { SimpleStrategy that = (SimpleStrategy) o; - return replicationFactor == that.replicationFactor; + return replicationFactor.equals(that.replicationFactor); } @Override public int hashCode() { - return replicationFactor; + return replicationFactor.hashCode(); } } static class NetworkTopologyStrategy extends ReplicationStrategy { private static final Logger logger = LoggerFactory.getLogger(NetworkTopologyStrategy.class); - private final Map replicationFactors; + private final Map replicationFactors; - private NetworkTopologyStrategy(Map replicationFactors) { + private NetworkTopologyStrategy(Map replicationFactors) { this.replicationFactors = replicationFactors; } @@ -163,7 +165,7 @@ Map> computeTokenToReplicaMap( String dc = h.getDatacenter(); if (dc == null || !allDcReplicas.containsKey(dc)) continue; - Integer rf = replicationFactors.get(dc); + Integer rf = replicationFactors.get(dc).fullReplicas(); Set dcReplicas = allDcReplicas.get(dc); if (rf == null || dcReplicas.size() >= rf) continue; @@ -198,7 +200,7 @@ Map> computeTokenToReplicaMap( // Warn the user because that leads to quadratic performance of this method (JAVA-702). for (Map.Entry> entry : allDcReplicas.entrySet()) { String dcName = entry.getKey(); - int expectedFactor = replicationFactors.get(dcName); + int expectedFactor = replicationFactors.get(dcName).fullReplicas(); int achievedFactor = entry.getValue().size(); if (achievedFactor < expectedFactor && !warnedDcs.contains(dcName)) { logger.warn( @@ -230,7 +232,8 @@ private boolean allDone(Map> map, Map dcHostC for (Map.Entry> entry : map.entrySet()) { String dc = entry.getKey(); int dcCount = dcHostCount.get(dc) == null ? 0 : dcHostCount.get(dc); - if (entry.getValue().size() < Math.min(replicationFactors.get(dc), dcCount)) return false; + if (entry.getValue().size() < Math.min(replicationFactors.get(dc).fullReplicas(), dcCount)) + return false; } return true; } diff --git a/driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java b/driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java index b50fc121399..25b813e3517 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +++ b/driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,6 @@ import com.google.common.util.concurrent.ListenableFuture; import io.netty.util.Timeout; import io.netty.util.TimerTask; -import java.net.InetSocketAddress; import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -64,6 +65,8 @@ class RequestHandler { private static final boolean HOST_METRICS_ENABLED = Boolean.getBoolean("com.datastax.driver.HOST_METRICS_ENABLED"); + private static final QueryLogger QUERY_LOGGER = QueryLogger.builder().build(); + static final String DISABLE_QUERY_WARNING_LOGS = "com.datastax.driver.DISABLE_QUERY_WARNING_LOGS"; final String id; @@ -79,7 +82,7 @@ class RequestHandler { private final io.netty.util.Timer scheduler; private volatile List triedHosts; - private volatile ConcurrentMap errors; + private volatile ConcurrentMap errors; private final Timer.Context timerContext; private final long startTime; @@ -223,6 +226,14 @@ private void setFinalResult( execution.retryConsistencyLevel, response.getCustomPayload()); } + // if the response from the server has warnings, they'll be set on the ExecutionInfo. Log them + // here, unless they've been disabled. + if (response.warnings != null + && !response.warnings.isEmpty() + && !Boolean.getBoolean(RequestHandler.DISABLE_QUERY_WARNING_LOGS) + && logger.isWarnEnabled()) { + logServerWarnings(response.warnings); + } callback.onSet(connection, response, info, statement, System.nanoTime() - startTime); } catch (Exception e) { callback.onException( @@ -234,6 +245,15 @@ private void setFinalResult( } } + private void logServerWarnings(List warnings) { + // truncate the statement query to the DEFAULT_MAX_QUERY_STRING_LENGTH, if necessary + final String queryString = QUERY_LOGGER.statementAsString(statement); + // log each warning separately + for (String warning : warnings) { + logger.warn("Query '{}' generated server side warning(s): {}", queryString, warning); + } + } + private void setFinalException( SpeculativeExecution execution, Connection connection, Exception exception) { if (!isDone.compareAndSet(false, true)) { @@ -262,7 +282,7 @@ private void reportNoMoreHosts(SpeculativeExecution execution) { execution, null, new NoHostAvailableException( - errors == null ? Collections.emptyMap() : errors)); + errors == null ? Collections.emptyMap() : errors)); } private boolean metricsEnabled() { @@ -399,18 +419,21 @@ public void onSuccess(Connection connection) { // If we have any problem with the connection, move to the next node. if (metricsEnabled()) metrics().getErrorMetrics().getConnectionErrors().inc(); if (connection != null) connection.release(); - logError(host.getSocketAddress(), e); + logError(host.getEndPoint(), e); findNextHostAndQuery(); } catch (BusyConnectionException e) { // The pool shouldn't have give us a busy connection unless we've maxed up the pool, // so move on to the next host. - connection.release(); - logError(host.getSocketAddress(), e); + connection.release(true); + logError(host.getEndPoint(), e); findNextHostAndQuery(); } catch (RuntimeException e) { if (connection != null) connection.release(); - logger.error("Unexpected error while querying " + host.getAddress(), e); - logError(host.getSocketAddress(), e); + logger.warn( + "Unexpected error while querying {} - [{}]. Find next host to query.", + host.getEndPoint(), + e.toString()); + logError(host.getEndPoint(), e); findNextHostAndQuery(); } } @@ -418,10 +441,13 @@ public void onSuccess(Connection connection) { @Override public void onFailure(Throwable t) { if (t instanceof BusyPoolException) { - logError(host.getSocketAddress(), t); + logError(host.getEndPoint(), t); } else { - logger.error("Unexpected error while querying " + host.getAddress(), t); - logError(host.getSocketAddress(), t); + logger.warn( + "Unexpected error while querying {} - [{}]. Find next host to query.", + host.getEndPoint(), + t.toString()); + logError(host.getEndPoint(), t); } findNextHostAndQuery(); } @@ -517,7 +543,7 @@ private void processRetryDecision( retryDecision.getRetryConsistencyLevel()); if (metricsEnabled()) metrics().getErrorMetrics().getRetries().inc(); // log error for the current host if we are switching to another one - if (!retryDecision.isRetryCurrent()) logError(connection.address, exceptionToReport); + if (!retryDecision.isRetryCurrent()) logError(connection.endPoint, exceptionToReport); retry(retryDecision.isRetryCurrent(), retryDecision.getRetryConsistencyLevel()); break; case RETHROW: @@ -539,16 +565,16 @@ private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLe if (!retryCurrent || !query(h)) findNextHostAndQuery(); } - private void logError(InetSocketAddress address, Throwable exception) { - logger.debug("[{}] Error querying {} : {}", id, address, exception.toString()); + private void logError(EndPoint endPoint, Throwable exception) { + logger.debug("[{}] Error querying {} : {}", id, endPoint, exception.toString()); if (errors == null) { synchronized (RequestHandler.this) { if (errors == null) { - errors = new ConcurrentHashMap(); + errors = new ConcurrentHashMap(); } } } - errors.put(address, exception); + errors.put(endPoint, exception); } void cancel() { @@ -624,7 +650,7 @@ public void onSet( break; case ERROR: Responses.Error err = (Responses.Error) response; - exceptionToReport = err.asException(connection.address); + exceptionToReport = err.asException(connection.endPoint); RetryPolicy.RetryDecision retry = null; RetryPolicy retryPolicy = retryPolicy(); switch (err.code) { @@ -695,7 +721,7 @@ public void onSet( case OVERLOADED: connection.release(); assert exceptionToReport instanceof OverloadedException; - logger.warn("Host {} is overloaded.", connection.address); + logger.warn("Host {} is overloaded.", connection.endPoint); retry = computeRetryDecisionOnRequestError((OverloadedException) exceptionToReport); break; case SERVER_ERROR: @@ -703,7 +729,7 @@ public void onSet( assert exceptionToReport instanceof ServerError; logger.warn( "{} replied with server error ({}), defuncting connection.", - connection.address, + connection.endPoint, err.message); // Defunct connection connection.defunct(exceptionToReport); @@ -714,11 +740,11 @@ public void onSet( assert exceptionToReport instanceof BootstrappingException; logger.error( "Query sent to {} but it is bootstrapping. This shouldn't happen but trying next host.", - connection.address); + connection.endPoint); if (metricsEnabled()) { metrics().getErrorMetrics().getOthers().inc(); } - logError(connection.address, exceptionToReport); + logError(connection.endPoint, exceptionToReport); retry(false, null); return; case UNPREPARED: @@ -758,7 +784,8 @@ public void onSet( "Query {} is not prepared on {}, preparing before retrying executing. " + "Seeing this message a few times is fine, but seeing it a lot may be source of performance problems", toPrepare.getQueryString(), - connection.address); + toPrepare.getQueryKeyspace(), + connection.endPoint); write(connection, prepareAndRetry(toPrepare.getQueryString())); // we're done for now, the prepareAndRetry callback will handle the rest @@ -850,14 +877,14 @@ public void onSet( retry(true, null); } else { logError( - connection.address, + connection.endPoint, new DriverException("Got unexpected response to prepare message: " + response)); retry(false, null); } break; case ERROR: logError( - connection.address, + connection.endPoint, new DriverException("Error preparing query, got " + response)); if (metricsEnabled()) metrics().getErrorMetrics().getOthers().inc(); retry(false, null); @@ -889,9 +916,9 @@ public boolean onTimeout(Connection connection, long latency, int retryCount) { } connection.release(); logError( - connection.address, + connection.endPoint, new OperationTimedOutException( - connection.address, "Timed out waiting for response to PREPARE message")); + connection.endPoint, "Timed out waiting for response to PREPARE message")); retry(false, null); return true; } @@ -953,7 +980,7 @@ public boolean onTimeout(Connection connection, long latency, int retryCount) { OperationTimedOutException timeoutException = new OperationTimedOutException( - connection.address, "Timed out waiting for server response"); + connection.endPoint, "Timed out waiting for server response"); try { connection.release(); diff --git a/driver-core/src/main/java/com/datastax/driver/core/Requests.java b/driver-core/src/main/java/com/datastax/driver/core/Requests.java index 7663dae4e2f..04833ce159c 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Requests.java +++ b/driver-core/src/main/java/com/datastax/driver/core/Requests.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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.google.common.collect.ImmutableMap; import io.netty.buffer.ByteBuf; import java.nio.ByteBuffer; +import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.List; @@ -26,6 +29,8 @@ class Requests { + static final ByteBuffer[] EMPTY_BB_ARRAY = new ByteBuffer[0]; + private Requests() {} static class Startup extends Message.Request { @@ -33,7 +38,7 @@ static class Startup extends Message.Request { private static final String CQL_VERSION = "3.0.0"; private static final String DRIVER_VERSION_OPTION = "DRIVER_VERSION"; private static final String DRIVER_NAME_OPTION = "DRIVER_NAME"; - private static final String DRIVER_NAME = "DataStax Java Driver"; + private static final String DRIVER_NAME = "Apache Cassandra Java Driver"; static final String COMPRESSION_OPTION = "COMPRESSION"; static final String NO_COMPACT_OPTION = "NO_COMPACT"; @@ -251,27 +256,33 @@ public String toString() { } enum QueryFlag { - // The order of that enum matters!! - VALUES, - SKIP_METADATA, - PAGE_SIZE, - PAGING_STATE, - SERIAL_CONSISTENCY, - DEFAULT_TIMESTAMP, - VALUE_NAMES; + VALUES(0x00000001), + SKIP_METADATA(0x00000002), + PAGE_SIZE(0x00000004), + PAGING_STATE(0x00000008), + SERIAL_CONSISTENCY(0x00000010), + DEFAULT_TIMESTAMP(0x00000020), + VALUE_NAMES(0x00000040), + NOW_IN_SECONDS(0x00000100), + ; + + private int mask; + + QueryFlag(int mask) { + this.mask = mask; + } static EnumSet deserialize(int flags) { EnumSet set = EnumSet.noneOf(QueryFlag.class); - QueryFlag[] values = QueryFlag.values(); - for (int n = 0; n < values.length; n++) { - if ((flags & (1 << n)) != 0) set.add(values[n]); + for (QueryFlag flag : values()) { + if ((flags & flag.mask) != 0) set.add(flag); } return set; } static void serialize(EnumSet flags, ByteBuf dest, ProtocolVersion version) { int i = 0; - for (QueryFlag flag : flags) i |= 1 << flag.ordinal(); + for (QueryFlag flag : flags) i |= flag.mask; if (version.compareTo(ProtocolVersion.V5) >= 0) { dest.writeInt(i); } else { @@ -290,37 +301,40 @@ static class QueryProtocolOptions { new QueryProtocolOptions( Message.Request.Type.QUERY, ConsistencyLevel.ONE, - Collections.emptyList(), + EMPTY_BB_ARRAY, Collections.emptyMap(), false, -1, null, ConsistencyLevel.SERIAL, - Long.MIN_VALUE); + Long.MIN_VALUE, + Integer.MIN_VALUE); private final EnumSet flags = EnumSet.noneOf(QueryFlag.class); private final Message.Request.Type requestType; final ConsistencyLevel consistency; - final List positionalValues; + final ByteBuffer[] positionalValues; final Map namedValues; final boolean skipMetadata; final int pageSize; final ByteBuffer pagingState; final ConsistencyLevel serialConsistency; final long defaultTimestamp; + final int nowInSeconds; QueryProtocolOptions( Message.Request.Type requestType, ConsistencyLevel consistency, - List positionalValues, + ByteBuffer[] positionalValues, Map namedValues, boolean skipMetadata, int pageSize, ByteBuffer pagingState, ConsistencyLevel serialConsistency, - long defaultTimestamp) { + long defaultTimestamp, + int nowInSeconds) { - Preconditions.checkArgument(positionalValues.isEmpty() || namedValues.isEmpty()); + Preconditions.checkArgument(positionalValues.length == 0 || namedValues.isEmpty()); this.requestType = requestType; this.consistency = consistency; @@ -331,9 +345,12 @@ static class QueryProtocolOptions { this.pagingState = pagingState; this.serialConsistency = serialConsistency; this.defaultTimestamp = defaultTimestamp; + this.nowInSeconds = nowInSeconds; // Populate flags - if (!positionalValues.isEmpty()) flags.add(QueryFlag.VALUES); + if (positionalValues.length > 0) { + flags.add(QueryFlag.VALUES); + } if (!namedValues.isEmpty()) { flags.add(QueryFlag.VALUES); flags.add(QueryFlag.VALUE_NAMES); @@ -343,6 +360,7 @@ static class QueryProtocolOptions { if (pagingState != null) flags.add(QueryFlag.PAGING_STATE); if (serialConsistency != ConsistencyLevel.SERIAL) flags.add(QueryFlag.SERIAL_CONSISTENCY); if (defaultTimestamp != Long.MIN_VALUE) flags.add(QueryFlag.DEFAULT_TIMESTAMP); + if (nowInSeconds != Integer.MIN_VALUE) flags.add(QueryFlag.NOW_IN_SECONDS); } QueryProtocolOptions copy(ConsistencyLevel newConsistencyLevel) { @@ -355,7 +373,8 @@ QueryProtocolOptions copy(ConsistencyLevel newConsistencyLevel) { pageSize, pagingState, serialConsistency, - defaultTimestamp); + defaultTimestamp, + nowInSeconds); } void encode(ByteBuf dest, ProtocolVersion version) { @@ -371,6 +390,7 @@ void encode(ByteBuf dest, ProtocolVersion version) { case V3: case V4: case V5: + case V6: CBUtil.writeConsistencyLevel(consistency, dest); QueryFlag.serialize(flags, dest, version); if (flags.contains(QueryFlag.VALUES)) { @@ -387,6 +407,8 @@ void encode(ByteBuf dest, ProtocolVersion version) { CBUtil.writeConsistencyLevel(serialConsistency, dest); if (version.compareTo(ProtocolVersion.V3) >= 0 && flags.contains(QueryFlag.DEFAULT_TIMESTAMP)) dest.writeLong(defaultTimestamp); + if (version.compareTo(ProtocolVersion.V5) >= 0 + && flags.contains(QueryFlag.NOW_IN_SECONDS)) dest.writeInt(nowInSeconds); break; default: throw version.unsupported(); @@ -406,6 +428,7 @@ int encodedSize(ProtocolVersion version) { case V3: case V4: case V5: + case V6: int size = 0; size += CBUtil.sizeOfConsistencyLevel(consistency); size += QueryFlag.serializedSize(version); @@ -423,6 +446,8 @@ int encodedSize(ProtocolVersion version) { size += CBUtil.sizeOfConsistencyLevel(serialConsistency); if (version.compareTo(ProtocolVersion.V3) >= 0 && flags.contains(QueryFlag.DEFAULT_TIMESTAMP)) size += 8; + if (version.compareTo(ProtocolVersion.V5) >= 0 + && flags.contains(QueryFlag.NOW_IN_SECONDS)) size += 4; return size; default: throw version.unsupported(); @@ -434,7 +459,7 @@ public String toString() { return String.format( "[cl=%s, positionalVals=%s, namedVals=%s, skip=%b, psize=%d, state=%s, serialCl=%s]", consistency, - positionalValues, + Arrays.toString(positionalValues), namedValues, skipMetadata, pageSize, @@ -461,7 +486,7 @@ public void encode(Batch msg, ByteBuf dest, ProtocolVersion version) { if (q instanceof String) CBUtil.writeLongString((String) q, dest); else CBUtil.writeShortBytes(((MD5Digest) q).bytes, dest); - CBUtil.writeValueList(msg.values.get(i), dest); + CBUtil.writeValueList(msg.values[i], dest); } msg.options.encode(dest, version); @@ -478,7 +503,7 @@ public int encodedSize(Batch msg, ProtocolVersion version) { ? CBUtil.sizeOfLongString((String) q) : CBUtil.sizeOfShortBytes(((MD5Digest) q).bytes)); - size += CBUtil.sizeOfValueList(msg.values.get(i)); + size += CBUtil.sizeOfValueList(msg.values[i]); } size += msg.options.encodedSize(version); return size; @@ -500,13 +525,13 @@ private byte fromType(BatchStatement.Type type) { final BatchStatement.Type type; final List queryOrIdList; - final List> values; + final ByteBuffer[][] values; final BatchProtocolOptions options; Batch( BatchStatement.Type type, List queryOrIdList, - List> values, + ByteBuffer[][] values, BatchProtocolOptions options, boolean tracingRequested) { super(Message.Request.Type.BATCH, tracingRequested); @@ -533,10 +558,7 @@ public String toString() { sb.append("BATCH of ["); for (int i = 0; i < queryOrIdList.size(); i++) { if (i > 0) sb.append(", "); - sb.append(queryOrIdList.get(i)) - .append(" with ") - .append(values.get(i).size()) - .append(" values"); + sb.append(queryOrIdList.get(i)).append(" with ").append(values[i].length).append(" values"); } sb.append("] with options ").append(options); return sb.toString(); @@ -548,19 +570,26 @@ static class BatchProtocolOptions { final ConsistencyLevel consistency; final ConsistencyLevel serialConsistency; final long defaultTimestamp; + final int nowInSeconds; BatchProtocolOptions( - ConsistencyLevel consistency, ConsistencyLevel serialConsistency, long defaultTimestamp) { + ConsistencyLevel consistency, + ConsistencyLevel serialConsistency, + long defaultTimestamp, + int nowInSeconds) { this.consistency = consistency; this.serialConsistency = serialConsistency; this.defaultTimestamp = defaultTimestamp; + this.nowInSeconds = nowInSeconds; if (serialConsistency != ConsistencyLevel.SERIAL) flags.add(QueryFlag.SERIAL_CONSISTENCY); if (defaultTimestamp != Long.MIN_VALUE) flags.add(QueryFlag.DEFAULT_TIMESTAMP); + if (nowInSeconds != Integer.MIN_VALUE) flags.add(QueryFlag.NOW_IN_SECONDS); } BatchProtocolOptions copy(ConsistencyLevel newConsistencyLevel) { - return new BatchProtocolOptions(newConsistencyLevel, serialConsistency, defaultTimestamp); + return new BatchProtocolOptions( + newConsistencyLevel, serialConsistency, defaultTimestamp, nowInSeconds); } void encode(ByteBuf dest, ProtocolVersion version) { @@ -571,11 +600,14 @@ void encode(ByteBuf dest, ProtocolVersion version) { case V3: case V4: case V5: + case V6: CBUtil.writeConsistencyLevel(consistency, dest); QueryFlag.serialize(flags, dest, version); if (flags.contains(QueryFlag.SERIAL_CONSISTENCY)) CBUtil.writeConsistencyLevel(serialConsistency, dest); if (flags.contains(QueryFlag.DEFAULT_TIMESTAMP)) dest.writeLong(defaultTimestamp); + if (version.compareTo(ProtocolVersion.V5) >= 0 + && flags.contains(QueryFlag.NOW_IN_SECONDS)) dest.writeInt(nowInSeconds); break; default: throw version.unsupported(); @@ -589,12 +621,15 @@ int encodedSize(ProtocolVersion version) { case V3: case V4: case V5: + case V6: int size = 0; size += CBUtil.sizeOfConsistencyLevel(consistency); size += QueryFlag.serializedSize(version); if (flags.contains(QueryFlag.SERIAL_CONSISTENCY)) size += CBUtil.sizeOfConsistencyLevel(serialConsistency); if (flags.contains(QueryFlag.DEFAULT_TIMESTAMP)) size += 8; + if (version.compareTo(ProtocolVersion.V5) >= 0 + && flags.contains(QueryFlag.NOW_IN_SECONDS)) size += 4; return size; default: throw version.unsupported(); diff --git a/driver-core/src/main/java/com/datastax/driver/core/Responses.java b/driver-core/src/main/java/com/datastax/driver/core/Responses.java index 067a151d84e..f17018cc2c7 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Responses.java +++ b/driver-core/src/main/java/com/datastax/driver/core/Responses.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,8 @@ import com.datastax.driver.core.exceptions.AlreadyExistsException; import com.datastax.driver.core.exceptions.AuthenticationException; import com.datastax.driver.core.exceptions.BootstrappingException; +import com.datastax.driver.core.exceptions.CASWriteUnknownException; +import com.datastax.driver.core.exceptions.CDCWriteException; import com.datastax.driver.core.exceptions.DriverException; import com.datastax.driver.core.exceptions.DriverInternalError; import com.datastax.driver.core.exceptions.FunctionExecutionException; @@ -44,7 +48,6 @@ import com.datastax.driver.core.utils.Bytes; import io.netty.buffer.ByteBuf; import java.net.InetAddress; -import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.ArrayDeque; import java.util.ArrayList; @@ -120,6 +123,12 @@ public Error decode(ByteBuf body, ProtocolVersion version, CodecRegistry codecRe clt, received, blockFor, failures, failuresMap, dataPresent != 0); } break; + case CAS_WRITE_UNKNOWN: + clt = CBUtil.readConsistencyLevel(body); + received = body.readInt(); + blockFor = body.readInt(); + infos = new CASWriteUnknownException(clt, received, blockFor); + break; case UNPREPARED: infos = MD5Digest.wrap(CBUtil.readBytes(body)); break; @@ -147,49 +156,55 @@ private Error( this.infos = infos; } - DriverException asException(InetSocketAddress host) { + DriverException asException(EndPoint endPoint) { switch (code) { case SERVER_ERROR: - return new ServerError(host, message); + return new ServerError(endPoint, message); case PROTOCOL_ERROR: - return new ProtocolError(host, message); + return new ProtocolError(endPoint, message); case BAD_CREDENTIALS: - return new AuthenticationException(host, message); + return new AuthenticationException(endPoint, message); case UNAVAILABLE: - return ((UnavailableException) infos).copy(host); // We copy to have a nice stack trace + return ((UnavailableException) infos) + .copy(endPoint); // We copy to have a nice stack trace case OVERLOADED: - return new OverloadedException(host, message); + return new OverloadedException(endPoint, message); case IS_BOOTSTRAPPING: - return new BootstrappingException(host, message); + return new BootstrappingException(endPoint, message); case TRUNCATE_ERROR: - return new TruncateException(host, message); + return new TruncateException(endPoint, message); case WRITE_TIMEOUT: - return ((WriteTimeoutException) infos).copy(host); + return ((WriteTimeoutException) infos).copy(endPoint); case READ_TIMEOUT: - return ((ReadTimeoutException) infos).copy(host); + return ((ReadTimeoutException) infos).copy(endPoint); case WRITE_FAILURE: - return ((WriteFailureException) infos).copy(host); + return ((WriteFailureException) infos).copy(endPoint); case READ_FAILURE: - return ((ReadFailureException) infos).copy(host); + return ((ReadFailureException) infos).copy(endPoint); case FUNCTION_FAILURE: - return new FunctionExecutionException(host, message); + return new FunctionExecutionException(endPoint, message); + case CDC_WRITE_FAILURE: + return new CDCWriteException(endPoint, message); + case CAS_WRITE_UNKNOWN: + return ((CASWriteUnknownException) infos).copy(endPoint); case SYNTAX_ERROR: - return new SyntaxError(host, message); + return new SyntaxError(endPoint, message); case UNAUTHORIZED: - return new UnauthorizedException(host, message); + return new UnauthorizedException(endPoint, message); case INVALID: - return new InvalidQueryException(host, message); + return new InvalidQueryException(endPoint, message); case CONFIG_ERROR: - return new InvalidConfigurationInQueryException(host, message); + return new InvalidConfigurationInQueryException(endPoint, message); case ALREADY_EXISTS: - return ((AlreadyExistsException) infos).copy(host); + return ((AlreadyExistsException) infos).copy(endPoint); case UNPREPARED: - return new UnpreparedException(host, message); + return new UnpreparedException(endPoint, message); + default: return new DriverInternalError( String.format( "Unknown protocol error code %s returned by %s. The error message was: %s", - code, host, message)); + code, endPoint, message)); } } @@ -604,6 +619,7 @@ private Metadata decodeResultMetadata( case V3: case V4: case V5: + case V6: return Rows.Metadata.decode(body, version, codecRegistry); default: throw version.unsupported(); @@ -678,6 +694,7 @@ public Result decode( case V3: case V4: case V5: + case V6: change = CBUtil.readEnumValue(Change.class, body); targetType = CBUtil.readEnumValue(SchemaElement.class, body); targetKeyspace = CBUtil.readString(body); diff --git a/driver-core/src/main/java/com/datastax/driver/core/ResultSet.java b/driver-core/src/main/java/com/datastax/driver/core/ResultSet.java index 4b9902d32ce..78083f9ccc9 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ResultSet.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/ResultSetFuture.java b/driver-core/src/main/java/com/datastax/driver/core/ResultSetFuture.java index c78c4e08183..09a227ed5f8 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ResultSetFuture.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ResultSetFuture.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/Row.java b/driver-core/src/main/java/com/datastax/driver/core/Row.java index 879086f83f9..57dd5870c0e 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Row.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/SSLOptions.java b/driver-core/src/main/java/com/datastax/driver/core/SSLOptions.java index 86b5f34527d..f97b56c7313 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/SSLOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/SSLOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 +19,6 @@ import io.netty.channel.socket.SocketChannel; import io.netty.handler.ssl.SslHandler; -import java.net.InetSocketAddress; /** * Defines how the driver configures SSL connections. @@ -44,8 +45,8 @@ public interface SSLOptions { * * @param channel the channel. * @return the handler. - * @deprecated use {@link RemoteEndpointAwareSSLOptions#newSSLHandler(SocketChannel, - * InetSocketAddress)} instead. + * @deprecated use {@link RemoteEndpointAwareSSLOptions#newSSLHandler(SocketChannel, EndPoint)} + * instead. */ @SuppressWarnings("DeprecatedIsStillUsed") @Deprecated diff --git a/driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListener.java b/driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListener.java index d20d0fbd755..2989cb98e3c 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListener.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, diff --git a/driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListenerBase.java b/driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListenerBase.java index b2185633174..f46231963ed 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListenerBase.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/SchemaElement.java b/driver-core/src/main/java/com/datastax/driver/core/SchemaElement.java index 36d1e1d2a00..1ef0944cb0e 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/SchemaElement.java +++ b/driver-core/src/main/java/com/datastax/driver/core/SchemaElement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/SchemaParser.java b/driver-core/src/main/java/com/datastax/driver/core/SchemaParser.java index d6e3094c663..ee2e272bf05 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/SchemaParser.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -56,6 +58,7 @@ static SchemaParser forVersion(VersionNumber cassandraVersion) { } static SchemaParser forDseVersion(VersionNumber dseVersion) { + if (dseVersion.getMajor() == 6 && dseVersion.getMinor() >= 8) return V4_PARSER; if (dseVersion.getMajor() >= 5) return V3_PARSER; return V2_PARSER; } @@ -93,7 +96,13 @@ void refresh( connection, cassandraVersion); - Metadata metadata = cluster.getMetadata(); + Metadata metadata; + try { + metadata = cluster.getMetadata(); + } catch (IllegalStateException e) { + logger.warn("Unable to refresh metadata, cluster has been closed"); + return; + } metadata.lock.lock(); try { if (targetType == null || targetType == KEYSPACE) { @@ -435,19 +444,29 @@ private void updateKeyspaces( metadata.triggerOnKeyspaceChanged(newKeyspace, oldKeyspace); } Map oldTables = - oldKeyspace == null ? new HashMap() : oldKeyspace.tables; + oldKeyspace == null + ? new HashMap() + : new HashMap(oldKeyspace.tables); updateTables(metadata, oldTables, newKeyspace.tables, null); Map oldTypes = - oldKeyspace == null ? new HashMap() : oldKeyspace.userTypes; + oldKeyspace == null + ? new HashMap() + : new HashMap(oldKeyspace.userTypes); updateUserTypes(metadata, oldTypes, newKeyspace.userTypes, null); Map oldFunctions = - oldKeyspace == null ? new HashMap() : oldKeyspace.functions; + oldKeyspace == null + ? new HashMap() + : new HashMap(oldKeyspace.functions); updateFunctions(metadata, oldFunctions, newKeyspace.functions, null); Map oldAggregates = - oldKeyspace == null ? new HashMap() : oldKeyspace.aggregates; + oldKeyspace == null + ? new HashMap() + : new HashMap(oldKeyspace.aggregates); updateAggregates(metadata, oldAggregates, newKeyspace.aggregates, null); Map oldViews = - oldKeyspace == null ? new HashMap() : oldKeyspace.views; + oldKeyspace == null + ? new HashMap() + : new HashMap(oldKeyspace.views); updateViews(metadata, oldViews, newKeyspace.views, null); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/Segment.java b/driver-core/src/main/java/com/datastax/driver/core/Segment.java new file mode 100644 index 00000000000..be386826be9 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/Segment.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.driver.core; + +import io.netty.buffer.ByteBuf; + +/** + * A container of {@link Frame}s in protocol v5 and above. This is a new protocol construct that + * allows checksumming and compressing multiple messages together. + * + *

{@link #getPayload()} contains either: + * + *

    + *
  • a sequence of encoded {@link Frame}s, all concatenated together. In this case, {@link + * #isSelfContained()} return true. + *
  • or a slice of an encoded large {@link Frame} (if that frame is longer than {@link + * #MAX_PAYLOAD_LENGTH}). In this case, {@link #isSelfContained()} returns false. + *
+ * + * The payload is not compressed; compression is handled at a lower level when encoding or decoding + * this object. + * + *

Naming is provisional: "segment" is not the official name, I picked it arbitrarily for the + * driver code to avoid a name clash. It's possible that this type will be renamed to "frame", and + * {@link Frame} to something else, at some point in the future (this is an ongoing discussion on + * the server ticket). + */ +class Segment { + + static int MAX_PAYLOAD_LENGTH = 128 * 1024 - 1; + + private final ByteBuf payload; + private final boolean isSelfContained; + + Segment(ByteBuf payload, boolean isSelfContained) { + this.payload = payload; + this.isSelfContained = isSelfContained; + } + + public ByteBuf getPayload() { + return payload; + } + + public boolean isSelfContained() { + return isSelfContained; + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/SegmentBuilder.java b/driver-core/src/main/java/com/datastax/driver/core/SegmentBuilder.java new file mode 100644 index 00000000000..9e5e75eec76 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/SegmentBuilder.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.driver.core; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.collect.ImmutableList; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import io.netty.util.concurrent.Future; +import io.netty.util.concurrent.GenericFutureListener; +import java.util.ArrayList; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Abstracts the details of batching a sequence of {@link Message.Request}s into one or more {@link + * Segment}s before sending them out on the network. + * + *

This class is not thread-safe. + */ +class SegmentBuilder { + + private static final Logger logger = LoggerFactory.getLogger(SegmentBuilder.class); + + private final ChannelHandlerContext context; + private final ByteBufAllocator allocator; + private final int maxPayloadLength; + private final Message.ProtocolEncoder requestEncoder; + + private final List currentPayloadHeaders = new ArrayList(); + private final List currentPayloadBodies = new ArrayList(); + private final List currentPayloadPromises = new ArrayList(); + private int currentPayloadLength; + + SegmentBuilder( + ChannelHandlerContext context, + ByteBufAllocator allocator, + Message.ProtocolEncoder requestEncoder) { + this(context, allocator, requestEncoder, Segment.MAX_PAYLOAD_LENGTH); + } + + /** Exposes the max length for unit tests; in production, this is hard-coded. */ + @VisibleForTesting + SegmentBuilder( + ChannelHandlerContext context, + ByteBufAllocator allocator, + Message.ProtocolEncoder requestEncoder, + int maxPayloadLength) { + this.context = context; + this.allocator = allocator; + this.requestEncoder = requestEncoder; + this.maxPayloadLength = maxPayloadLength; + } + + /** + * Adds a new request. It will be encoded into one or more segments, that will be passed to {@link + * #processSegment(Segment, ChannelPromise)} at some point in the future. + * + *

The caller must invoke {@link #flush()} after the last request. + */ + public void addRequest(Message.Request request, ChannelPromise promise) { + + // Wrap the request into a legacy frame, append that frame to the payload. + int frameHeaderLength = Frame.Header.lengthFor(requestEncoder.protocolVersion); + int frameBodyLength = requestEncoder.encodedSize(request); + int frameLength = frameHeaderLength + frameBodyLength; + + Frame.Header header = + new Frame.Header( + requestEncoder.protocolVersion, + requestEncoder.computeFlags(request), + request.getStreamId(), + request.type.opcode, + frameBodyLength); + + if (frameLength > maxPayloadLength) { + // Large request: split into multiple dedicated segments and process them immediately: + ByteBuf frame = allocator.ioBuffer(frameLength); + header.encodeInto(frame); + requestEncoder.encode(request, frame); + + int sliceCount = + (frameLength / maxPayloadLength) + (frameLength % maxPayloadLength == 0 ? 0 : 1); + + logger.trace( + "Splitting large request ({} bytes) into {} segments: {}", + frameLength, + sliceCount, + request); + + List segmentPromises = split(promise, sliceCount); + int i = 0; + do { + ByteBuf part = frame.readSlice(Math.min(maxPayloadLength, frame.readableBytes())); + part.retain(); + process(part, false, segmentPromises.get(i++)); + } while (frame.isReadable()); + // We've retained each slice, and won't reference this buffer anymore + frame.release(); + } else { + // Small request: append to an existing segment, together with other messages. + if (currentPayloadLength + frameLength > maxPayloadLength) { + // Current segment is full, process and start a new one: + processCurrentPayload(); + resetCurrentPayload(); + } + // Append frame to current segment + logger.trace( + "Adding {}th request to self-contained segment: {}", + currentPayloadHeaders.size() + 1, + request); + currentPayloadHeaders.add(header); + currentPayloadBodies.add(request); + currentPayloadPromises.add(promise); + currentPayloadLength += frameLength; + } + } + + /** + * Signals that we're done adding requests. + * + *

This must be called after adding the last request, it will possibly trigger the generation + * of one last segment. + */ + public void flush() { + if (currentPayloadLength > 0) { + processCurrentPayload(); + resetCurrentPayload(); + } + } + + /** What to do whenever a full segment is ready. */ + protected void processSegment(Segment segment, ChannelPromise segmentPromise) { + context.write(segment, segmentPromise); + } + + private void process(ByteBuf payload, boolean isSelfContained, ChannelPromise segmentPromise) { + processSegment(new Segment(payload, isSelfContained), segmentPromise); + } + + private void processCurrentPayload() { + int requestCount = currentPayloadHeaders.size(); + assert currentPayloadBodies.size() == requestCount + && currentPayloadPromises.size() == requestCount; + logger.trace("Emitting new self-contained segment with {} frame(s)", requestCount); + ByteBuf payload = this.allocator.ioBuffer(currentPayloadLength); + for (int i = 0; i < requestCount; i++) { + Frame.Header header = currentPayloadHeaders.get(i); + Message.Request request = currentPayloadBodies.get(i); + header.encodeInto(payload); + requestEncoder.encode(request, payload); + } + process(payload, true, merge(currentPayloadPromises)); + } + + private void resetCurrentPayload() { + currentPayloadHeaders.clear(); + currentPayloadBodies.clear(); + currentPayloadPromises.clear(); + currentPayloadLength = 0; + } + + // Merges multiple promises into a single one, that will notify all of them when done. + // This is used when multiple requests are sent as a single segment. + private ChannelPromise merge(List framePromises) { + if (framePromises.size() == 1) { + return framePromises.get(0); + } + ChannelPromise segmentPromise = context.newPromise(); + final ImmutableList dependents = ImmutableList.copyOf(framePromises); + segmentPromise.addListener( + new GenericFutureListener>() { + @Override + public void operationComplete(Future future) throws Exception { + if (future.isSuccess()) { + for (ChannelPromise framePromise : dependents) { + framePromise.setSuccess(); + } + } else { + Throwable cause = future.cause(); + for (ChannelPromise framePromise : dependents) { + framePromise.setFailure(cause); + } + } + } + }); + return segmentPromise; + } + + // Splits a single promise into multiple ones. The original promise will complete when all the + // splits have. + // This is used when a single request is sliced into multiple segment. + private List split(ChannelPromise framePromise, int sliceCount) { + // We split one frame into multiple slices. When all slices are written, the frame is written. + List slicePromises = new ArrayList(sliceCount); + for (int i = 0; i < sliceCount; i++) { + slicePromises.add(context.newPromise()); + } + GenericFutureListener> sliceListener = + new SliceWriteListener(framePromise, slicePromises); + for (int i = 0; i < sliceCount; i++) { + slicePromises.get(i).addListener(sliceListener); + } + return slicePromises; + } + + static class SliceWriteListener implements GenericFutureListener> { + + private final ChannelPromise parentPromise; + private final List slicePromises; + + // All slices are written to the same channel, and the segment is built from the Flusher which + // also runs on the same event loop, so we don't need synchronization. + private int remainingSlices; + + SliceWriteListener(ChannelPromise parentPromise, List slicePromises) { + this.parentPromise = parentPromise; + this.slicePromises = slicePromises; + this.remainingSlices = slicePromises.size(); + } + + @Override + public void operationComplete(Future future) { + if (!parentPromise.isDone()) { + if (future.isSuccess()) { + remainingSlices -= 1; + if (remainingSlices == 0) { + parentPromise.setSuccess(); + } + } else { + // If any slice fails, we can immediately mark the whole frame as failed: + parentPromise.setFailure(future.cause()); + // Cancel any remaining slice, Netty will not send the bytes. + for (ChannelPromise slicePromise : slicePromises) { + slicePromise.cancel(/*Netty ignores this*/ false); + } + } + } + } + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/SegmentCodec.java b/driver-core/src/main/java/com/datastax/driver/core/SegmentCodec.java new file mode 100644 index 00000000000..c098c842381 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/SegmentCodec.java @@ -0,0 +1,212 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +import com.datastax.driver.core.exceptions.CrcMismatchException; +import com.google.common.annotations.VisibleForTesting; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import java.io.IOException; +import java.util.List; + +class SegmentCodec { + + private static final int COMPRESSED_HEADER_LENGTH = 5; + private static final int UNCOMPRESSED_HEADER_LENGTH = 3; + static final int CRC24_LENGTH = 3; + static final int CRC32_LENGTH = 4; + + private final ByteBufAllocator allocator; + private final boolean compress; + private final FrameCompressor compressor; + + SegmentCodec(ByteBufAllocator allocator, ProtocolOptions.Compression compression) { + this.allocator = allocator; + this.compress = compression != ProtocolOptions.Compression.NONE; + this.compressor = compression.compressor(); + } + + /** The length of the segment header, excluding the 3-byte trailing CRC. */ + int headerLength() { + return compress ? COMPRESSED_HEADER_LENGTH : UNCOMPRESSED_HEADER_LENGTH; + } + + void encode(Segment segment, List out) throws IOException { + ByteBuf uncompressedPayload = segment.getPayload(); + int uncompressedPayloadLength = uncompressedPayload.readableBytes(); + assert uncompressedPayloadLength <= Segment.MAX_PAYLOAD_LENGTH; + ByteBuf encodedPayload; + if (compress) { + uncompressedPayload.markReaderIndex(); + ByteBuf compressedPayload = compressor.compress(uncompressedPayload); + if (compressedPayload.readableBytes() >= uncompressedPayloadLength) { + // Skip compression if it's not worth it + uncompressedPayload.resetReaderIndex(); + encodedPayload = uncompressedPayload; + compressedPayload.release(); + // By convention, this is how we signal this to the server: + uncompressedPayloadLength = 0; + } else { + encodedPayload = compressedPayload; + uncompressedPayload.release(); + } + } else { + encodedPayload = uncompressedPayload; + } + int payloadLength = encodedPayload.readableBytes(); + + ByteBuf header = + encodeHeader(payloadLength, uncompressedPayloadLength, segment.isSelfContained()); + + int payloadCrc = Crc.computeCrc32(encodedPayload); + ByteBuf trailer = allocator.ioBuffer(CRC32_LENGTH); + for (int i = 0; i < CRC32_LENGTH; i++) { + trailer.writeByte(payloadCrc & 0xFF); + payloadCrc >>= 8; + } + + out.add(header); + out.add(encodedPayload); + out.add(trailer); + } + + @VisibleForTesting + ByteBuf encodeHeader(int payloadLength, int uncompressedLength, boolean isSelfContained) { + assert payloadLength <= Segment.MAX_PAYLOAD_LENGTH; + assert !compress || uncompressedLength <= Segment.MAX_PAYLOAD_LENGTH; + + int headerLength = headerLength(); + + long headerData = payloadLength; + int flagOffset = 17; + if (compress) { + headerData |= (long) uncompressedLength << 17; + flagOffset += 17; + } + if (isSelfContained) { + headerData |= 1L << flagOffset; + } + + int headerCrc = Crc.computeCrc24(headerData, headerLength); + + ByteBuf header = allocator.ioBuffer(headerLength + CRC24_LENGTH); + // Write both data and CRC in little-endian order + for (int i = 0; i < headerLength; i++) { + int shift = i * 8; + header.writeByte((int) (headerData >> shift & 0xFF)); + } + for (int i = 0; i < CRC24_LENGTH; i++) { + int shift = i * 8; + header.writeByte(headerCrc >> shift & 0xFF); + } + return header; + } + + /** + * Decodes a segment header and checks its CRC. It is assumed that the caller has already checked + * that there are enough bytes. + */ + Header decodeHeader(ByteBuf buffer) throws CrcMismatchException { + int headerLength = headerLength(); + assert buffer.readableBytes() >= headerLength + CRC24_LENGTH; + + // Read header data (little endian): + long headerData = 0; + for (int i = 0; i < headerLength; i++) { + headerData |= (buffer.readByte() & 0xFFL) << 8 * i; + } + + // Read CRC (little endian) and check it: + int expectedHeaderCrc = 0; + for (int i = 0; i < CRC24_LENGTH; i++) { + expectedHeaderCrc |= (buffer.readByte() & 0xFF) << 8 * i; + } + int actualHeaderCrc = Crc.computeCrc24(headerData, headerLength); + if (actualHeaderCrc != expectedHeaderCrc) { + throw new CrcMismatchException( + String.format( + "CRC mismatch on header %s. Received %s, computed %s.", + Long.toHexString(headerData), + Integer.toHexString(expectedHeaderCrc), + Integer.toHexString(actualHeaderCrc))); + } + + int payloadLength = (int) headerData & Segment.MAX_PAYLOAD_LENGTH; + headerData >>= 17; + int uncompressedPayloadLength; + if (compress) { + uncompressedPayloadLength = (int) headerData & Segment.MAX_PAYLOAD_LENGTH; + headerData >>= 17; + } else { + uncompressedPayloadLength = -1; + } + boolean isSelfContained = (headerData & 1) == 1; + return new Header(payloadLength, uncompressedPayloadLength, isSelfContained); + } + + /** + * Decodes the rest of a segment from a previously decoded header, and checks the payload's CRC. + * It is assumed that the caller has already checked that there are enough bytes. + */ + Segment decode(Header header, ByteBuf buffer) throws CrcMismatchException, IOException { + assert buffer.readableBytes() == header.payloadLength + CRC32_LENGTH; + + // Extract payload: + ByteBuf encodedPayload = buffer.readSlice(header.payloadLength); + encodedPayload.retain(); + + // Read and check CRC: + int expectedPayloadCrc = 0; + for (int i = 0; i < CRC32_LENGTH; i++) { + expectedPayloadCrc |= (buffer.readByte() & 0xFF) << 8 * i; + } + buffer.release(); // done with this (we retained the payload independently) + int actualPayloadCrc = Crc.computeCrc32(encodedPayload); + if (actualPayloadCrc != expectedPayloadCrc) { + encodedPayload.release(); + throw new CrcMismatchException( + String.format( + "CRC mismatch on payload. Received %s, computed %s.", + Integer.toHexString(expectedPayloadCrc), Integer.toHexString(actualPayloadCrc))); + } + + // Decompress payload if needed: + ByteBuf payload; + if (compress && header.uncompressedPayloadLength > 0) { + payload = compressor.decompress(encodedPayload, header.uncompressedPayloadLength); + encodedPayload.release(); + } else { + payload = encodedPayload; + } + + return new Segment(payload, header.isSelfContained); + } + + /** Temporary holder for header data. During decoding, it is convenient to store it separately. */ + static class Header { + final int payloadLength; + final int uncompressedPayloadLength; + final boolean isSelfContained; + + public Header(int payloadLength, int uncompressedPayloadLength, boolean isSelfContained) { + this.payloadLength = payloadLength; + this.uncompressedPayloadLength = uncompressedPayloadLength; + this.isSelfContained = isSelfContained; + } + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/SegmentToBytesEncoder.java b/driver-core/src/main/java/com/datastax/driver/core/SegmentToBytesEncoder.java new file mode 100644 index 00000000000..58c51bf2c83 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/SegmentToBytesEncoder.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.driver.core; + +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToMessageEncoder; +import java.util.List; + +@ChannelHandler.Sharable +class SegmentToBytesEncoder extends MessageToMessageEncoder { + + private final SegmentCodec codec; + + SegmentToBytesEncoder(SegmentCodec codec) { + super(Segment.class); + this.codec = codec; + } + + @Override + protected void encode(ChannelHandlerContext ctx, Segment segment, List out) + throws Exception { + codec.encode(segment, out); + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/SegmentToFrameDecoder.java b/driver-core/src/main/java/com/datastax/driver/core/SegmentToFrameDecoder.java new file mode 100644 index 00000000000..7155895e8e8 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/SegmentToFrameDecoder.java @@ -0,0 +1,97 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +import com.datastax.driver.core.Frame.Header; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.buffer.CompositeByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToMessageDecoder; +import java.util.ArrayList; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Converts the segments decoded by {@link BytesToSegmentDecoder} into legacy frames understood by + * the rest of the driver. + */ +class SegmentToFrameDecoder extends MessageToMessageDecoder { + + private static final Logger logger = LoggerFactory.getLogger(SegmentToFrameDecoder.class); + + // Accumulated state when we are reading a sequence of slices + private Header pendingHeader; + private final List accumulatedSlices = new ArrayList(); + private int accumulatedLength; + + SegmentToFrameDecoder() { + super(Segment.class); + } + + @Override + protected void decode(ChannelHandlerContext ctx, Segment segment, List out) { + if (segment.isSelfContained()) { + decodeSelfContained(segment, out); + } else { + decodeSlice(segment, ctx.alloc(), out); + } + } + + private void decodeSelfContained(Segment segment, List out) { + ByteBuf payload = segment.getPayload(); + int frameCount = 0; + do { + Header header = Header.decode(payload); + ByteBuf body = payload.readSlice(header.bodyLength); + body.retain(); + out.add(new Frame(header, body)); + frameCount += 1; + } while (payload.isReadable()); + payload.release(); + logger.trace("Decoded self-contained segment into {} frame(s)", frameCount); + } + + private void decodeSlice(Segment segment, ByteBufAllocator allocator, List out) { + assert pendingHeader != null ^ (accumulatedSlices.isEmpty() && accumulatedLength == 0); + ByteBuf payload = segment.getPayload(); + if (pendingHeader == null) { // first slice + pendingHeader = Header.decode(payload); // note: this consumes the header data + } + accumulatedSlices.add(payload); + accumulatedLength += payload.readableBytes(); + logger.trace( + "StreamId {}: decoded slice {}, {}/{} bytes", + pendingHeader.streamId, + accumulatedSlices.size(), + accumulatedLength, + pendingHeader.bodyLength); + assert accumulatedLength <= pendingHeader.bodyLength; + if (accumulatedLength == pendingHeader.bodyLength) { + // We've received enough data to reassemble the whole message + CompositeByteBuf body = allocator.compositeBuffer(accumulatedSlices.size()); + body.addComponents(true, accumulatedSlices); + out.add(new Frame(pendingHeader, body)); + // Reset our state + pendingHeader = null; + accumulatedSlices.clear(); + accumulatedLength = 0; + } + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/ServerSideTimestampGenerator.java b/driver-core/src/main/java/com/datastax/driver/core/ServerSideTimestampGenerator.java index 6f54660f36b..4e917941614 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ServerSideTimestampGenerator.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/Session.java b/driver-core/src/main/java/com/datastax/driver/core/Session.java index a8e4a59b2a8..d4ab7bfbc75 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Session.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/SessionManager.java b/driver-core/src/main/java/com/datastax/driver/core/SessionManager.java index f0d38b0b92e..476ddc55269 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +++ b/driver-core/src/main/java/com/datastax/driver/core/SessionManager.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,10 +36,8 @@ import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.SettableFuture; import com.google.common.util.concurrent.Uninterruptibles; -import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -235,7 +235,7 @@ public ListenableFuture apply(Response response) { // the nodes of this session. // If that changes, we'll have to make sure this propagate to other sessions // too. - return prepare(stmt, future.getAddress()); + return prepare(stmt, future.getEndPoint()); } else { return Futures.immediateFuture(stmt); } @@ -248,7 +248,7 @@ public ListenableFuture apply(Response response) { } case ERROR: return Futures.immediateFailedFuture( - ((Responses.Error) response).asException(future.getAddress())); + ((Responses.Error) response).asException(future.getEndPoint())); default: return Futures.immediateFailedFuture( new DriverInternalError( @@ -582,6 +582,12 @@ else if (fetchSize != Integer.MAX_VALUE) usedPagingState = statement.getPagingState(); } + int nowInSeconds = statement.getNowInSeconds(); + if (nowInSeconds != Integer.MIN_VALUE && protocolVersion.compareTo(ProtocolVersion.V5) < 0) { + throw new UnsupportedFeatureException( + protocolVersion, "Now in seconds is only supported since native protocol V5"); + } + if (statement instanceof StatementWrapper) statement = ((StatementWrapper) statement).getWrappedStatement(); @@ -608,10 +614,8 @@ else if (fetchSize != Integer.MAX_VALUE) if (protocolVersion == ProtocolVersion.V2 && rawNamedValues != null) throw new UnsupportedFeatureException(protocolVersion, "Named values are not supported"); - List positionalValues = - rawPositionalValues == null - ? Collections.emptyList() - : Arrays.asList(rawPositionalValues); + ByteBuffer[] positionalValues = + rawPositionalValues == null ? Requests.EMPTY_BB_ARRAY : rawPositionalValues; Map namedValues = rawNamedValues == null ? Collections.emptyMap() : rawNamedValues; @@ -627,7 +631,8 @@ else if (fetchSize != Integer.MAX_VALUE) fetchSize, usedPagingState, serialConsistency, - defaultTimestamp); + defaultTimestamp, + nowInSeconds); request = new Requests.Query(qString, options, statement.isTracing()); } else if (statement instanceof BoundStatement) { BoundStatement bs = (BoundStatement) statement; @@ -650,13 +655,14 @@ else if (fetchSize != Integer.MAX_VALUE) new Requests.QueryProtocolOptions( Message.Request.Type.EXECUTE, consistency, - Arrays.asList(bs.wrapper.values), + bs.wrapper.values, Collections.emptyMap(), skipMetadata, fetchSize, usedPagingState, serialConsistency, - defaultTimestamp); + defaultTimestamp, + nowInSeconds); request = new Requests.Execute( bs.statement.getPreparedId().boundValuesMetadata.id, @@ -675,7 +681,8 @@ else if (fetchSize != Integer.MAX_VALUE) if (protocolVersion.compareTo(ProtocolVersion.V4) < 0) bs.ensureAllSet(); BatchStatement.IdAndValues idAndVals = bs.getIdAndValues(protocolVersion, codecRegistry); Requests.BatchProtocolOptions options = - new Requests.BatchProtocolOptions(consistency, serialConsistency, defaultTimestamp); + new Requests.BatchProtocolOptions( + consistency, serialConsistency, defaultTimestamp, nowInSeconds); request = new Requests.Batch( bs.batchType, idAndVals.ids, idAndVals.values, options, statement.isTracing()); @@ -711,11 +718,11 @@ public void run() { } private ListenableFuture prepare( - final PreparedStatement statement, InetSocketAddress toExclude) { + final PreparedStatement statement, EndPoint toExclude) { final String query = statement.getQueryString(); List> futures = Lists.newArrayListWithExpectedSize(pools.size()); for (final Map.Entry entry : pools.entrySet()) { - if (entry.getKey().getSocketAddress().equals(toExclude)) continue; + if (entry.getKey().getEndPoint().equals(toExclude)) continue; try { // Preparing is not critical: if it fails, it will fix itself later when the user tries to diff --git a/driver-core/src/main/java/com/datastax/driver/core/SettableByIndexData.java b/driver-core/src/main/java/com/datastax/driver/core/SettableByIndexData.java index aba3af457da..6c37476036e 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/SettableByIndexData.java +++ b/driver-core/src/main/java/com/datastax/driver/core/SettableByIndexData.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/SettableByNameData.java b/driver-core/src/main/java/com/datastax/driver/core/SettableByNameData.java index 4c606702cf5..f9ae68525d1 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/SettableByNameData.java +++ b/driver-core/src/main/java/com/datastax/driver/core/SettableByNameData.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/SettableData.java b/driver-core/src/main/java/com/datastax/driver/core/SettableData.java index 493c487670d..f9ac384820e 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/SettableData.java +++ b/driver-core/src/main/java/com/datastax/driver/core/SettableData.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/SimpleJSONParser.java b/driver-core/src/main/java/com/datastax/driver/core/SimpleJSONParser.java index b8c38db510d..d8d41e1d9c7 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/SimpleJSONParser.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java b/driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java index 2a1be224ed3..5b65957af2c 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, diff --git a/driver-core/src/main/java/com/datastax/driver/core/SnappyCompressor.java b/driver-core/src/main/java/com/datastax/driver/core/SnappyCompressor.java index 6f0c9f3811f..fc1afdd2c6f 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/SnappyCompressor.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -54,9 +56,12 @@ private SnappyCompressor() { @Override Frame compress(Frame frame) throws IOException { - ByteBuf input = frame.body; - ByteBuf frameBody = input.isDirect() ? compressDirect(input) : compressHeap(input); - return frame.with(frameBody); + return frame.with(compress(frame.body)); + } + + @Override + ByteBuf compress(ByteBuf buffer) throws IOException { + return buffer.isDirect() ? compressDirect(buffer) : compressHeap(buffer); } private ByteBuf compressDirect(ByteBuf input) throws IOException { @@ -117,6 +122,13 @@ Frame decompress(Frame frame) throws IOException { return frame.with(frameBody); } + @Override + ByteBuf decompress(ByteBuf buffer, int uncompressedLength) throws IOException { + // Note that the Snappy algorithm already encodes the uncompressed length, we don't need the + // provided one. + return buffer.isDirect() ? decompressDirect(buffer) : decompressHeap(buffer); + } + private ByteBuf decompressDirect(ByteBuf input) throws IOException { ByteBuffer in = inputNioBuffer(input); // Increase reader index. diff --git a/driver-core/src/main/java/com/datastax/driver/core/SniEndPoint.java b/driver-core/src/main/java/com/datastax/driver/core/SniEndPoint.java new file mode 100644 index 00000000000..46e9b54a653 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/SniEndPoint.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.driver.core; + +import com.google.common.base.Objects; +import com.google.common.base.Preconditions; +import com.google.common.primitives.UnsignedBytes; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.util.Arrays; +import java.util.Comparator; +import java.util.concurrent.atomic.AtomicLong; + +/** An endpoint to access nodes through a proxy that uses SNI routing. */ +public class SniEndPoint implements EndPoint { + + private static final AtomicLong OFFSET = new AtomicLong(); + + private final InetSocketAddress proxyAddress; + private final String serverName; + + /** + * @param proxyAddress the address of the proxy. If it is {@linkplain + * InetSocketAddress#isUnresolved() unresolved}, each call to {@link #resolve()} will + * re-resolve it, fetch all of its A-records, and if there are more than 1 pick one in a + * round-robin fashion. + * @param serverName the SNI server name. In the context of DSOD, this is the string + * representation of the host id. + */ + public SniEndPoint(InetSocketAddress proxyAddress, String serverName) { + Preconditions.checkNotNull(proxyAddress); + Preconditions.checkNotNull(serverName); + this.proxyAddress = proxyAddress; + this.serverName = serverName; + } + + @Override + public InetSocketAddress resolve() { + if (proxyAddress.isUnresolved()) { + try { + InetAddress[] aRecords = InetAddress.getAllByName(proxyAddress.getHostName()); + if (aRecords.length == 0) { + // Probably never happens, but the JDK docs don't explicitly say so + throw new IllegalArgumentException( + "Could not resolve proxy address " + proxyAddress.getHostName()); + } + // 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; + return new InetSocketAddress(aRecords[index], proxyAddress.getPort()); + } catch (UnknownHostException e) { + throw new IllegalArgumentException( + "Could not resolve proxy address " + proxyAddress.getHostName(), e); + } + } else { + return proxyAddress; + } + } + + String getServerName() { + return serverName; + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } else if (other instanceof SniEndPoint) { + SniEndPoint that = (SniEndPoint) other; + return this.proxyAddress.equals(that.proxyAddress) && this.serverName.equals(that.serverName); + } else { + return false; + } + } + + @Override + public int hashCode() { + return Objects.hashCode(proxyAddress, serverName); + } + + @Override + public String toString() { + // Note that this uses the original proxy address, so if there are multiple A-records it won't + // show which one was selected. If that turns out to be a problem for debugging, we might need + // to store the result of resolve() in Connection and log that instead of the endpoint. + return proxyAddress.toString() + ":" + serverName; + } + + private static final Comparator IP_COMPARATOR = + new Comparator() { + @Override + public int compare(InetAddress address1, InetAddress address2) { + return UnsignedBytes.lexicographicalComparator() + .compare(address1.getAddress(), address2.getAddress()); + } + }; +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/SniEndPointFactory.java b/driver-core/src/main/java/com/datastax/driver/core/SniEndPointFactory.java new file mode 100644 index 00000000000..f40550dbd99 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/SniEndPointFactory.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.datastax.driver.core; + +import java.net.InetSocketAddress; +import java.util.UUID; + +public class SniEndPointFactory implements EndPointFactory { + + private final InetSocketAddress proxyAddress; + + public SniEndPointFactory(InetSocketAddress proxyAddress) { + this.proxyAddress = proxyAddress; + } + + @Override + public void init(Cluster cluster) {} + + @Override + public EndPoint create(Row peersRow) { + UUID host_id = peersRow.getUUID("host_id"); + return new SniEndPoint(proxyAddress, host_id.toString()); + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/SniSSLOptions.java b/driver-core/src/main/java/com/datastax/driver/core/SniSSLOptions.java new file mode 100644 index 00000000000..ae9476e3553 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/SniSSLOptions.java @@ -0,0 +1,135 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +import com.google.common.collect.ImmutableList; +import io.netty.channel.socket.SocketChannel; +import io.netty.handler.ssl.SslHandler; +import java.net.InetSocketAddress; +import java.util.concurrent.CopyOnWriteArrayList; +import javax.net.ssl.SNIHostName; +import javax.net.ssl.SNIServerName; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLParameters; + +@IgnoreJDK6Requirement +@SuppressWarnings("deprecation") +public class SniSSLOptions extends JdkSSLOptions implements ExtendedRemoteEndpointAwareSslOptions { + + // An offset that gets added to our "fake" ports (see below). We pick this value because it is the + // start of the ephemeral port range. + private static final int FAKE_PORT_OFFSET = 49152; + + private final CopyOnWriteArrayList fakePorts = new CopyOnWriteArrayList(); + + /** + * Creates a new instance. + * + * @param context the SSL context. + * @param cipherSuites the cipher suites to use. + */ + protected SniSSLOptions(SSLContext context, String[] cipherSuites) { + super(context, cipherSuites); + } + + @Override + public SslHandler newSSLHandler(SocketChannel channel) { + throw new AssertionError( + "This class implements RemoteEndpointAwareSSLOptions, this method should not be called"); + } + + @Override + public SslHandler newSSLHandler(SocketChannel channel, EndPoint remoteEndpoint) { + SSLEngine engine = newSSLEngine(channel, remoteEndpoint); + return new SslHandler(engine); + } + + @Override + public SslHandler newSSLHandler(SocketChannel channel, InetSocketAddress remoteEndpoint) { + throw new AssertionError( + "The driver should never call this method on an object that implements " + + this.getClass().getSimpleName()); + } + + protected SSLEngine newSSLEngine( + @SuppressWarnings("unused") SocketChannel channel, EndPoint remoteEndpoint) { + if (!(remoteEndpoint instanceof SniEndPoint)) { + throw new IllegalArgumentException( + String.format( + "Configuration error: can only use %s with SNI end points", + this.getClass().getSimpleName())); + } + SniEndPoint sniEndPoint = (SniEndPoint) remoteEndpoint; + InetSocketAddress address = sniEndPoint.resolve(); + String sniServerName = sniEndPoint.getServerName(); + + // When hostname verification is enabled (with setEndpointIdentificationAlgorithm), the SSL + // engine will try to match the server's certificate against the SNI host name; if that doesn't + // work, it will fall back to the "advisory peer host" passed to createSSLEngine. + // + // In our case, the first check will never succeed because our SNI host name is not the DNS name + // (we use the Cassandra host_id instead). So we *must* set the advisory peer information. + // + // However if we use the address as-is, this leads to another issue: the advisory peer + // information is also used to cache SSL sessions internally. All of our nodes share the same + // proxy address, so the JDK tries to reuse SSL sessions across nodes. But it doesn't update the + // SNI host name every time, so it ends up opening connections to the wrong node. + // + // 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 = context.createSSLEngine(address.getHostName(), getFakePort(sniServerName)); + engine.setUseClientMode(true); + SSLParameters parameters = engine.getSSLParameters(); + parameters.setServerNames(ImmutableList.of(new SNIHostName(sniServerName))); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + engine.setSSLParameters(parameters); + if (cipherSuites != null) engine.setEnabledCipherSuites(cipherSuites); + return engine; + } + + private int getFakePort(String sniServerName) { + fakePorts.addIfAbsent(sniServerName); + return FAKE_PORT_OFFSET + fakePorts.indexOf(sniServerName); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends JdkSSLOptions.Builder { + + @Override + public SniSSLOptions.Builder withSSLContext(SSLContext context) { + super.withSSLContext(context); + return this; + } + + @Override + public SniSSLOptions.Builder withCipherSuites(String[] cipherSuites) { + super.withCipherSuites(cipherSuites); + return this; + } + + @Override + public SniSSLOptions build() { + return new SniSSLOptions(context, cipherSuites); + } + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/SocketOptions.java b/driver-core/src/main/java/com/datastax/driver/core/SocketOptions.java index 3517c82cd5e..61f7beabd29 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/SocketOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/SocketOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/Statement.java b/driver-core/src/main/java/com/datastax/driver/core/Statement.java index 56ffdcbc1bf..a6190dfb1cb 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Statement.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -74,6 +76,7 @@ public ConsistencyLevel getConsistencyLevel() { protected volatile Boolean idempotent; private volatile Map outgoingPayload; private volatile Host host; + private volatile int nowInSeconds = Integer.MIN_VALUE; // We don't want to expose the constructor, because the code relies on this being only sub-classed // by RegularStatement, BoundStatement and BatchStatement @@ -648,4 +651,21 @@ public Statement setHost(Host host) { this.host = host; return this; } + + /** + * @return a custom "now in seconds" to use when applying the request (for testing purposes). + * {@link Integer#MIN_VALUE} means "no value". + */ + public int getNowInSeconds() { + return nowInSeconds; + } + + /** + * Sets the "now in seconds" to use when applying the request (for testing purposes). {@link + * Integer#MIN_VALUE} means "no value". + */ + public Statement setNowInSeconds(int nowInSeconds) { + this.nowInSeconds = nowInSeconds; + return this; + } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/StatementWrapper.java b/driver-core/src/main/java/com/datastax/driver/core/StatementWrapper.java index 89903f97c5c..ffcb26a3ad7 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/StatementWrapper.java +++ b/driver-core/src/main/java/com/datastax/driver/core/StatementWrapper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -233,4 +235,15 @@ public Statement setHost(Host host) { wrapped.setHost(host); return this; } + + @Override + public int getNowInSeconds() { + return wrapped.getNowInSeconds(); + } + + @Override + public Statement setNowInSeconds(int nowInSeconds) { + wrapped.setNowInSeconds(nowInSeconds); + return this; + } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/StreamIdGenerator.java b/driver-core/src/main/java/com/datastax/driver/core/StreamIdGenerator.java index b7f613d569f..f914adcfc5c 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/StreamIdGenerator.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -47,6 +49,7 @@ private static int streamIdSizeFor(ProtocolVersion version) { case V3: case V4: case V5: + case V6: return 2; default: throw version.unsupported(); diff --git a/driver-core/src/main/java/com/datastax/driver/core/SystemProperties.java b/driver-core/src/main/java/com/datastax/driver/core/SystemProperties.java index 7c5541e4295..8d78d81a677 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/SystemProperties.java +++ b/driver-core/src/main/java/com/datastax/driver/core/SystemProperties.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java b/driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java index f818d4880f9..c88f8183d44 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/TableOptionsMetadata.java b/driver-core/src/main/java/com/datastax/driver/core/TableOptionsMetadata.java index ccfed3bba29..15c172ef37f 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/TableOptionsMetadata.java +++ b/driver-core/src/main/java/com/datastax/driver/core/TableOptionsMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,9 +25,10 @@ public class TableOptionsMetadata { private static final String COMMENT = "comment"; - private static final String READ_REPAIR = "read_repair_chance"; - private static final String DCLOCAL_READ_REPAIR = "dclocal_read_repair_chance"; - private static final String LOCAL_READ_REPAIR = "local_read_repair_chance"; + private static final String READ_REPAIR_CHANCE = "read_repair_chance"; + private static final String DCLOCAL_READ_REPAIR_CHANCE = "dclocal_read_repair_chance"; + private static final String READ_REPAIR = "read_repair"; + private static final String LOCAL_READ_REPAIR_CHANCE = "local_read_repair_chance"; private static final String REPLICATE_ON_WRITE = "replicate_on_write"; private static final String GC_GRACE = "gc_grace_seconds"; private static final String BF_FP_CHANCE = "bloom_filter_fp_chance"; @@ -45,6 +48,7 @@ public class TableOptionsMetadata { private static final String CRC_CHECK_CHANCE = "crc_check_chance"; private static final String EXTENSIONS = "extensions"; private static final String CDC = "cdc"; + private static final String ADDITIONAL_WRITE_POLICY = "additional_write_policy"; private static final boolean DEFAULT_REPLICATE_ON_WRITE = true; private static final double DEFAULT_BF_FP_CHANCE = 0.01; @@ -57,12 +61,15 @@ public class TableOptionsMetadata { private static final int DEFAULT_MAX_INDEX_INTERVAL = 2048; private static final double DEFAULT_CRC_CHECK_CHANCE = 1.0; private static final boolean DEFAULT_CDC = false; + private static final String DEFAULT_READ_REPAIR = "BLOCKING"; + private static final String DEFAULT_ADDITIONAL_WRITE_POLICY = "99p"; private final boolean isCompactStorage; private final String comment; - private final double readRepair; - private final double localReadRepair; + private final double readRepairChance; + private final double localReadRepairChance; + private final String readRepair; private final boolean replicateOnWrite; private final int gcGrace; private final double bfFpChance; @@ -79,6 +86,7 @@ public class TableOptionsMetadata { private final Double crcCheckChance; private final Map extensions; private final boolean cdc; + private final String additionalWritePolicy; TableOptionsMetadata(Row row, boolean isCompactStorage, VersionNumber version) { @@ -92,10 +100,13 @@ public class TableOptionsMetadata { this.isCompactStorage = isCompactStorage; this.comment = isNullOrAbsent(row, COMMENT) ? "" : row.getString(COMMENT); - this.readRepair = row.getDouble(READ_REPAIR); + this.readRepairChance = row.getDouble(READ_REPAIR_CHANCE); + + if (is400OrHigher) this.readRepair = row.getString(READ_REPAIR); + else this.readRepair = DEFAULT_READ_REPAIR; - if (is300OrHigher) this.localReadRepair = row.getDouble(DCLOCAL_READ_REPAIR); - else this.localReadRepair = row.getDouble(LOCAL_READ_REPAIR); + if (is300OrHigher) this.localReadRepairChance = row.getDouble(DCLOCAL_READ_REPAIR_CHANCE); + else this.localReadRepairChance = row.getDouble(LOCAL_READ_REPAIR_CHANCE); this.replicateOnWrite = is210OrHigher || isNullOrAbsent(row, REPLICATE_ON_WRITE) @@ -176,6 +187,9 @@ public class TableOptionsMetadata { if (is380OrHigher) this.cdc = isNullOrAbsent(row, CDC) ? DEFAULT_CDC : row.getBool(CDC); else this.cdc = DEFAULT_CDC; + + if (is400OrHigher) this.additionalWritePolicy = row.getString(ADDITIONAL_WRITE_POLICY); + else this.additionalWritePolicy = DEFAULT_ADDITIONAL_WRITE_POLICY; } private static boolean isNullOrAbsent(Row row, String name) { @@ -206,6 +220,19 @@ public String getComment() { * @return the read repair chance set for table (in [0.0, 1.0]). */ public double getReadRepairChance() { + return readRepairChance; + } + + /** + * Returns the read_repair option for this table. NOTE: this is a Cassandra® 4.0 and newer + * option (described here: + * http://cassandra.apache.org/doc/latest/operating/read_repair.html). Possible values are + * {@code BLOCKING} or {@code NONE}, with the default being {@code BLOCKING}. + * + * @return the read repair option (either {@code BLOCKING} or {@code NONE}). + */ + public String getReadRepair() { return readRepair; } @@ -215,7 +242,7 @@ public double getReadRepairChance() { * @return the local read repair chance set for table (in [0.0, 1.0]). */ public double getLocalReadRepairChance() { - return localReadRepair; + return localReadRepairChance; } /** @@ -396,6 +423,17 @@ public boolean isCDC() { return cdc; } + /** + * The threshold at which a cheap quorum write will be upgraded to include transient replicas. + * + *

This option is only available in Cassandra® 4.0 and above. Default value is {@code 99p}. + * + * @return The additional write policy for this table (ex. '99p'). + */ + public String getAdditionalWritePolicy() { + return additionalWritePolicy; + } + @Override public boolean equals(Object other) { if (other == this) return true; @@ -404,8 +442,9 @@ public boolean equals(Object other) { TableOptionsMetadata that = (TableOptionsMetadata) other; return this.isCompactStorage == that.isCompactStorage && MoreObjects.equal(this.comment, that.comment) - && this.readRepair == that.readRepair - && this.localReadRepair == that.localReadRepair + && this.readRepairChance == that.readRepairChance + && this.localReadRepairChance == that.localReadRepairChance + && MoreObjects.equal(this.readRepair, that.readRepair) && this.replicateOnWrite == that.replicateOnWrite && this.gcGrace == that.gcGrace && this.bfFpChance == that.bfFpChance @@ -421,6 +460,7 @@ public boolean equals(Object other) { && MoreObjects.equal(this.compaction, that.compaction) && MoreObjects.equal(this.compression, that.compression) && MoreObjects.equal(this.crcCheckChance, that.crcCheckChance) + && MoreObjects.equal(this.additionalWritePolicy, that.additionalWritePolicy) && MoreObjects.equal(this.extensions, that.extensions); } @@ -429,8 +469,9 @@ public int hashCode() { return MoreObjects.hashCode( isCompactStorage, comment, + readRepairChance, + localReadRepairChance, readRepair, - localReadRepair, replicateOnWrite, gcGrace, bfFpChance, @@ -446,6 +487,7 @@ public int hashCode() { compression, crcCheckChance, extensions, - cdc); + cdc, + additionalWritePolicy); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGenerator.java b/driver-core/src/main/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGenerator.java index 612f2208e1f..bcadb3007a2 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGenerator.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGenerator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/ThreadingOptions.java b/driver-core/src/main/java/com/datastax/driver/core/ThreadingOptions.java index 47f9c1c8700..07c99a874bc 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ThreadingOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ThreadingOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/TimestampGenerator.java b/driver-core/src/main/java/com/datastax/driver/core/TimestampGenerator.java index 242ec4aa2bd..309db0cb88a 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/TimestampGenerator.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/Token.java b/driver-core/src/main/java/com/datastax/driver/core/Token.java index 733cb604e43..79bd75c5ab5 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/Token.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -418,7 +420,8 @@ List split(Token startToken, Token endToken, int numberOfSplits) { start = toBigInteger(oppStartToken.value, significantBytes); end = toBigInteger(oppEndToken.value, significantBytes); range = end.subtract(start); - if (addedBytes == 4 || range.compareTo(bigNumberOfSplits) >= 0) break; + if (addedBytes == 4 || start.equals(end) || range.compareTo(bigNumberOfSplits) >= 0) + break; significantBytes += 1; addedBytes += 1; } @@ -486,21 +489,7 @@ protected ByteBuffer toBytes(BigInteger value, int significantBytes) { @VisibleForTesting OPPToken(ByteBuffer value) { - this.value = stripTrailingZeroBytes(value); - } - - /** @return A new ByteBuffer from the input Buffer with any trailing 0-bytes stripped off. */ - private static ByteBuffer stripTrailingZeroBytes(ByteBuffer b) { - byte result[] = Bytes.getArray(b); - int zeroIndex = result.length; - for (int i = result.length - 1; i > 0; i--) { - if (result[i] == 0) { - zeroIndex = i; - } else { - break; - } - } - return ByteBuffer.wrap(result, 0, zeroIndex); + this.value = value; } @Override diff --git a/driver-core/src/main/java/com/datastax/driver/core/TokenRange.java b/driver-core/src/main/java/com/datastax/driver/core/TokenRange.java index 3b62c1fedc6..40b41ed0a51 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/TokenRange.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/TranslatedAddressEndPoint.java b/driver-core/src/main/java/com/datastax/driver/core/TranslatedAddressEndPoint.java new file mode 100644 index 00000000000..168376f53b5 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/TranslatedAddressEndPoint.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.driver.core; + +import com.google.common.base.Objects; +import java.net.InetSocketAddress; + +/** + * An endpoint based on server-reported RPC addresses, that might require translation if they are + * accessed through a proxy. + */ +class TranslatedAddressEndPoint implements EndPoint { + + private final InetSocketAddress translatedAddress; + + TranslatedAddressEndPoint(InetSocketAddress translatedAddress) { + this.translatedAddress = translatedAddress; + } + + @Override + public InetSocketAddress resolve() { + return translatedAddress; + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } else if (other instanceof TranslatedAddressEndPoint) { + TranslatedAddressEndPoint that = (TranslatedAddressEndPoint) other; + return Objects.equal(this.translatedAddress, that.translatedAddress); + } else { + return false; + } + } + + @Override + public int hashCode() { + return translatedAddress.hashCode(); + } + + @Override + public String toString() { + return translatedAddress.toString(); + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/TupleType.java b/driver-core/src/main/java/com/datastax/driver/core/TupleType.java index eb4e7bc118f..deac9aa0624 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/TupleType.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/TupleValue.java b/driver-core/src/main/java/com/datastax/driver/core/TupleValue.java index 952c3453ab4..57622546c72 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/TupleValue.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java b/driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java index 52c904456a8..e78e7eb7ad7 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, @@ -30,7 +32,6 @@ import com.google.common.reflect.TypeToken; import java.io.DataInput; import java.io.IOException; -import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.net.InetAddress; @@ -592,7 +593,11 @@ public boolean accepts(TypeToken javaType) { /** * Return {@code true} if this codec is capable of serializing the given {@code javaType}. * - *

This implementation simply calls {@link #accepts(TypeToken)}. + *

This implementation simply compares the given type against this codec's runtime (raw) type + * for equality; it is invariant with respect to the passed argument (through the usage + * of {@link Class#equals(Object)} and it's strongly recommended not to modify this + * behavior. This means that a codec will only ever return {@code true} for the + * exact runtime (raw) Java type that it has been created for. * * @param javaType The Java type this codec should serialize from and deserialize to; cannot be * {@code null}. @@ -602,7 +607,26 @@ public boolean accepts(TypeToken javaType) { */ public boolean accepts(Class javaType) { checkNotNull(javaType, "Parameter javaType cannot be null"); - return accepts(TypeToken.of(javaType)); + if (javaType.isPrimitive()) { + if (javaType == Boolean.TYPE) { + javaType = Boolean.class; + } else if (javaType == Character.TYPE) { + javaType = Character.class; + } else if (javaType == Byte.TYPE) { + javaType = Byte.class; + } else if (javaType == Short.TYPE) { + javaType = Short.class; + } else if (javaType == Integer.TYPE) { + javaType = Integer.class; + } else if (javaType == Long.TYPE) { + javaType = Long.class; + } else if (javaType == Float.TYPE) { + javaType = Float.class; + } else if (javaType == Double.TYPE) { + javaType = Double.class; + } + } + return this.javaType.getRawType().equals(javaType); } /** @@ -621,7 +645,7 @@ public boolean accepts(DataType cqlType) { /** * Return {@code true} if this codec is capable of serializing the given object. Note that the - * object's Java type is inferred from the object' runtime (raw) type, contrary to {@link + * object's Java type is inferred from the object's runtime (raw) type, contrary to {@link * #accepts(TypeToken)} which is capable of handling generic types. * *

This method is intended mostly to be used by the QueryBuilder when no type information is @@ -631,10 +655,9 @@ public boolean accepts(DataType cqlType) { * *

    *
  1. The default implementation is covariant with respect to the passed argument - * (through the usage of {@link TypeToken#isAssignableFrom(TypeToken)} or {@link - * TypeToken#isSupertypeOf(Type)}) and it's strongly recommended not to modify this - * behavior. This means that, by default, a codec will accept any subtype of - * the Java type that it has been created for. + * (through the usage of {@link Class#isAssignableFrom(Class)}) and it's strongly + * recommended not to modify this behavior. This means that, by default, a codec will + * accept any subtype of the Java type that it has been created for. *
  2. The base implementation provided here can only handle non-parameterized types; codecs * handling parameterized types, such as collection types, must override this method and * perform some sort of "manual" inspection of the actual type parameters. @@ -651,7 +674,7 @@ public boolean accepts(DataType cqlType) { */ public boolean accepts(Object value) { checkNotNull(value, "Parameter value cannot be null"); - return GuavaCompatibility.INSTANCE.isSupertypeOf(this.javaType, TypeToken.of(value.getClass())); + return javaType.getRawType().isAssignableFrom(value.getClass()); } @Override diff --git a/driver-core/src/main/java/com/datastax/driver/core/TypeTokens.java b/driver-core/src/main/java/com/datastax/driver/core/TypeTokens.java index c912b096332..990b4c4dd86 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/TypeTokens.java +++ b/driver-core/src/main/java/com/datastax/driver/core/TypeTokens.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/UDTValue.java b/driver-core/src/main/java/com/datastax/driver/core/UDTValue.java index a1b9e196222..a5af7e2e5e7 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/UDTValue.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/UserType.java b/driver-core/src/main/java/com/datastax/driver/core/UserType.java index 1683b7b022c..50afc48913a 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/UserType.java +++ b/driver-core/src/main/java/com/datastax/driver/core/UserType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/VIntCoding.java b/driver-core/src/main/java/com/datastax/driver/core/VIntCoding.java index 3113b658bdc..84aba9bb1d5 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/VIntCoding.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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, diff --git a/driver-core/src/main/java/com/datastax/driver/core/VersionNumber.java b/driver-core/src/main/java/com/datastax/driver/core/VersionNumber.java index 58e9ef47a8c..debf049ce9b 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/VersionNumber.java +++ b/driver-core/src/main/java/com/datastax/driver/core/VersionNumber.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/WriteType.java b/driver-core/src/main/java/com/datastax/driver/core/WriteType.java index c16e3ec44cf..332fc125d27 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/WriteType.java +++ b/driver-core/src/main/java/com/datastax/driver/core/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/driver-core/src/main/java/com/datastax/driver/core/exceptions/AlreadyExistsException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/AlreadyExistsException.java index b019e83a067..692383c9ec9 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/AlreadyExistsException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -15,6 +17,7 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -24,7 +27,7 @@ public class AlreadyExistsException extends QueryValidationException private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; private final String keyspace; private final String table; @@ -32,17 +35,17 @@ public AlreadyExistsException(String keyspace, String table) { this(null, keyspace, table); } - public AlreadyExistsException(InetSocketAddress address, String keyspace, String table) { + public AlreadyExistsException(EndPoint endPoint, String keyspace, String table) { super(makeMsg(keyspace, table)); - this.address = address; + this.endPoint = endPoint; this.keyspace = keyspace; this.table = table; } private AlreadyExistsException( - InetSocketAddress address, String msg, Throwable cause, String keyspace, String table) { + EndPoint endPoint, String msg, Throwable cause, String keyspace, String table) { super(msg, cause); - this.address = address; + this.endPoint = endPoint; this.keyspace = keyspace; this.table = table; } @@ -52,16 +55,21 @@ private static String makeMsg(String keyspace, String table) { else return String.format("Table %s.%s already exists", keyspace, table); } - /** {@inheritDoc} */ @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } - /** {@inheritDoc} */ @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } /** @@ -98,7 +106,7 @@ public String getTable() { @Override public DriverException copy() { - return new AlreadyExistsException(getAddress(), getMessage(), this, keyspace, table); + return new AlreadyExistsException(getEndPoint(), getMessage(), this, keyspace, table); } /** @@ -114,11 +122,11 @@ public DriverException copy() { * generally yields a more user-friendly stack trace that the original one. *
* - * @param address The full address of the host that caused this exception to be thrown. + * @param endPoint The full address of the host that caused this exception to be thrown. * @return a copy/clone of this exception, but with the given host address instead of the original * one. */ - public AlreadyExistsException copy(InetSocketAddress address) { - return new AlreadyExistsException(address, getMessage(), this, keyspace, table); + public AlreadyExistsException copy(EndPoint endPoint) { + return new AlreadyExistsException(endPoint, getMessage(), this, keyspace, table); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/AuthenticationException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/AuthenticationException.java index 54b20ab1aaf..5d9747a5ba5 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/AuthenticationException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -15,6 +17,7 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -23,32 +26,43 @@ public class AuthenticationException extends DriverException implements Coordina private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; + + public AuthenticationException(EndPoint endPoint, String message) { + super(String.format("Authentication error on host %s: %s", endPoint, message)); + this.endPoint = endPoint; + } + // Preserve a constructor with InetSocketAddress for backward compatibility, because legacy + // authenticators might use it public AuthenticationException(InetSocketAddress address, String message) { - super(String.format("Authentication error on host %s: %s", address, message)); - this.address = address; + this(new WrappingEndPoint(address), message); } - private AuthenticationException(InetSocketAddress address, String message, Throwable cause) { + private AuthenticationException(EndPoint endPoint, String message, Throwable cause) { super(message, cause); - this.address = address; + this.endPoint = endPoint; } - /** {@inheritDoc} */ @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } - /** {@inheritDoc} */ @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } @Override public DriverException copy() { - return new AuthenticationException(address, getMessage(), this); + return new AuthenticationException(endPoint, getMessage(), this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/BootstrappingException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/BootstrappingException.java index 4f2bbf3adfa..4f6663a2816 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/BootstrappingException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -15,6 +17,7 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -24,34 +27,38 @@ public class BootstrappingException extends QueryExecutionException private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; - public BootstrappingException(InetSocketAddress address, String message) { - super(String.format("Queried host (%s) was bootstrapping: %s", address, message)); - this.address = address; + public BootstrappingException(EndPoint endPoint, String message) { + super(String.format("Queried host (%s) was bootstrapping: %s", endPoint, message)); + this.endPoint = endPoint; } /** Private constructor used solely when copying exceptions. */ - private BootstrappingException( - InetSocketAddress address, String message, BootstrappingException cause) { + private BootstrappingException(EndPoint endPoint, String message, BootstrappingException cause) { super(message, cause); - this.address = address; + this.endPoint = endPoint; } - /** {@inheritDoc} */ @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } - /** {@inheritDoc} */ @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } @Override public BootstrappingException copy() { - return new BootstrappingException(address, getMessage(), this); + return new BootstrappingException(endPoint, getMessage(), this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/BusyConnectionException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/BusyConnectionException.java index eae24a386d1..d5b51c9abac 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/BusyConnectionException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -15,6 +17,7 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -23,30 +26,37 @@ public class BusyConnectionException extends DriverException implements Coordina private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; - public BusyConnectionException(InetSocketAddress address) { - super(String.format("[%s] Connection has run out of stream IDs", address.getAddress())); - this.address = address; + public BusyConnectionException(EndPoint endPoint) { + super(String.format("[%s] Connection has run out of stream IDs", endPoint)); + this.endPoint = endPoint; } - public BusyConnectionException(InetSocketAddress address, Throwable cause) { - super(String.format("[%s] Connection has run out of stream IDs", address.getAddress()), cause); - this.address = address; + public BusyConnectionException(EndPoint endPoint, Throwable cause) { + super(String.format("[%s] Connection has run out of stream IDs", endPoint), cause); + this.endPoint = endPoint; } @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } @Override public BusyConnectionException copy() { - return new BusyConnectionException(address, this); + return new BusyConnectionException(endPoint, this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/BusyPoolException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/BusyPoolException.java index 52586ab194d..e98f7f75da4 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/BusyPoolException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/BusyPoolException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import com.datastax.driver.core.HostDistance; import com.datastax.driver.core.Statement; import java.net.InetAddress; @@ -47,45 +50,52 @@ public class BusyPoolException extends DriverException implements CoordinatorExc private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; - public BusyPoolException(InetSocketAddress address, int queueSize) { - this(address, buildMessage(address, queueSize), null); + public BusyPoolException(EndPoint endPoint, int queueSize) { + this(endPoint, buildMessage(endPoint, queueSize), null); } - public BusyPoolException(InetSocketAddress address, long timeout, TimeUnit unit) { - this(address, buildMessage(address, timeout, unit), null); + public BusyPoolException(EndPoint endPoint, long timeout, TimeUnit unit) { + this(endPoint, buildMessage(endPoint, timeout, unit), null); } - private BusyPoolException(InetSocketAddress address, String message, Throwable cause) { + private BusyPoolException(EndPoint endPoint, String message, Throwable cause) { super(message, cause); - this.address = address; + this.endPoint = endPoint; } - private static String buildMessage(InetSocketAddress address, int queueSize) { + private static String buildMessage(EndPoint endPoint, int queueSize) { return String.format( "[%s] Pool is busy (no available connection and the queue has reached its max size %d)", - address.getAddress(), queueSize); + endPoint, queueSize); } - private static String buildMessage(InetSocketAddress address, long timeout, TimeUnit unit) { + private static String buildMessage(EndPoint endPoint, long timeout, TimeUnit unit) { return String.format( "[%s] Pool is busy (no available connection and timed out after %d %s)", - address.getAddress(), timeout, unit); + endPoint, timeout, unit); } @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } @Override public BusyPoolException copy() { - return new BusyPoolException(address, getMessage(), this); + return new BusyPoolException(endPoint, getMessage(), this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/CASWriteUnknownException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/CASWriteUnknownException.java new file mode 100644 index 00000000000..07261fd6fce --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/CASWriteUnknownException.java @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core.exceptions; + +import com.datastax.driver.core.ConsistencyLevel; +import com.datastax.driver.core.EndPoint; + +public class CASWriteUnknownException extends QueryConsistencyException { + + private static final long serialVersionUID = 0; + + /** + * This constructor should only be used internally by the driver when decoding error responses. + */ + public CASWriteUnknownException(ConsistencyLevel consistency, int received, int required) { + this(null, consistency, received, required); + } + + public CASWriteUnknownException( + EndPoint endPoint, ConsistencyLevel consistency, int received, int required) { + super( + endPoint, + String.format( + "CAS operation result is unknown - proposal was not accepted by a quorum. (%d / %d)", + received, required), + consistency, + received, + required); + } + + private CASWriteUnknownException( + EndPoint endPoint, + String msg, + Throwable cause, + ConsistencyLevel consistency, + int received, + int required) { + super(endPoint, msg, cause, consistency, received, required); + } + + @Override + public CASWriteUnknownException copy() { + return new CASWriteUnknownException( + getEndPoint(), + getMessage(), + this, + getConsistencyLevel(), + getReceivedAcknowledgements(), + getRequiredAcknowledgements()); + } + + /** + * Create a copy of this exception with a nicer stack trace, and including the coordinator address + * that caused this exception to be raised. + * + *

This method is mainly intended for internal use by the driver and exists mainly because: + * + *

    + *
  1. the original exception was decoded from a response frame and at that time, the + * coordinator address was not available; and + *
  2. the newly-created exception will refer to the current thread in its stack trace, which + * generally yields a more user-friendly stack trace that the original one. + *
+ * + * @param endPoint The full address of the host that caused this exception to be thrown. + * @return a copy/clone of this exception, but with the given host address instead of the original + * one. + */ + public CASWriteUnknownException copy(EndPoint endPoint) { + return new CASWriteUnknownException( + endPoint, + getMessage(), + this, + getConsistencyLevel(), + getReceivedAcknowledgements(), + getRequiredAcknowledgements()); + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/CDCWriteException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/CDCWriteException.java new file mode 100644 index 00000000000..93170eb733e --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/CDCWriteException.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.driver.core.exceptions; + +import com.datastax.driver.core.EndPoint; +import java.net.InetAddress; +import java.net.InetSocketAddress; + +/** An error occurred when trying to write a CDC mutation to the commitlog * */ +public class CDCWriteException extends QueryExecutionException implements CoordinatorException { + + private static final long serialVersionUID = 0; + + private final EndPoint endPoint; + + public CDCWriteException(EndPoint endPoint, String message) { + super(message); + this.endPoint = endPoint; + } + + /** Private constructor used solely when copying exceptions. */ + private CDCWriteException(EndPoint endPoint, String message, CDCWriteException cause) { + super(message, cause); + this.endPoint = endPoint; + } + + @Override + public EndPoint getEndPoint() { + return endPoint; + } + + @Override + @Deprecated + public InetSocketAddress getAddress() { + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); + } + + @Override + public CDCWriteException copy() { + return new CDCWriteException(endPoint, getMessage(), this); + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/CodecNotFoundException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/CodecNotFoundException.java index 73fb3745257..93e4fd07bcc 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/CodecNotFoundException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/ConnectionException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/ConnectionException.java index 5e4e0eb4f3f..4fc36b830cf 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/ConnectionException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/ConnectionException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -23,36 +26,43 @@ public class ConnectionException extends DriverException implements CoordinatorE private static final long serialVersionUID = 0; - public final InetSocketAddress address; + private final EndPoint endPoint; - public ConnectionException(InetSocketAddress address, String msg, Throwable cause) { + public ConnectionException(EndPoint endPoint, String msg, Throwable cause) { super(msg, cause); - this.address = address; + this.endPoint = endPoint; } - public ConnectionException(InetSocketAddress address, String msg) { + public ConnectionException(EndPoint endPoint, String msg) { super(msg); - this.address = address; + this.endPoint = endPoint; } @Override - public InetAddress getHost() { - return address == null ? null : address.getAddress(); + public EndPoint getEndPoint() { + return endPoint; } @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } @Override public String getMessage() { - return address == null ? getRawMessage() : String.format("[%s] %s", address, getRawMessage()); + return endPoint == null ? getRawMessage() : String.format("[%s] %s", endPoint, getRawMessage()); } @Override public ConnectionException copy() { - return new ConnectionException(address, getRawMessage(), this); + return new ConnectionException(endPoint, getRawMessage(), this); } String getRawMessage() { diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/CoordinatorException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/CoordinatorException.java index c866dda9804..ce2474999a9 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/CoordinatorException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -15,6 +17,7 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -25,20 +28,29 @@ public interface CoordinatorException { /** - * The coordinator host that was contacted. - * - *

This is a shortcut for {@link InetSocketAddress#getAddress() getAddress().getAddress()}. + * The connection information of the coordinator host that was contacted. May be {@code null} if + * the coordinator is not known. + */ + EndPoint getEndPoint(); + + /** + * The coordinator host that was contacted; may be {@code null} if the coordinator is not known. * - * @return The coordinator host that was contacted; may be {@code null} if the coordinator is not - * known. + * @deprecated {@link #getEndPoint()} provides more accurate information if the connection + * information consists of more than a socket address. This method is a shortcut for {@code + * getEndPoint().resolve().getAddress()}. */ + @Deprecated InetAddress getHost(); /** - * The full address of the coordinator host that was contacted. + * The full address of the coordinator host that was contacted; may be {@code null} if the + * coordinator is not known. * - * @return the full address of the coordinator host that was contacted; may be {@code null} if the - * coordinator is not known. + * @deprecated {@link #getEndPoint()} provides more accurate information if the connection + * information consists of more than a socket address. This method is a shortcut for {@code + * getEndPoint().resolve()}. */ + @Deprecated InetSocketAddress getAddress(); } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/CrcMismatchException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/CrcMismatchException.java new file mode 100644 index 00000000000..22ccf21db60 --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/CrcMismatchException.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.driver.core.exceptions; + +/** + * Thrown when the checksums in a server response don't match (protocol v5 or above). + * + *

This indicates a data corruption issue, either due to a hardware issue on the client, or on + * the network between the server and the client. It is not recoverable: the driver will drop the + * connection. + */ +public class CrcMismatchException extends DriverException { + + private static final long serialVersionUID = 0; + + public CrcMismatchException(String message) { + super(message); + } + + public CrcMismatchException(String message, Throwable cause) { + super(message, cause); + } + + @Override + public CrcMismatchException copy() { + return new CrcMismatchException(getMessage(), this); + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverException.java index f8ed67b5931..1e806a57cc9 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverInternalError.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverInternalError.java index 68a4c6f9801..d408c968490 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverInternalError.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverInternalError.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/FrameTooLongException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/FrameTooLongException.java index af8fae0dd15..9d15ee8aa6e 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/FrameTooLongException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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/driver-core/src/main/java/com/datastax/driver/core/exceptions/FunctionExecutionException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/FunctionExecutionException.java index 89dc194d0cb..81f2b62fe23 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/FunctionExecutionException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/FunctionExecutionException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -24,32 +27,37 @@ public class FunctionExecutionException extends QueryExecutionException private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; - public FunctionExecutionException(InetSocketAddress address, String msg) { + public FunctionExecutionException(EndPoint endPoint, String msg) { super(msg); - this.address = address; + this.endPoint = endPoint; } - private FunctionExecutionException(InetSocketAddress address, String msg, Throwable cause) { + private FunctionExecutionException(EndPoint endPoint, String msg, Throwable cause) { super(msg, cause); - this.address = address; + this.endPoint = endPoint; } - /** {@inheritDoc} */ @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } - /** {@inheritDoc} */ @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } @Override public DriverException copy() { - return new FunctionExecutionException(address, getMessage(), this); + return new FunctionExecutionException(endPoint, getMessage(), this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidConfigurationInQueryException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidConfigurationInQueryException.java index 399dafce313..4bdb1b604e8 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidConfigurationInQueryException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -15,7 +17,7 @@ */ package com.datastax.driver.core.exceptions; -import java.net.InetSocketAddress; +import com.datastax.driver.core.EndPoint; /** * A specific invalid query exception that indicates that the query is invalid because of some @@ -29,12 +31,12 @@ public class InvalidConfigurationInQueryException extends InvalidQueryException private static final long serialVersionUID = 0; - public InvalidConfigurationInQueryException(InetSocketAddress address, String msg) { - super(address, msg); + public InvalidConfigurationInQueryException(EndPoint endPoint, String msg) { + super(endPoint, msg); } @Override public InvalidConfigurationInQueryException copy() { - return new InvalidConfigurationInQueryException(getAddress(), getMessage()); + return new InvalidConfigurationInQueryException(getEndPoint(), getMessage()); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidQueryException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidQueryException.java index cbdff9281ed..5bdc6451350 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidQueryException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -15,6 +17,7 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -24,38 +27,45 @@ public class InvalidQueryException extends QueryValidationException private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; public InvalidQueryException(String msg) { this(null, msg); } - public InvalidQueryException(InetSocketAddress address, String msg) { + public InvalidQueryException(EndPoint endPoint, String msg) { super(msg); - this.address = address; + this.endPoint = endPoint; } public InvalidQueryException(String msg, Throwable cause) { this(null, msg, cause); } - public InvalidQueryException(InetSocketAddress address, String msg, Throwable cause) { + public InvalidQueryException(EndPoint endPoint, String msg, Throwable cause) { super(msg, cause); - this.address = address; + this.endPoint = endPoint; } @Override public DriverException copy() { - return new InvalidQueryException(getAddress(), getMessage(), this); + return new InvalidQueryException(getEndPoint(), getMessage(), this); } @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidTypeException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidTypeException.java index 4e3f6baec07..e6829dcfd78 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidTypeException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidTypeException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/NoHostAvailableException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/NoHostAvailableException.java index cc00e5b3ecf..06c20f88d77 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/NoHostAvailableException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/NoHostAvailableException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,9 +17,9 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.io.PrintWriter; import java.io.StringWriter; -import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; @@ -40,15 +42,15 @@ public class NoHostAvailableException extends DriverException { private static final int MAX_ERRORS_IN_DEFAULT_MESSAGE = 3; - private final Map errors; + private final Map errors; - public NoHostAvailableException(Map errors) { + public NoHostAvailableException(Map errors) { super(makeMessage(errors, MAX_ERRORS_IN_DEFAULT_MESSAGE, false, false)); this.errors = errors; } private NoHostAvailableException( - String message, Throwable cause, Map errors) { + String message, Throwable cause, Map errors) { super(message, cause); this.errors = errors; } @@ -58,8 +60,8 @@ private NoHostAvailableException( * * @return a map containing for each tried host the error triggered when trying it. */ - public Map getErrors() { - return new HashMap(errors); + public Map getErrors() { + return new HashMap(errors); } /** @@ -84,7 +86,7 @@ public NoHostAvailableException copy() { } private static String makeMessage( - Map errors, + Map errors, int maxErrorsInMessage, boolean formatted, boolean includeStackTraces) { @@ -98,7 +100,7 @@ private static String makeMessage( int n = 0; boolean truncated = false; - for (Map.Entry entry : errors.entrySet()) { + for (Map.Entry entry : errors.entrySet()) { if (n > 0) out.print(formatted ? "\n" : ", "); out.print(entry.getKey()); if (n < maxErrorsInMessage) { diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/OperationTimedOutException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/OperationTimedOutException.java index 21b9ae4f457..4c7b8b93923 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/OperationTimedOutException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/OperationTimedOutException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,8 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import com.datastax.driver.core.SocketOptions; -import java.net.InetSocketAddress; /** * Thrown on a client-side timeout, i.e. when the client didn't hear back from the server within @@ -26,20 +28,20 @@ public class OperationTimedOutException extends ConnectionException { private static final long serialVersionUID = 0; - public OperationTimedOutException(InetSocketAddress address) { - super(address, "Operation timed out"); + public OperationTimedOutException(EndPoint endPoint) { + super(endPoint, "Operation timed out"); } - public OperationTimedOutException(InetSocketAddress address, String msg) { - super(address, msg); + public OperationTimedOutException(EndPoint endPoint, String msg) { + super(endPoint, msg); } - public OperationTimedOutException(InetSocketAddress address, String msg, Throwable cause) { - super(address, msg, cause); + public OperationTimedOutException(EndPoint endPoint, String msg, Throwable cause) { + super(endPoint, msg, cause); } @Override public OperationTimedOutException copy() { - return new OperationTimedOutException(address, getRawMessage(), this); + return new OperationTimedOutException(getEndPoint(), getRawMessage(), this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/OverloadedException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/OverloadedException.java index c5d5ca28f84..42bc0fbb79d 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/OverloadedException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -15,6 +17,7 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -23,34 +26,38 @@ public class OverloadedException extends QueryExecutionException implements Coor private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; - public OverloadedException(InetSocketAddress address, String message) { - super(String.format("Queried host (%s) was overloaded: %s", address, message)); - this.address = address; + public OverloadedException(EndPoint endPoint, String message) { + super(String.format("Queried host (%s) was overloaded: %s", endPoint, message)); + this.endPoint = endPoint; } /** Private constructor used solely when copying exceptions. */ - private OverloadedException( - InetSocketAddress address, String message, OverloadedException cause) { + private OverloadedException(EndPoint endPoint, String message, OverloadedException cause) { super(message, cause); - this.address = address; + this.endPoint = endPoint; } - /** {@inheritDoc} */ @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } - /** {@inheritDoc} */ @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } @Override public OverloadedException copy() { - return new OverloadedException(address, getMessage(), this); + return new OverloadedException(endPoint, getMessage(), this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/PagingStateException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/PagingStateException.java index 0f1fe9c25f1..0e05f0d9b43 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/PagingStateException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/PagingStateException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/ProtocolError.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/ProtocolError.java index 6a098ab953f..6628fb0fb90 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/ProtocolError.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -15,6 +17,7 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -27,36 +30,41 @@ public class ProtocolError extends DriverInternalError implements CoordinatorExc private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; - public ProtocolError(InetSocketAddress address, String message) { + public ProtocolError(EndPoint endPoint, String message) { super( String.format( "An unexpected protocol error occurred on host %s. This is a bug in this library, please report: %s", - address, message)); - this.address = address; + endPoint, message)); + this.endPoint = endPoint; } /** Private constructor used solely when copying exceptions. */ - private ProtocolError(InetSocketAddress address, String message, ProtocolError cause) { + private ProtocolError(EndPoint endPoint, String message, ProtocolError cause) { super(message, cause); - this.address = address; + this.endPoint = endPoint; } - /** {@inheritDoc} */ @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } - /** {@inheritDoc} */ @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } @Override public ProtocolError copy() { - return new ProtocolError(address, getMessage(), this); + return new ProtocolError(endPoint, getMessage(), this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryConsistencyException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryConsistencyException.java index 3686cce1397..e82306270e3 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryConsistencyException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -16,6 +18,7 @@ package com.datastax.driver.core.exceptions; import com.datastax.driver.core.ConsistencyLevel; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -37,33 +40,29 @@ public abstract class QueryConsistencyException extends QueryExecutionException implements CoordinatorException { - private final InetSocketAddress address; + private final EndPoint endPoint; private final ConsistencyLevel consistency; private final int received; private final int required; protected QueryConsistencyException( - InetSocketAddress address, - String msg, - ConsistencyLevel consistency, - int received, - int required) { + EndPoint endPoint, String msg, ConsistencyLevel consistency, int received, int required) { super(msg); - this.address = address; + this.endPoint = endPoint; this.consistency = consistency; this.received = received; this.required = required; } protected QueryConsistencyException( - InetSocketAddress address, + EndPoint endPoint, String msg, Throwable cause, ConsistencyLevel consistency, int received, int required) { super(msg, cause); - this.address = address; + this.endPoint = endPoint; this.consistency = consistency; this.received = received; this.required = required; @@ -99,26 +98,25 @@ public int getRequiredAcknowledgements() { } /** - * The coordinator host that caused this exception to be thrown. Note that this is the query - * coordinator host, not the host which timed out. + * {@inheritDoc} * - * @return The coordinator host that caused this exception to be thrown, or {@code null} if this - * exception has been generated driver-side. + *

Note that this is the information of the host that coordinated the query, not the + * one that timed out. */ @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } - /** - * The full address of the coordinator host that caused this exception to be thrown. Note that - * this is the query coordinator host, not the host which timed out. - * - * @return the full address of the coordinator host that caused this exception to be thrown, or - * {@code null} if this exception has been generated driver-side. - */ @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryExecutionException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryExecutionException.java index 7a343c1b4a8..67b8a2747a7 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryExecutionException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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/driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryValidationException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryValidationException.java index d6c23cf787f..68707128814 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryValidationException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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/driver-core/src/main/java/com/datastax/driver/core/exceptions/ReadFailureException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/ReadFailureException.java index 580b8708adb..b1e76b1e739 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/ReadFailureException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -16,8 +18,8 @@ package com.datastax.driver.core.exceptions; import com.datastax.driver.core.ConsistencyLevel; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; -import java.net.InetSocketAddress; import java.util.Collections; import java.util.Map; @@ -62,7 +64,7 @@ public ReadFailureException( } public ReadFailureException( - InetSocketAddress address, + EndPoint endPoint, ConsistencyLevel consistency, int received, int required, @@ -70,7 +72,7 @@ public ReadFailureException( Map failuresMap, boolean dataPresent) { super( - address, + endPoint, String.format( "Cassandra failure during read query at consistency %s " + "(%d responses were required but only %d replica responded, %d failed)", @@ -86,14 +88,14 @@ public ReadFailureException( /** @deprecated Legacy constructor for backward compatibility. */ @Deprecated public ReadFailureException( - InetSocketAddress address, + EndPoint endPoint, ConsistencyLevel consistency, int received, int required, int failed, boolean dataPresent) { this( - address, + endPoint, consistency, received, required, @@ -103,7 +105,7 @@ public ReadFailureException( } private ReadFailureException( - InetSocketAddress address, + EndPoint endPoint, String msg, Throwable cause, ConsistencyLevel consistency, @@ -112,7 +114,7 @@ private ReadFailureException( int failed, Map failuresMap, boolean dataPresent) { - super(address, msg, cause, consistency, received, required); + super(endPoint, msg, cause, consistency, received, required); this.failed = failed; this.failuresMap = failuresMap; this.dataPresent = dataPresent; @@ -169,7 +171,7 @@ public boolean wasDataRetrieved() { @Override public ReadFailureException copy() { return new ReadFailureException( - getAddress(), + getEndPoint(), getMessage(), this, getConsistencyLevel(), @@ -180,9 +182,9 @@ public ReadFailureException copy() { wasDataRetrieved()); } - public ReadFailureException copy(InetSocketAddress address) { + public ReadFailureException copy(EndPoint endPoint) { return new ReadFailureException( - address, + endPoint, getMessage(), this, getConsistencyLevel(), diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/ReadTimeoutException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/ReadTimeoutException.java index eb8cbf26553..c9803ccd43f 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/ReadTimeoutException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -16,7 +18,7 @@ package com.datastax.driver.core.exceptions; import com.datastax.driver.core.ConsistencyLevel; -import java.net.InetSocketAddress; +import com.datastax.driver.core.EndPoint; /** A Cassandra timeout during a read query. */ public class ReadTimeoutException extends QueryConsistencyException { @@ -34,15 +36,16 @@ public ReadTimeoutException( } public ReadTimeoutException( - InetSocketAddress address, + EndPoint endPoint, ConsistencyLevel consistency, int received, int required, boolean dataPresent) { super( - address, + endPoint, 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.", consistency, formatDetails(received, required, dataPresent)), consistency, received, @@ -51,14 +54,14 @@ consistency, formatDetails(received, required, dataPresent)), } private ReadTimeoutException( - InetSocketAddress address, + EndPoint endPoint, String msg, Throwable cause, ConsistencyLevel consistency, int received, int required, boolean dataPresent) { - super(address, msg, cause, consistency, received, required); + super(endPoint, msg, cause, consistency, received, required); this.dataPresent = dataPresent; } @@ -87,7 +90,7 @@ public boolean wasDataRetrieved() { @Override public ReadTimeoutException copy() { return new ReadTimeoutException( - getAddress(), + getEndPoint(), getMessage(), this, getConsistencyLevel(), @@ -109,13 +112,13 @@ public ReadTimeoutException copy() { * generally yields a more user-friendly stack trace that the original one. * * - * @param address The full address of the host that caused this exception to be thrown. + * @param endPoint The full address of the host that caused this exception to be thrown. * @return a copy/clone of this exception, but with the given host address instead of the original * one. */ - public ReadTimeoutException copy(InetSocketAddress address) { + public ReadTimeoutException copy(EndPoint endPoint) { return new ReadTimeoutException( - address, + endPoint, getMessage(), this, getConsistencyLevel(), diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/ServerError.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/ServerError.java index 24f040cce76..f616cb74d11 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/ServerError.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -15,6 +17,7 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -26,33 +29,38 @@ public class ServerError extends DriverInternalError implements CoordinatorExcep private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; - public ServerError(InetSocketAddress address, String message) { - super(String.format("An unexpected error occurred server side on %s: %s", address, message)); - this.address = address; + public ServerError(EndPoint endPoint, String message) { + super(String.format("An unexpected error occurred server side on %s: %s", endPoint, message)); + this.endPoint = endPoint; } /** Private constructor used solely when copying exceptions. */ - private ServerError(InetSocketAddress address, String message, ServerError cause) { + private ServerError(EndPoint endPoint, String message, ServerError cause) { super(message, cause); - this.address = address; + this.endPoint = endPoint; } - /** {@inheritDoc} */ @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } - /** {@inheritDoc} */ @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } @Override public ServerError copy() { - return new ServerError(address, getMessage(), this); + return new ServerError(endPoint, getMessage(), this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/SyntaxError.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/SyntaxError.java index 1e2c38140c4..f9c6d1272e7 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/SyntaxError.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -15,6 +17,7 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -23,32 +26,37 @@ public class SyntaxError extends QueryValidationException implements Coordinator private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; - public SyntaxError(InetSocketAddress address, String msg) { + public SyntaxError(EndPoint endPoint, String msg) { super(msg); - this.address = address; + this.endPoint = endPoint; } - private SyntaxError(InetSocketAddress address, String msg, Throwable cause) { + private SyntaxError(EndPoint endPoint, String msg, Throwable cause) { super(msg, cause); - this.address = address; + this.endPoint = endPoint; } - /** {@inheritDoc} */ @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } - /** {@inheritDoc} */ @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } @Override public SyntaxError copy() { - return new SyntaxError(getAddress(), getMessage(), this); + return new SyntaxError(getEndPoint(), getMessage(), this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/TraceRetrievalException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/TraceRetrievalException.java index 21295474663..10b77d8fc60 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/TraceRetrievalException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/TraceRetrievalException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/TransportException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/TransportException.java index a227745ffb6..dab3868e76e 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/TransportException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/TransportException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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.driver.core.exceptions; -import java.net.InetSocketAddress; +import com.datastax.driver.core.EndPoint; /** * A connection exception that has to do with the transport itself, i.e. that suggests the node is @@ -25,16 +27,16 @@ public class TransportException extends ConnectionException { private static final long serialVersionUID = 0; - public TransportException(InetSocketAddress address, String msg, Throwable cause) { - super(address, msg, cause); + public TransportException(EndPoint endPoint, String msg, Throwable cause) { + super(endPoint, msg, cause); } - public TransportException(InetSocketAddress address, String msg) { - super(address, msg); + public TransportException(EndPoint endPoint, String msg) { + super(endPoint, msg); } @Override public TransportException copy() { - return new TransportException(address, getRawMessage(), this); + return new TransportException(getEndPoint(), getRawMessage(), this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/TruncateException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/TruncateException.java index 604cfe17910..76b412df87e 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/TruncateException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -15,6 +17,7 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -23,32 +26,37 @@ public class TruncateException extends QueryExecutionException implements Coordi private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; - public TruncateException(InetSocketAddress address, String msg) { + public TruncateException(EndPoint endPoint, String msg) { super(msg); - this.address = address; + this.endPoint = endPoint; } - private TruncateException(InetSocketAddress address, String msg, Throwable cause) { + private TruncateException(EndPoint endPoint, String msg, Throwable cause) { super(msg, cause); - this.address = address; + this.endPoint = endPoint; } - /** {@inheritDoc} */ @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } - /** {@inheritDoc} */ @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } @Override public TruncateException copy() { - return new TruncateException(getAddress(), getMessage(), this); + return new TruncateException(getEndPoint(), getMessage(), this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnauthorizedException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnauthorizedException.java index 64a6f1cfb2a..e967d260c96 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnauthorizedException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -15,6 +17,7 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -27,32 +30,37 @@ public class UnauthorizedException extends QueryValidationException private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; - public UnauthorizedException(InetSocketAddress address, String msg) { + public UnauthorizedException(EndPoint endPoint, String msg) { super(msg); - this.address = address; + this.endPoint = endPoint; } - private UnauthorizedException(InetSocketAddress address, String msg, Throwable cause) { + private UnauthorizedException(EndPoint endPoint, String msg, Throwable cause) { super(msg, cause); - this.address = address; + this.endPoint = endPoint; } - /** {@inheritDoc} */ @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } - /** {@inheritDoc} */ @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } @Override public UnauthorizedException copy() { - return new UnauthorizedException(getAddress(), getMessage(), this); + return new UnauthorizedException(getEndPoint(), getMessage(), this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnavailableException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnavailableException.java index 7c2b72fe942..6b5c78b85a3 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnavailableException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -16,6 +18,7 @@ package com.datastax.driver.core.exceptions; import com.datastax.driver.core.ConsistencyLevel; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -27,7 +30,7 @@ public class UnavailableException extends QueryExecutionException implements Coo private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; private final ConsistencyLevel consistency; private final int required; private final int alive; @@ -40,26 +43,26 @@ public UnavailableException(ConsistencyLevel consistency, int required, int aliv } public UnavailableException( - InetSocketAddress address, ConsistencyLevel consistency, int required, int alive) { + EndPoint endPoint, ConsistencyLevel consistency, int required, int alive) { super( String.format( "Not enough replicas available for query at consistency %s (%d required but only %d alive)", consistency, required, alive)); - this.address = address; + this.endPoint = endPoint; this.consistency = consistency; this.required = required; this.alive = alive; } private UnavailableException( - InetSocketAddress address, + EndPoint endPoint, String message, Throwable cause, ConsistencyLevel consistency, int required, int alive) { super(message, cause); - this.address = address; + this.endPoint = endPoint; this.consistency = consistency; this.required = required; this.alive = alive; @@ -95,21 +98,27 @@ public int getAliveReplicas() { return alive; } - /** {@inheritDoc} */ @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } - /** {@inheritDoc} */ @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } @Override public UnavailableException copy() { - return new UnavailableException(getAddress(), getMessage(), this, consistency, required, alive); + return new UnavailableException( + getEndPoint(), getMessage(), this, consistency, required, alive); } /** @@ -125,11 +134,12 @@ public UnavailableException copy() { * generally yields a more user-friendly stack trace that the original one. * * - * @param address The full address of the host that caused this exception to be thrown. + * @param endPoint The full connection information of the host that caused this exception to be + * thrown. * @return a copy/clone of this exception, but with the given host address instead of the original * one. */ - public UnavailableException copy(InetSocketAddress address) { - return new UnavailableException(address, getMessage(), this, consistency, required, alive); + public UnavailableException copy(EndPoint endPoint) { + return new UnavailableException(endPoint, getMessage(), this, consistency, required, alive); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnpreparedException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnpreparedException.java index 05acbec5c0f..6a951433079 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnpreparedException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnpreparedException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -23,37 +26,41 @@ public class UnpreparedException extends QueryValidationException implements Coo private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; - public UnpreparedException(InetSocketAddress address, String message) { + public UnpreparedException(EndPoint endPoint, String message) { super( String.format( "A prepared query was submitted on %s but was not known of that node: %s", - address, message)); - this.address = address; + endPoint, message)); + this.endPoint = endPoint; } /** Private constructor used solely when copying exceptions. */ - private UnpreparedException( - InetSocketAddress address, String message, UnpreparedException cause) { + private UnpreparedException(EndPoint endPoint, String message, UnpreparedException cause) { super(message, cause); - this.address = address; + this.endPoint = endPoint; } - /** {@inheritDoc} */ @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } - /** {@inheritDoc} */ @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } @Override public UnpreparedException copy() { - return new UnpreparedException(address, getMessage(), this); + return new UnpreparedException(endPoint, getMessage(), this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnresolvedUserTypeException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnresolvedUserTypeException.java index c42a0d81dcd..94ff48a126d 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnresolvedUserTypeException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnresolvedUserTypeException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedFeatureException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedFeatureException.java index 7d4e4d6613b..b45df6ebda9 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedFeatureException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedFeatureException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedProtocolVersionException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedProtocolVersionException.java index 2174c3ff86a..7c6b381bcfe 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedProtocolVersionException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -15,6 +17,7 @@ */ package com.datastax.driver.core.exceptions; +import com.datastax.driver.core.EndPoint; import com.datastax.driver.core.ProtocolVersion; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -28,53 +31,56 @@ public class UnsupportedProtocolVersionException extends DriverException private static final long serialVersionUID = 0; - private final InetSocketAddress address; + private final EndPoint endPoint; private final ProtocolVersion unsupportedVersion; private final ProtocolVersion serverVersion; public UnsupportedProtocolVersionException( - InetSocketAddress address, - ProtocolVersion unsupportedVersion, - ProtocolVersion serverVersion) { - super(makeErrorMessage(address, unsupportedVersion, serverVersion)); - this.address = address; + EndPoint endPoint, ProtocolVersion unsupportedVersion, ProtocolVersion serverVersion) { + super(makeErrorMessage(endPoint, unsupportedVersion, serverVersion)); + this.endPoint = endPoint; this.unsupportedVersion = unsupportedVersion; this.serverVersion = serverVersion; } public UnsupportedProtocolVersionException( - InetSocketAddress address, + EndPoint endPoint, ProtocolVersion unsupportedVersion, ProtocolVersion serverVersion, Throwable cause) { - super(makeErrorMessage(address, unsupportedVersion, serverVersion), cause); - this.address = address; + super(makeErrorMessage(endPoint, unsupportedVersion, serverVersion), cause); + this.endPoint = endPoint; this.unsupportedVersion = unsupportedVersion; this.serverVersion = serverVersion; } private static String makeErrorMessage( - InetSocketAddress address, - ProtocolVersion unsupportedVersion, - ProtocolVersion serverVersion) { + EndPoint endPoint, ProtocolVersion unsupportedVersion, ProtocolVersion serverVersion) { return unsupportedVersion == serverVersion ? String.format( - "[%s] Host does not support protocol version %s", address, unsupportedVersion) + "[%s] Host does not support protocol version %s", endPoint, unsupportedVersion) : String.format( "[%s] Host does not support protocol version %s but %s", - address, unsupportedVersion, serverVersion); + endPoint, unsupportedVersion, serverVersion); } @Override - public InetAddress getHost() { - return address != null ? address.getAddress() : null; + public EndPoint getEndPoint() { + return endPoint; } @Override + @Deprecated public InetSocketAddress getAddress() { - return address; + return (endPoint == null) ? null : endPoint.resolve(); + } + + @Override + @Deprecated + public InetAddress getHost() { + return (endPoint == null) ? null : endPoint.resolve().getAddress(); } /** @@ -102,6 +108,6 @@ public ProtocolVersion getUnsupportedVersion() { @Override public UnsupportedProtocolVersionException copy() { return new UnsupportedProtocolVersionException( - address, unsupportedVersion, serverVersion, this); + endPoint, unsupportedVersion, serverVersion, this); } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/WrappingEndPoint.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/WrappingEndPoint.java new file mode 100644 index 00000000000..5572788311f --- /dev/null +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/WrappingEndPoint.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.driver.core.exceptions; + +import com.datastax.driver.core.EndPoint; +import java.net.InetSocketAddress; + +// The sole purpose of this class is to allow some exception types to preserve a constructor that +// takes an InetSocketAddress (for backward compatibility). +class WrappingEndPoint implements EndPoint { + private final InetSocketAddress address; + + WrappingEndPoint(InetSocketAddress address) { + this.address = address; + } + + @Override + public InetSocketAddress resolve() { + return address; + } +} diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteFailureException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteFailureException.java index 37a5e809ba0..a66c25fa59a 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteFailureException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -16,9 +18,9 @@ package com.datastax.driver.core.exceptions; import com.datastax.driver.core.ConsistencyLevel; +import com.datastax.driver.core.EndPoint; import com.datastax.driver.core.WriteType; import java.net.InetAddress; -import java.net.InetSocketAddress; import java.util.Collections; import java.util.Map; @@ -62,7 +64,7 @@ public WriteFailureException( } public WriteFailureException( - InetSocketAddress address, + EndPoint endPoint, ConsistencyLevel consistency, WriteType writeType, int received, @@ -70,7 +72,7 @@ public WriteFailureException( int failed, Map failuresMap) { super( - address, + endPoint, String.format( "Cassandra failure during write query at consistency %s " + "(%d responses were required but only %d replica responded, %d failed)", @@ -86,14 +88,14 @@ public WriteFailureException( /** @deprecated Legacy constructor for backward compatibility. */ @Deprecated public WriteFailureException( - InetSocketAddress address, + EndPoint endPoint, ConsistencyLevel consistency, WriteType writeType, int received, int required, int failed) { this( - address, + endPoint, consistency, writeType, received, @@ -103,7 +105,7 @@ public WriteFailureException( } private WriteFailureException( - InetSocketAddress address, + EndPoint endPoint, String msg, Throwable cause, ConsistencyLevel consistency, @@ -112,7 +114,7 @@ private WriteFailureException( int required, int failed, Map failuresMap) { - super(address, msg, cause, consistency, received, required); + super(endPoint, msg, cause, consistency, received, required); this.writeType = writeType; this.failed = failed; this.failuresMap = failuresMap; @@ -164,7 +166,7 @@ public Map getFailuresMap() { @Override public WriteFailureException copy() { return new WriteFailureException( - getAddress(), + getEndPoint(), getMessage(), this, getConsistencyLevel(), @@ -175,9 +177,9 @@ public WriteFailureException copy() { failuresMap); } - public WriteFailureException copy(InetSocketAddress address) { + public WriteFailureException copy(EndPoint endPoint) { return new WriteFailureException( - address, + endPoint, getMessage(), this, getConsistencyLevel(), diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteTimeoutException.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteTimeoutException.java index 3188a5ddb91..b72c7a93a7e 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteTimeoutException.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -16,8 +18,8 @@ package com.datastax.driver.core.exceptions; import com.datastax.driver.core.ConsistencyLevel; +import com.datastax.driver.core.EndPoint; import com.datastax.driver.core.WriteType; -import java.net.InetSocketAddress; /** A Cassandra timeout during a write query. */ public class WriteTimeoutException extends QueryConsistencyException { @@ -35,13 +37,13 @@ public WriteTimeoutException( } public WriteTimeoutException( - InetSocketAddress address, + EndPoint endPoint, ConsistencyLevel consistency, WriteType writeType, int received, int required) { super( - address, + endPoint, String.format( "Cassandra timeout during %s write query at consistency %s " + "(%d replica were required but only %d acknowledged the write)", @@ -53,14 +55,14 @@ public WriteTimeoutException( } private WriteTimeoutException( - InetSocketAddress address, + EndPoint endPoint, String msg, Throwable cause, ConsistencyLevel consistency, WriteType writeType, int received, int required) { - super(address, msg, cause, consistency, received, required); + super(endPoint, msg, cause, consistency, received, required); this.writeType = writeType; } @@ -76,7 +78,7 @@ public WriteType getWriteType() { @Override public WriteTimeoutException copy() { return new WriteTimeoutException( - getAddress(), + getEndPoint(), getMessage(), this, getConsistencyLevel(), @@ -102,7 +104,7 @@ public WriteTimeoutException copy() { * @return a copy/clone of this exception, but with the given host address instead of the original * one. */ - public WriteTimeoutException copy(InetSocketAddress address) { + public WriteTimeoutException copy(EndPoint address) { return new WriteTimeoutException( address, getMessage(), diff --git a/driver-core/src/main/java/com/datastax/driver/core/exceptions/package-info.java b/driver-core/src/main/java/com/datastax/driver/core/exceptions/package-info.java index e3980a58b57..e4205946ebd 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/exceptions/package-info.java +++ b/driver-core/src/main/java/com/datastax/driver/core/exceptions/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, @@ -13,5 +15,5 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/** Exceptions thrown by the DataStax Java driver for Cassandra. */ +/** Exceptions thrown by the Java Driver for Cassandra. */ package com.datastax.driver.core.exceptions; diff --git a/driver-core/src/main/java/com/datastax/driver/core/package-info.java b/driver-core/src/main/java/com/datastax/driver/core/package-info.java index 995ba870c77..ae82e0e5544 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/package-info.java +++ b/driver-core/src/main/java/com/datastax/driver/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, @@ -14,7 +16,7 @@ * limitations under the License. */ /** - * The main package for the DataStax Java driver for Cassandra. + * The main package for the Java Driver for Cassandra. * *

The main entry for this package is the {@link com.datastax.driver.core.Cluster} class. */ diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/AddressTranslator.java b/driver-core/src/main/java/com/datastax/driver/core/policies/AddressTranslator.java index 87bb59364f4..981b3b5748a 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/AddressTranslator.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/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/driver-core/src/main/java/com/datastax/driver/core/policies/ChainableLoadBalancingPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/ChainableLoadBalancingPolicy.java index 873606ef470..8995d558352 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/ChainableLoadBalancingPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/ChainableLoadBalancingPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/Clock.java b/driver-core/src/main/java/com/datastax/driver/core/policies/Clock.java index a10d37c39ca..00c32dbcc11 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/Clock.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/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, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/ConstantReconnectionPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/ConstantReconnectionPolicy.java index d6c782d0c0c..b5d90f19437 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/ConstantReconnectionPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/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/driver-core/src/main/java/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.java index 93e70a197fc..bcb69f7b4ca 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/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/driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java index 121683f22ed..a05d5087e4b 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -342,7 +344,11 @@ public Builder withLocalDc(String localDc) { * * @param usedHostsPerRemoteDc the number. * @return this builder. + * @deprecated This functionality will be removed in the next major release of the driver. DC + * failover shouldn't be done in the driver, which does not have the necessary context to + * know what makes sense considering application semantics. */ + @Deprecated public Builder withUsedHostsPerRemoteDc(int usedHostsPerRemoteDc) { Preconditions.checkArgument( usedHostsPerRemoteDc >= 0, "usedHostsPerRemoteDc must be equal or greater than 0"); @@ -363,7 +369,11 @@ public Builder withUsedHostsPerRemoteDc(int usedHostsPerRemoteDc) { * you do. * * @return this builder. + * @deprecated This functionality will be removed in the next major release of the driver. DC + * failover shouldn't be done in the driver, which does not have the necessary context to + * know what makes sense considering application semantics. */ + @Deprecated public Builder allowRemoteDCsForLocalConsistencyLevel() { this.allowRemoteDCsForLocalConsistencyLevel = true; return this; diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java index dc8fed4262b..f59f0f67565 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/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, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.java index 27eaf72066c..f0e289331dc 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslator.java b/driver-core/src/main/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslator.java index 4507d4d425e..6d5e865879b 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslator.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/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/driver-core/src/main/java/com/datastax/driver/core/policies/ErrorAwarePolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/ErrorAwarePolicy.java index 7d6992ccfd4..e600a4e4005 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/ErrorAwarePolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/ErrorAwarePolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/ExponentialReconnectionPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/ExponentialReconnectionPolicy.java index 0b4282a98ac..c206c530f56 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/ExponentialReconnectionPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/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/driver-core/src/main/java/com/datastax/driver/core/policies/FallthroughRetryPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/FallthroughRetryPolicy.java index 22c6f030c8c..610283255b0 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/FallthroughRetryPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/FallthroughRetryPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/HostFilterPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/HostFilterPolicy.java index 8bb1a5e6573..4dddb87aef4 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/HostFilterPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/HostFilterPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicy.java index b73e183a150..f1a1009bcb1 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/IdentityTranslator.java b/driver-core/src/main/java/com/datastax/driver/core/policies/IdentityTranslator.java index 9276a855860..03ada4bfae2 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/IdentityTranslator.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/IdentityTranslator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/LatencyAwarePolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/LatencyAwarePolicy.java index e92c9599ab3..b62acf892bc 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/LatencyAwarePolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/LatencyAwarePolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -709,7 +711,7 @@ public Builder withExclusionThreshold(double exclusionThreshold) { * *

{@code d = (t - t') / scale
      * alpha = 1 - (ln(d+1) / d)
-     * avg = alpha * l + (1 - alpha * prev)}
+ * avg = alpha * l + (1 - alpha) * prev} * * Typically, with a {@code scale} of 100 milliseconds (the default), if a new latency is * measured and the previous measure is 10 millisecond old (so {@code d=0.1}), then {@code diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/LoadBalancingPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/LoadBalancingPolicy.java index 27684060ea3..afdba14453a 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/LoadBalancingPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/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, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/LoggingRetryPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/LoggingRetryPolicy.java index 791b2b5da79..ab48733c100 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/LoggingRetryPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/LoggingRetryPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/NoSpeculativeExecutionPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/NoSpeculativeExecutionPolicy.java index 587349545b9..a4a53c2f546 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/NoSpeculativeExecutionPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/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/driver-core/src/main/java/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.java index ecad11826c9..995a6775275 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java b/driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java index 2777e929ca2..0011a85e8a1 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,8 @@ package com.datastax.driver.core.policies; import com.datastax.driver.core.AtomicMonotonicTimestampGenerator; +import com.datastax.driver.core.DefaultEndPointFactory; +import com.datastax.driver.core.EndPointFactory; import com.datastax.driver.core.TimestampGenerator; /** Policies configured for a {@link com.datastax.driver.core.Cluster} instance. */ @@ -43,6 +47,7 @@ public static Builder builder() { private final AddressTranslator addressTranslator; private final TimestampGenerator timestampGenerator; private final SpeculativeExecutionPolicy speculativeExecutionPolicy; + private final EndPointFactory endPointFactory; private Policies( LoadBalancingPolicy loadBalancingPolicy, @@ -50,13 +55,15 @@ private Policies( RetryPolicy retryPolicy, AddressTranslator addressTranslator, TimestampGenerator timestampGenerator, - SpeculativeExecutionPolicy speculativeExecutionPolicy) { + SpeculativeExecutionPolicy speculativeExecutionPolicy, + EndPointFactory endPointFactory) { this.loadBalancingPolicy = loadBalancingPolicy; this.reconnectionPolicy = reconnectionPolicy; this.retryPolicy = retryPolicy; this.addressTranslator = addressTranslator; this.timestampGenerator = timestampGenerator; this.speculativeExecutionPolicy = speculativeExecutionPolicy; + this.endPointFactory = endPointFactory; } /** @@ -134,6 +141,10 @@ public static SpeculativeExecutionPolicy defaultSpeculativeExecutionPolicy() { return DEFAULT_SPECULATIVE_EXECUTION_POLICY; } + public static EndPointFactory defaultEndPointFactory() { + return new DefaultEndPointFactory(); + } + /** * The load balancing policy in use. * @@ -195,6 +206,10 @@ public SpeculativeExecutionPolicy getSpeculativeExecutionPolicy() { return speculativeExecutionPolicy; } + public EndPointFactory getEndPointFactory() { + return endPointFactory; + } + /** A builder to create a new {@code Policies} object. */ public static class Builder { private LoadBalancingPolicy loadBalancingPolicy; @@ -203,6 +218,7 @@ public static class Builder { private AddressTranslator addressTranslator; private TimestampGenerator timestampGenerator; private SpeculativeExecutionPolicy speculativeExecutionPolicy; + private EndPointFactory endPointFactory; /** * Sets the load balancing policy. @@ -271,6 +287,11 @@ public Builder withSpeculativeExecutionPolicy( return this; } + public Builder withEndPointFactory(EndPointFactory endPointFactory) { + this.endPointFactory = endPointFactory; + return this; + } + /** * Builds the final object from this builder. * @@ -287,7 +308,8 @@ public Policies build() { timestampGenerator == null ? defaultTimestampGenerator() : timestampGenerator, speculativeExecutionPolicy == null ? defaultSpeculativeExecutionPolicy() - : speculativeExecutionPolicy); + : speculativeExecutionPolicy, + endPointFactory == null ? defaultEndPointFactory() : endPointFactory); } } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/ReconnectionPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/ReconnectionPolicy.java index d51d687ecca..0cdae499c7a 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/ReconnectionPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/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/driver-core/src/main/java/com/datastax/driver/core/policies/RetryPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/RetryPolicy.java index 8be904d2778..2a51acb30ba 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/RetryPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/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, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/RollingCount.java b/driver-core/src/main/java/com/datastax/driver/core/policies/RollingCount.java index 8f061fa5b92..2f33fcf9273 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/RollingCount.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/RollingCount.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/RoundRobinPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/RoundRobinPolicy.java index 49b24f63e3f..ab7b4a2e3bf 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/RoundRobinPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/RoundRobinPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.java index f1d01d5b273..82aa791693b 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/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/driver-core/src/main/java/com/datastax/driver/core/policies/TokenAwarePolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/TokenAwarePolicy.java index 77c6aeb8571..ccfda1062d7 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/TokenAwarePolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/TokenAwarePolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/WhiteListPolicy.java b/driver-core/src/main/java/com/datastax/driver/core/policies/WhiteListPolicy.java index eace6ae8a64..9ef85186d15 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/WhiteListPolicy.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/WhiteListPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -68,7 +70,10 @@ private static Predicate buildPredicate(Collection whit return new Predicate() { @Override public boolean apply(Host host) { - return hosts.contains(host.getSocketAddress()); + // This policy shouldn't be used with endpoints that don't resolve to unique addresses. This + // should be pretty obvious from the API. We don't really have any way to check it here. + InetSocketAddress socketAddress = host.getEndPoint().resolve(); + return hosts.contains(socketAddress); } }; } @@ -116,7 +121,8 @@ public static WhiteListPolicy ofHosts( new Predicate() { @Override public boolean apply(Host host) { - return addresses.contains(host.getAddress()); + InetSocketAddress socketAddress = host.getEndPoint().resolve(); + return addresses.contains(socketAddress.getAddress()); } }); } diff --git a/driver-core/src/main/java/com/datastax/driver/core/policies/package-info.java b/driver-core/src/main/java/com/datastax/driver/core/policies/package-info.java index 54117d969ec..cd0bd707554 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/policies/package-info.java +++ b/driver-core/src/main/java/com/datastax/driver/core/policies/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, @@ -13,7 +15,5 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/** - * Policies that allow to control some of the behavior of the DataStax Java driver for Cassandra. - */ +/** Policies that allow to control some of the behavior of the Java Driver for Cassandra. */ package com.datastax.driver.core.policies; diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Assignment.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Assignment.java index be35ab6e3e7..fdf31ab384c 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Assignment.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Assignment.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java index 546176f852f..3c89993cb6e 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/BindMarker.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/BindMarker.java index 78719cafda5..e9b6427ec05 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/BindMarker.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/BindMarker.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java index 7a880a70fbf..76e6cb45189 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Clause.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Clause.java index d6a3c1d35f2..1d91a8a7005 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Clause.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Clause.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java index 0ea36f9d435..42e32d9035b 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Delete.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java index 7c0a8978918..57df351f912 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Ordering.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Ordering.java index 52c83184e02..d6fc90f9579 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Ordering.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Ordering.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java index 5e09d0cef9c..1062b66bf94 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java index 73031988854..c92fb3fa6a7 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,9 +17,11 @@ */ package com.datastax.driver.core.querybuilder; +import com.datastax.driver.core.AbstractTableMetadata; import com.datastax.driver.core.CodecRegistry; import com.datastax.driver.core.ColumnMetadata; import com.datastax.driver.core.DataType; +import com.datastax.driver.core.MaterializedViewMetadata; import com.datastax.driver.core.Metadata; import com.datastax.driver.core.TableMetadata; import java.util.ArrayList; @@ -47,7 +51,8 @@ public class Select extends BuiltStatement { this(keyspace, table, null, null, columnNames, isDistinct, isJson); } - Select(TableMetadata table, List columnNames, boolean isDistinct, boolean isJson) { + Select( + AbstractTableMetadata table, List columnNames, boolean isDistinct, boolean isJson) { this( Metadata.quoteIfNecessary(table.getKeyspace().getName()), Metadata.quoteIfNecessary(table.getName()), @@ -469,6 +474,16 @@ public Select from(String keyspace, String table) { public Select from(TableMetadata table) { return new Select(table, columnNames, isDistinct, isJson); } + + /** + * Adds the materialized view to select from. + * + * @param view the materialized view to select from. + * @return a newly built SELECT statement that selects from {@code view}. + */ + public Select from(MaterializedViewMetadata view) { + return new Select(view, columnNames, isDistinct, isJson); + } } /** An Selection clause for an in-construction SELECT statement. */ @@ -857,5 +872,14 @@ public Select from(TableMetadata table) { previousSelection = null; return super.from(table); } + + @Override + public Select from(MaterializedViewMetadata view) { + if (previousSelection != null) { + addName(previousSelection); + } + previousSelection = null; + return super.from(view); + } } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Truncate.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Truncate.java index 57087e97055..0dd49546c04 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Truncate.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Truncate.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java index 9331cba7bd0..7014b4a4a93 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Using.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Using.java index de12ad64d88..77a0d6a552f 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Using.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Using.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java index b1122f437cf..dde2a669654 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/package-info.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/package-info.java index 36a8012a6fe..4bf5951e4e4 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/package-info.java +++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/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/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/AbstractCreateStatement.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/AbstractCreateStatement.java index f47f85a1787..c13d3eaca4d 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/AbstractCreateStatement.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/AbstractCreateStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Alter.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Alter.java index dff2a553b9e..0b77099be4c 100755 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Alter.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Alter.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/AlterKeyspace.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/AlterKeyspace.java index f826c5636d1..0d062a90e98 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/AlterKeyspace.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/AlterKeyspace.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/ColumnType.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/ColumnType.java index 24ee1da7f6d..4531b01bd9b 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/ColumnType.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/ColumnType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Create.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Create.java index b04131a6e09..9fdbbe1a6b6 100755 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Create.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Create.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateIndex.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateIndex.java index 35cd1a1460c..e0fb1d15d44 100755 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateIndex.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateIndex.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateKeyspace.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateKeyspace.java index cbdbb6f07f7..443635815a5 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateKeyspace.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateKeyspace.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateType.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateType.java index 11f846cfba3..9425ccf1109 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateType.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Drop.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Drop.java index a7642ebd472..660e427ad48 100755 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Drop.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Drop.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/DropKeyspace.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/DropKeyspace.java index 6e32c614731..93a6e9f7a64 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/DropKeyspace.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/DropKeyspace.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/KeyspaceOptions.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/KeyspaceOptions.java index c34e77c2060..f0d2d1721b9 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/KeyspaceOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/KeyspaceOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/NativeColumnType.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/NativeColumnType.java index 2d5bf67f0dc..defceef3edc 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/NativeColumnType.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/NativeColumnType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaBuilder.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaBuilder.java index b2f1f61b7ad..d71bcb7e6ec 100755 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaBuilder.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -440,4 +442,30 @@ public static TableOptions.CachingRowsPerPartition rows(int rowNumber) { } return new TableOptions.CachingRowsPerPartition(Integer.toString(rowNumber)); } + + public static TableOptions.AdditionalWritePolicyValue additionalWritePolicyNever() { + return new TableOptions.AdditionalWritePolicyValue("'NEVER'"); + } + + public static TableOptions.AdditionalWritePolicyValue additionalWritePolicyAlways() { + return new TableOptions.AdditionalWritePolicyValue("'ALWAYS'"); + } + + public static TableOptions.AdditionalWritePolicyValue additionalWritePolicyPercentile( + int percentile) { + if (percentile < 0 || percentile > 100) { + throw new IllegalArgumentException( + "Percentile value for additional write policy should be between 0 and 100"); + } + return new TableOptions.AdditionalWritePolicyValue("'" + percentile + "percentile'"); + } + + public static TableOptions.AdditionalWritePolicyValue additionalWritePolicyMillisecs( + int millisecs) { + if (millisecs < 0) { + throw new IllegalArgumentException( + "Millisecond value for speculative retry should be positive"); + } + return new TableOptions.AdditionalWritePolicyValue("'" + millisecs + "ms'"); + } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaStatement.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaStatement.java index 986c13065a0..352d7c60b9e 100755 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaStatement.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/StatementStart.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/StatementStart.java index d39e23a9233..6bdca1dccab 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/StatementStart.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/StatementStart.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/TableOptions.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/TableOptions.java index b8e66781be8..0e24d2b98f1 100755 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/TableOptions.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/TableOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -72,6 +74,10 @@ public abstract class TableOptions extends SchemaStateme private List customOptions = new ArrayList(); + private Optional readReapair = Optional.absent(); + + private Optional additionalWritePolicy = Optional.absent(); + @SuppressWarnings("unchecked") private final T self = (T) this; @@ -409,6 +415,45 @@ public T freeformOption(String key, Object value) { return self; } + /** + * Define the read_repair mode for this table. Possible values are: + * + *
    + *
  • BLOCKING + *
  • NONE + *
+ * + *

This option is for Cassandra 4.0+. The default value is {@code BLOCKING}, which means that + * when a read repair is started, a read will block on writes sent to other replicas until the CL + * is reached by the writes. This provides monotonic quorum reads, but not partition level write + * atomicity. + * + *

If {@code NONE} is specified, the coordinator will reconcile any differences between + * replicas, but will not attempt to repair them. This provides partition level write atomicity, + * but not monotonic quorum reads. + * + * @param readRepair the read repair mode. + * @return this {@code TableOptions} object. + */ + public T readRepair(ReadRepairValue readRepair) { + this.readReapair = Optional.fromNullable(readRepair); + return self; + } + + /** + * Define the additional_write_policy for this table. This specifies the threshold at which a + * cheap quorum write will be upgraded to include transient replicas. + * + *

This option is for Cassandra 4.0+. The default value is "99p". + * + * @param additionalWritePolicy the additional write policy threshold. + * @return this {@code TableOptions} object. + */ + public T additionalWritePolicy(AdditionalWritePolicyValue additionalWritePolicy) { + this.additionalWritePolicy = Optional.fromNullable(additionalWritePolicy); + return self; + } + private static String buildCustomOption(String key, Object value) { return String.format( "%s = %s", key, (value instanceof String) ? "'" + value + "'" : value.toString()); @@ -483,6 +528,14 @@ private List buildCommonOptions() { options.add("cdc = " + cdc.get()); } + if (readReapair.isPresent()) { + options.add("read_repair = " + readReapair.get().value()); + } + + if (additionalWritePolicy.isPresent()) { + options.add("additional_write_policy = " + additionalWritePolicy.get().value()); + } + options.addAll(customOptions); return options; @@ -1362,4 +1415,45 @@ public String value() { return value; } } + + /** Read Repair modes. Possible values: BLOCKING, NONE. */ + public static enum ReadRepairValue { + BLOCKING("'BLOCKING'"), + NONE("'NONE'"); + + private String value; + + private ReadRepairValue(String value) { + this.value = value; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return value; + } + } + + /** + * Additional Write Policy. Default value is 99p. + * + *

To create instances, use {@link SchemaBuilder#additionalWritePolicyNone() ()}, {@link + * SchemaBuilder#additionalWritePolicyAlways()}, {@link + * SchemaBuilder#additionalWritePolicyMillisecs(int)} or {@link + * SchemaBuilder#additionalWritePolicyMillisecs(int)}. + */ + public static class AdditionalWritePolicyValue { + private String value; + + public AdditionalWritePolicyValue(String value) { + this.value = value; + } + + public String value() { + return value; + } + } } diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/UDTType.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/UDTType.java index f7b147c28a9..c280543962e 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/UDTType.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/UDTType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/package-info.java b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/package-info.java index 769f43f3581..1588393466f 100755 --- a/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/package-info.java +++ b/driver-core/src/main/java/com/datastax/driver/core/schemabuilder/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/driver-core/src/main/java/com/datastax/driver/core/utils/Bytes.java b/driver-core/src/main/java/com/datastax/driver/core/utils/Bytes.java index 894cc2e42a6..5a45a4c02a2 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/utils/Bytes.java +++ b/driver-core/src/main/java/com/datastax/driver/core/utils/Bytes.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/utils/MoreFutures.java b/driver-core/src/main/java/com/datastax/driver/core/utils/MoreFutures.java index 5cbbe38c007..fe17d5b8f5d 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/utils/MoreFutures.java +++ b/driver-core/src/main/java/com/datastax/driver/core/utils/MoreFutures.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/utils/MoreObjects.java b/driver-core/src/main/java/com/datastax/driver/core/utils/MoreObjects.java index 4a87a46553f..7cf42382072 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/utils/MoreObjects.java +++ b/driver-core/src/main/java/com/datastax/driver/core/utils/MoreObjects.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/main/java/com/datastax/driver/core/utils/UUIDs.java b/driver-core/src/main/java/com/datastax/driver/core/utils/UUIDs.java index fafa2e15fb2..83b317b8c5d 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/utils/UUIDs.java +++ b/driver-core/src/main/java/com/datastax/driver/core/utils/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, diff --git a/driver-core/src/main/resources/com/datastax/driver/core/Driver.properties b/driver-core/src/main/resources/com/datastax/driver/core/Driver.properties index e9a44b0b905..23b955a044f 100644 --- a/driver-core/src/main/resources/com/datastax/driver/core/Driver.properties +++ b/driver-core/src/main/resources/com/datastax/driver/core/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, diff --git a/driver-core/src/test/java/com/datastax/driver/core/AbstractBatchIdempotencyTest.java b/driver-core/src/test/java/com/datastax/driver/core/AbstractBatchIdempotencyTest.java index a5627d69880..50cface64a8 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/AbstractBatchIdempotencyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/AbstractBatchIdempotencyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/AbstractPoliciesTest.java b/driver-core/src/test/java/com/datastax/driver/core/AbstractPoliciesTest.java index aeb000c05ea..c8366175699 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/AbstractPoliciesTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/AbstractPoliciesTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 +85,8 @@ protected void createMultiDCSchema(int dc1RF, int dc2RF) { /** Coordinator management/count */ protected void addCoordinator(ResultSet rs) { - InetAddress coordinator = rs.getExecutionInfo().getQueriedHost().getAddress(); + InetAddress coordinator = + rs.getExecutionInfo().getQueriedHost().getEndPoint().resolve().getAddress(); Integer n = coordinators.get(coordinator); coordinators.put(coordinator, n == null ? 1 : n + 1); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java b/driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java index 9b9ebcc0943..fd36c94938f 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -369,7 +371,8 @@ protected Connection tryReconnect() throws ConnectionException { case THROW_EXCEPTION: logger.debug("simulate reconnection error"); throw new ConnectionException( - new InetSocketAddress(8888), "Simulated exception from mock reconnection"); + EndPoints.forAddress(new InetSocketAddress(8888)), + "Simulated exception from mock reconnection"); default: throw new AssertionError(); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java b/driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java index ba182d50a9f..766abe6ddb5 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 +46,10 @@ protected static class HostMock extends Host { private final InetSocketAddress address; private HostMock(InetSocketAddress address, Cluster.Manager manager) { - super(address, new ConvictionPolicy.DefaultConvictionPolicy.Factory(), manager); + super( + EndPoints.forAddress(address), + new ConvictionPolicy.DefaultConvictionPolicy.Factory(), + manager); this.address = address; } diff --git a/driver-core/src/test/java/com/datastax/driver/core/AdditionalWritePolicyTest.java b/driver-core/src/test/java/com/datastax/driver/core/AdditionalWritePolicyTest.java new file mode 100644 index 00000000000..415387ca672 --- /dev/null +++ b/driver-core/src/test/java/com/datastax/driver/core/AdditionalWritePolicyTest.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.driver.core; + +import static com.datastax.driver.core.Assertions.assertThat; +import static org.testng.Assert.fail; + +import com.datastax.driver.core.exceptions.InvalidQueryException; +import com.datastax.driver.core.schemabuilder.SchemaBuilder; +import com.datastax.driver.core.schemabuilder.TableOptions; +import com.datastax.driver.core.utils.CassandraVersion; +import org.testng.annotations.Test; + +@CassandraVersion( + value = "4.0.0-alpha1", + description = "Additional Write Policy is for Cassandra 4.0+") +public class AdditionalWritePolicyTest extends CCMTestsSupport { + + private void cleanup(String tableName) { + session().execute(String.format("DROP TABLE IF EXISTS %s", tableName)); + } + + @Test(groups = "short") + public void should_create_table_with_additional_write_policy_default() { + String test_table = "awp_default"; + session() + .execute( + SchemaBuilder.createTable(test_table) + .addPartitionKey("pk", DataType.text()) + .addColumn("data", DataType.text())); + assertThat( + cluster() + .getMetadata() + .getKeyspace(keyspace) + .getTable(test_table) + .getOptions() + .getAdditionalWritePolicy()) + .isEqualTo("99p"); + cleanup(test_table); + } + + @Test(groups = "short") + public void should_create_table_with_additonal_write_policy_percentile() { + String test_table = "awp_percentile"; + session() + .execute( + SchemaBuilder.createTable(test_table) + .addPartitionKey("pk", DataType.text()) + .addColumn("data", DataType.text()) + .withOptions() + .additionalWritePolicy(SchemaBuilder.additionalWritePolicyPercentile(44))); + assertThat( + cluster() + .getMetadata() + .getKeyspace(keyspace) + .getTable(test_table) + .getOptions() + .getAdditionalWritePolicy()) + .isEqualTo("44p"); + cleanup(test_table); + } + + @Test(groups = "short") + public void should_create_table_with_additonal_write_policy_millisecs() { + String test_table = "awp_millisecs"; + session() + .execute( + SchemaBuilder.createTable(test_table) + .addPartitionKey("pk", DataType.text()) + .addColumn("data", DataType.text()) + .withOptions() + .additionalWritePolicy(SchemaBuilder.additionalWritePolicyMillisecs(350))); + assertThat( + cluster() + .getMetadata() + .getKeyspace(keyspace) + .getTable(test_table) + .getOptions() + .getAdditionalWritePolicy()) + .isEqualTo("350ms"); + cleanup(test_table); + } + + @Test(groups = "short") + public void should_create_table_with_additonal_write_policy_never() { + String test_table = "awp_never"; + session() + .execute( + SchemaBuilder.createTable(test_table) + .addPartitionKey("pk", DataType.text()) + .addColumn("data", DataType.text()) + .withOptions() + .additionalWritePolicy(SchemaBuilder.additionalWritePolicyNever())); + assertThat( + cluster() + .getMetadata() + .getKeyspace(keyspace) + .getTable(test_table) + .getOptions() + .getAdditionalWritePolicy()) + .isEqualTo("NEVER"); + cleanup(test_table); + } + + @Test(groups = "short") + public void should_create_table_with_additonal_write_policy_always() { + String test_table = "awp_always"; + session() + .execute( + SchemaBuilder.createTable(test_table) + .addPartitionKey("pk", DataType.text()) + .addColumn("data", DataType.text()) + .withOptions() + .additionalWritePolicy(SchemaBuilder.additionalWritePolicyAlways())); + assertThat( + cluster() + .getMetadata() + .getKeyspace(keyspace) + .getTable(test_table) + .getOptions() + .getAdditionalWritePolicy()) + .isEqualTo("ALWAYS"); + cleanup(test_table); + } + + @Test(groups = "short") + public void should_fail_to_create_table_with_invalid_additonal_write_policy() { + String test_table = "awp_invalid"; + try { + session() + .execute( + SchemaBuilder.createTable(test_table) + .addPartitionKey("pk", DataType.text()) + .addColumn("data", DataType.text()) + .withOptions() + .additionalWritePolicy(new TableOptions.AdditionalWritePolicyValue("'ALL'"))); + fail("Should not be able to create table with invlaid 'additional_write_policy': 'ALL'"); + } catch (InvalidQueryException iqe) { + assertThat(iqe) + .hasMessageContaining("Invalid value") + .hasMessageContaining("ALL") + .hasMessageContaining("for option"); + } finally { + cleanup(test_table); + } + } +} diff --git a/driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataAssert.java b/driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataAssert.java index 6fb5d93bf35..bf77e1c41c9 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataTest.java b/driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataTest.java index 55459b7da13..7f9432fda99 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/Assertions.java b/driver-core/src/test/java/com/datastax/driver/core/Assertions.java index 0b633336d79..11d10f715ac 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/Assertions.java +++ b/driver-core/src/test/java/com/datastax/driver/core/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, @@ -15,7 +17,7 @@ */ package com.datastax.driver.core; -/** Augment AssertJ with custom assertions for the Java driver. */ +/** Augment AssertJ with custom assertions for the Java Driver. */ public class Assertions extends org.assertj.core.api.Assertions { public static ClusterAssert assertThat(Cluster cluster) { return new ClusterAssert(cluster); diff --git a/driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java b/driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java index d59e9829bb1..fe75253b9bf 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 +26,6 @@ import com.datastax.driver.core.utils.CassandraVersion; import com.google.common.base.Function; import com.google.common.base.Throwables; -import com.google.common.collect.Lists; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.Uninterruptibles; @@ -83,13 +84,7 @@ public void cancelled_query_should_release_the_connection() throws InterruptedEx public void should_init_cluster_and_session_if_needed() throws Exception { // For this test we need an uninitialized cluster, so we can't reuse the one provided by the // parent class. Rebuild a new one with the same (unique) host. - Host host = cluster().getMetadata().allHosts().iterator().next(); - - Cluster cluster2 = - register( - Cluster.builder() - .addContactPointsWithPorts(Lists.newArrayList(host.getSocketAddress())) - .build()); + Cluster cluster2 = register(createClusterBuilder().build()); try { Session session2 = cluster2.newSession(); diff --git a/driver-core/src/test/java/com/datastax/driver/core/AsyncResultSetTest.java b/driver-core/src/test/java/com/datastax/driver/core/AsyncResultSetTest.java index 4381702e5c1..08e7f009b2a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/AsyncResultSetTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/AsyncResultSetTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/AtomicMonotonicTimestampGeneratorTest.java b/driver-core/src/test/java/com/datastax/driver/core/AtomicMonotonicTimestampGeneratorTest.java index 45f00cd15e1..e7bdf848b24 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/AtomicMonotonicTimestampGeneratorTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/AtomicMonotonicTimestampGeneratorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java b/driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java index 53efcbbefc4..0166fac1b2a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -53,17 +55,11 @@ public void sleepIf12() { @Test(groups = "short") public void should_connect_with_credentials() { PlainTextAuthProvider authProvider = spy(new PlainTextAuthProvider("cassandra", "cassandra")); - Cluster cluster = - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withAuthProvider(authProvider) - .build(); + Cluster cluster = createClusterBuilder().withAuthProvider(authProvider).build(); cluster.connect(); verify(authProvider, atLeastOnce()) .newAuthenticator( - findHost(cluster, 1).getSocketAddress(), - "org.apache.cassandra.auth.PasswordAuthenticator"); + findHost(cluster, 1).getEndPoint(), "org.apache.cassandra.auth.PasswordAuthenticator"); assertThat(cluster.getMetrics().getErrorMetrics().getAuthenticationErrors().getCount()) .isEqualTo(0); } @@ -79,13 +75,7 @@ public void should_connect_with_credentials() { */ @Test(groups = "short") public void should_fail_to_connect_with_wrong_credentials() { - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withCredentials("bogus", "bogus") - .build()); + Cluster cluster = register(createClusterBuilder().withCredentials("bogus", "bogus").build()); try { cluster.connect(); @@ -107,12 +97,7 @@ public void should_fail_to_connect_with_wrong_credentials() { @Test(groups = "short", expectedExceptions = AuthenticationException.class) public void should_fail_to_connect_without_credentials() { - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .build()); + Cluster cluster = register(createClusterBuilder().build()); cluster.connect(); } @@ -125,9 +110,7 @@ public void should_fail_to_connect_without_credentials() { @CCMConfig(dirtiesContext = true) public void should_connect_with_slow_server() { Cluster cluster = - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() .withAuthProvider(new SlowAuthProvider()) .withPoolingOptions(new PoolingOptions().setHeartbeatIntervalSeconds(1)) .build(); @@ -141,7 +124,7 @@ public SlowAuthProvider() { } @Override - public Authenticator newAuthenticator(InetSocketAddress host, String authenticator) + public Authenticator newAuthenticator(EndPoint host, String authenticator) throws AuthenticationException { simulateBusyServer(); return super.newAuthenticator(host, authenticator); @@ -170,13 +153,7 @@ public void run() { @Test(groups = "short") public void should_not_create_pool_with_wrong_credentials() { PlainTextAuthProvider authProvider = new PlainTextAuthProvider("cassandra", "cassandra"); - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withAuthProvider(authProvider) - .build()); + Cluster cluster = register(createClusterBuilder().withAuthProvider(authProvider).build()); cluster.init(); authProvider.setPassword("wrong"); Level previous = TestUtils.setLogLevel(Session.class, Level.WARN); diff --git a/driver-core/src/test/java/com/datastax/driver/core/BatchStatementIdempotencyTest.java b/driver-core/src/test/java/com/datastax/driver/core/BatchStatementIdempotencyTest.java index 442bd27ca72..2fd645275f3 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/BatchStatementIdempotencyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/BatchStatementIdempotencyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java b/driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java index 5f6fe83bb92..07320f87a1b 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/BoundStatementTest.java b/driver-core/src/test/java/com/datastax/driver/core/BoundStatementTest.java index 9d84799c183..7b33590fe38 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/BoundStatementTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/BoundStatementTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/BytesToSegmentDecoderTest.java b/driver-core/src/test/java/com/datastax/driver/core/BytesToSegmentDecoderTest.java new file mode 100644 index 00000000000..70608509988 --- /dev/null +++ b/driver-core/src/test/java/com/datastax/driver/core/BytesToSegmentDecoderTest.java @@ -0,0 +1,139 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.datastax.driver.core.ProtocolOptions.Compression; +import com.datastax.driver.core.exceptions.CrcMismatchException; +import com.google.common.base.Strings; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.buffer.ByteBufUtil; +import io.netty.buffer.Unpooled; +import io.netty.channel.embedded.EmbeddedChannel; +import io.netty.handler.codec.DecoderException; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class BytesToSegmentDecoderTest { + + // Hard-coded test data, the values were generated with our encoding methods. + // We're not really testing the decoding itself here, only that our subclass calls the + // LengthFieldBasedFrameDecoder parent constructor with the right parameters. + private static final ByteBuf REGULAR_HEADER = byteBuf("04000201f9f2"); + private static final ByteBuf REGULAR_PAYLOAD = byteBuf("00000001"); + private static final ByteBuf REGULAR_TRAILER = byteBuf("1fd6022d"); + private static final ByteBuf REGULAR_WRONG_HEADER = byteBuf("04000202f9f2"); + private static final ByteBuf REGULAR_WRONG_TRAILER = byteBuf("1fd6022e"); + + private static final ByteBuf MAX_HEADER = byteBuf("ffff03254047"); + private static final ByteBuf MAX_PAYLOAD = + byteBuf(Strings.repeat("01", Segment.MAX_PAYLOAD_LENGTH)); + private static final ByteBuf MAX_TRAILER = byteBuf("a05c2f13"); + + private static final ByteBuf LZ4_HEADER = byteBuf("120020000491c94f"); + private static final ByteBuf LZ4_PAYLOAD_UNCOMPRESSED = + byteBuf("00000001000000010000000100000001"); + private static final ByteBuf LZ4_PAYLOAD_COMPRESSED = + byteBuf("f00100000001000000010000000100000001"); + private static final ByteBuf LZ4_TRAILER = byteBuf("2bd67f90"); + + private EmbeddedChannel channel; + + @BeforeMethod(groups = "unit") + public void setup() { + channel = new EmbeddedChannel(); + } + + @Test(groups = "unit") + public void should_decode_regular_segment() { + channel.pipeline().addLast(newDecoder(Compression.NONE)); + channel.writeInbound(Unpooled.wrappedBuffer(REGULAR_HEADER, REGULAR_PAYLOAD, REGULAR_TRAILER)); + Segment segment = (Segment) channel.readInbound(); + assertThat(segment.isSelfContained()).isTrue(); + assertThat(segment.getPayload()).isEqualTo(REGULAR_PAYLOAD); + } + + @Test(groups = "unit") + public void should_decode_max_length_segment() { + channel.pipeline().addLast(newDecoder(Compression.NONE)); + channel.writeInbound(Unpooled.wrappedBuffer(MAX_HEADER, MAX_PAYLOAD, MAX_TRAILER)); + Segment segment = (Segment) channel.readInbound(); + assertThat(segment.isSelfContained()).isTrue(); + assertThat(segment.getPayload()).isEqualTo(MAX_PAYLOAD); + } + + @Test(groups = "unit") + public void should_decode_segment_from_multiple_incoming_chunks() { + channel.pipeline().addLast(newDecoder(Compression.NONE)); + // Send the header in two slices, to cover the case where the length can't be read the first + // time: + ByteBuf headerStart = REGULAR_HEADER.slice(0, 3); + ByteBuf headerEnd = REGULAR_HEADER.slice(3, 3); + channel.writeInbound(headerStart); + channel.writeInbound(headerEnd); + channel.writeInbound(REGULAR_PAYLOAD.duplicate()); + channel.writeInbound(REGULAR_TRAILER.duplicate()); + Segment segment = (Segment) channel.readInbound(); + assertThat(segment.isSelfContained()).isTrue(); + assertThat(segment.getPayload()).isEqualTo(REGULAR_PAYLOAD); + } + + @Test(groups = "unit") + public void should_decode_compressed_segment() { + channel.pipeline().addLast(newDecoder(Compression.LZ4)); + // We need a contiguous buffer for this one, because of how our decompressor operates + ByteBuf buffer = Unpooled.wrappedBuffer(LZ4_HEADER, LZ4_PAYLOAD_COMPRESSED, LZ4_TRAILER).copy(); + channel.writeInbound(buffer); + Segment segment = (Segment) channel.readInbound(); + assertThat(segment.isSelfContained()).isTrue(); + assertThat(segment.getPayload()).isEqualTo(LZ4_PAYLOAD_UNCOMPRESSED); + } + + @Test(groups = "unit") + public void should_surface_header_crc_mismatch() { + try { + channel.pipeline().addLast(newDecoder(Compression.NONE)); + channel.writeInbound( + Unpooled.wrappedBuffer(REGULAR_WRONG_HEADER, REGULAR_PAYLOAD, REGULAR_TRAILER)); + } catch (DecoderException exception) { + assertThat(exception).hasCauseInstanceOf(CrcMismatchException.class); + } + } + + @Test(groups = "unit") + public void should_surface_trailer_crc_mismatch() { + try { + channel.pipeline().addLast(newDecoder(Compression.NONE)); + channel.writeInbound( + Unpooled.wrappedBuffer(REGULAR_HEADER, REGULAR_PAYLOAD, REGULAR_WRONG_TRAILER)); + } catch (DecoderException exception) { + assertThat(exception).hasCauseInstanceOf(CrcMismatchException.class); + } + } + + private BytesToSegmentDecoder newDecoder(Compression compression) { + return new BytesToSegmentDecoder(new SegmentCodec(ByteBufAllocator.DEFAULT, compression)); + } + + private static ByteBuf byteBuf(String hex) { + return Unpooled.unreleasableBuffer( + Unpooled.unmodifiableBuffer(Unpooled.wrappedBuffer(ByteBufUtil.decodeHexDump(hex)))); + } +} diff --git a/driver-core/src/test/java/com/datastax/driver/core/CCMAccess.java b/driver-core/src/test/java/com/datastax/driver/core/CCMAccess.java index c3bcc00e8d5..22b7504a1d2 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CCMAccess.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CCMAccess.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 +19,9 @@ import java.io.Closeable; import java.io.File; +import java.net.InetAddress; import java.net.InetSocketAddress; +import java.util.List; import java.util.Map; public interface CCMAccess extends Closeable { @@ -41,8 +45,6 @@ enum Workload { * is assumed that this value is only used for representing the compatible Cassandra version for * that DSE version. * - *

- * * @return The version of this CCM cluster. */ VersionNumber getCassandraVersion(); @@ -50,8 +52,6 @@ enum Workload { /** * Returns the DSE version of this CCM cluster if this is a DSE cluster, otherwise null. * - *

- * * @return The version of this CCM cluster. */ VersionNumber getDSEVersion(); @@ -87,13 +87,29 @@ enum Workload { void setKeepLogs(boolean keepLogs); /** - * @return the node count for each datacenter, mapped in the corresponding cell of the returned - * int array. This is the count that was passed at initialization (that is, the argument to - * {@link CCMBridge.Builder#withNodes(int...)} or {@link CCMConfig#numberOfNodes()}). Note - * that it will NOT be updated dynamically if nodes are added or removed at runtime. + * Returns the node count for each datacenter, mapped in the corresponding cell of the returned + * int array. + * + *

This is the count that was passed at initialization (that is, the argument to {@link + * CCMBridge.Builder#withNodes(int...)} or {@link CCMConfig#numberOfNodes()}). Note that it will + * NOT be updated dynamically if nodes are added or removed at runtime. + * + * @return the node count for each datacenter. */ int[] getNodeCount(); + /** + * Returns the contact points to use to contact the CCM cluster. + * + *

This reflects the initial number of nodes in the cluster, as configured at initialization + * (that is, the argument to {@link CCMBridge.Builder#withNodes(int...)} or {@link + * CCMConfig#numberOfNodes()}). Note that it will NOT be updated dynamically if nodes are + * added or removed at runtime. + * + * @return the contact points to use to contact the CCM cluster. + */ + List getContactPoints(); + /** * Returns the address of the {@code nth} host in the CCM cluster (counting from 1, i.e., {@code * addressOfNode(1)} returns the address of the first node. @@ -246,13 +262,13 @@ enum Workload { // Methods blocking until nodes are up or down /** - * Waits for a host to be up by pinging the TCP socket directly, without using the Java driver's + * Waits for a host to be up by pinging the TCP socket directly, without using the Java Driver's * API. */ void waitForUp(int node); /** - * Waits for a host to be down by pinging the TCP socket directly, without using the Java driver's + * Waits for a host to be down by pinging the TCP socket directly, without using the Java Driver's * API. */ void waitForDown(int node); diff --git a/driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java b/driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java index e68751157e5..5070e673070 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; +import java.net.InetAddress; import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; @@ -110,7 +116,6 @@ public class CCMBridge implements CCMAccess { */ private static final Map dseToCassandraVersions = ImmutableMap.builder() - .put("6.0", "4.0") .put("5.1", "3.11") .put("5.0.4", "3.0.10") .put("5.0.3", "3.0.9") @@ -173,12 +178,6 @@ public class CCMBridge implements CCMAccess { String installDirectory = System.getProperty("cassandra.directory"); String branch = System.getProperty("cassandra.branch"); - String dseProperty = System.getProperty("dse"); - // If -Ddse, if the value is empty interpret it as enabled, - // otherwise if there is a value, parse as boolean. - boolean isDse = - dseProperty != null && (dseProperty.isEmpty() || Boolean.parseBoolean(dseProperty)); - ImmutableSet.Builder installArgs = ImmutableSet.builder(); if (installDirectory != null && !installDirectory.trim().isEmpty()) { installArgs.add("--install-dir=" + new File(installDirectory).getAbsolutePath()); @@ -188,7 +187,7 @@ public class CCMBridge implements CCMAccess { installArgs.add("-v " + inputCassandraVersion); } - if (isDse) { + if (isDse()) { installArgs.add("--dse"); } @@ -219,7 +218,7 @@ public class CCMBridge implements CCMAccess { } ENVIRONMENT_MAP = ImmutableMap.copyOf(envMap); - if (isDse) { + if (isDse()) { GLOBAL_DSE_VERSION_NUMBER = VersionNumber.parse(inputCassandraVersion); GLOBAL_CASSANDRA_VERSION_NUMBER = CCMBridge.getCassandraVersion(GLOBAL_DSE_VERSION_NUMBER); logger.info( @@ -247,6 +246,11 @@ public static VersionNumber getGlobalDSEVersion() { return GLOBAL_DSE_VERSION_NUMBER; } + public static boolean isDse() { + // System property "dse" must be present and evaluate to TRUE to indicate DSE is enabled. + return Boolean.getBoolean("dse"); + } + /** * @return The mapped cassandra version to the given dseVersion. If the DSE version can't be * derived the following logic is used: @@ -275,6 +279,12 @@ public static VersionNumber getCassandraVersion(VersionNumber dseVersion) { } else { return VersionNumber.parse("3.11"); } + } else if (dseVersion.getMajor() == 6) { + if (dseVersion.getMinor() < 8) { + return VersionNumber.parse("3.11"); + } else { + return VersionNumber.parse("4.0"); + } } else { // Fallback on 4.0 by default. return VersionNumber.parse("4.0"); @@ -363,6 +373,24 @@ public int[] getNodeCount() { return Arrays.copyOf(nodes, nodes.length); } + @Override + public List getContactPoints() { + List contactPoints = new ArrayList(); + int n = 1; + for (int dc = 1; dc <= nodes.length; dc++) { + int nodesInDc = nodes[dc - 1]; + for (int i = 0; i < nodesInDc; i++) { + try { + contactPoints.add(InetAddress.getByName(ipOfNode(n))); + } catch (UnknownHostException e) { + Throwables.propagate(e); + } + n++; + } + } + return contactPoints; + } + protected String ipOfNode(int n) { return ipPrefix + n; } @@ -769,7 +797,7 @@ protected void processLine(String line, int logLevel) { } /** - * Waits for a host to be up by pinging the TCP socket directly, without using the Java driver's + * Waits for a host to be up by pinging the TCP socket directly, without using the Java Driver's * API. */ @Override @@ -778,7 +806,7 @@ public void waitForUp(int node) { } /** - * Waits for a host to be down by pinging the TCP socket directly, without using the Java driver's + * Waits for a host to be down by pinging the TCP socket directly, without using the Java Driver's * API. */ @Override @@ -795,8 +823,10 @@ public ProtocolVersion getProtocolVersion() { return ProtocolVersion.V2; } else if (version.compareTo(VersionNumber.parse("2.2")) < 0) { return ProtocolVersion.V3; - } else { + } else if (version.compareTo(VersionNumber.parse("4.0")) < 0) { return ProtocolVersion.V4; + } else { + return ProtocolVersion.V5; } } @@ -862,13 +892,13 @@ public static class Builder { int[] nodes = {1}; private int[] jmxPorts = {}; private boolean start = true; - private boolean dse = false; + private boolean dse = isDse(); private VersionNumber version = null; - private Set createOptions = new LinkedHashSet(); - private Set jvmArgs = new LinkedHashSet(); + private final Set createOptions = new LinkedHashSet(); + private final Set jvmArgs = new LinkedHashSet(); private final Map cassandraConfiguration = Maps.newLinkedHashMap(); private final Map dseConfiguration = Maps.newLinkedHashMap(); - private Map workloads = new HashMap(); + private final Map workloads = new HashMap(); private Builder() { cassandraConfiguration.put("start_rpc", false); @@ -898,6 +928,7 @@ public Builder withoutNodes() { /** Enables SSL encryption. */ public Builder withSSL() { cassandraConfiguration.put("client_encryption_options.enabled", "true"); + cassandraConfiguration.put("client_encryption_options.optional", "false"); cassandraConfiguration.put( "client_encryption_options.keystore", DEFAULT_SERVER_KEYSTORE_FILE.getAbsolutePath()); cassandraConfiguration.put( @@ -1041,12 +1072,22 @@ public CCMBridge build() { } } - if (!isThriftSupported(cassandraVersion)) { + if (!isThriftSupported(cassandraVersion, dseVersion)) { // remove thrift configuration cassandraConfiguration.remove("start_rpc"); cassandraConfiguration.remove("rpc_port"); cassandraConfiguration.remove("thrift_prepared_statements_cache_size_mb"); } + if (!dse) { + if (isMaterializedViewsDisabledByDefault(cassandraVersion)) { + // enable materialized views + cassandraConfiguration.put("enable_materialized_views", true); + } + if (isSasiConfigEnablementRequired(cassandraVersion)) { + // enable SASI indexing in config (disabled by default in C* 4.0) + cassandraConfiguration.put("enable_sasi_indexes", true); + } + } final CCMBridge ccm = new CCMBridge( clusterName, @@ -1088,8 +1129,22 @@ public void run() { return ccm; } - private static boolean isThriftSupported(VersionNumber cassandraVersion) { - return cassandraVersion.compareTo(VersionNumber.parse("4.0")) < 0; + private static boolean isThriftSupported( + VersionNumber cassandraVersion, VersionNumber dseVersion) { + if (dseVersion == null) { + // Thrift is removed from some pre-release 4.x versions, make the comparison work for those + return cassandraVersion.nextStable().compareTo(VersionNumber.parse("4.0")) < 0; + } else { + return dseVersion.nextStable().compareTo(VersionNumber.parse("6.0")) < 0; + } + } + + private static boolean isMaterializedViewsDisabledByDefault(VersionNumber cassandraVersion) { + return cassandraVersion.nextStable().compareTo(VersionNumber.parse("4.0")) >= 0; + } + + private static boolean isSasiConfigEnablementRequired(VersionNumber cassandraVersion) { + return cassandraVersion.nextStable().compareTo(VersionNumber.parse("4.0")) >= 0; } public int weight() { diff --git a/driver-core/src/test/java/com/datastax/driver/core/CCMBridgeTest.java b/driver-core/src/test/java/com/datastax/driver/core/CCMBridgeTest.java index 15147738072..e82db86ea88 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CCMBridgeTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CCMBridgeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/CCMCache.java b/driver-core/src/test/java/com/datastax/driver/core/CCMCache.java index e8682003c7f..caa2a1ed218 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CCMCache.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CCMCache.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,10 @@ import com.google.common.cache.RemovalNotification; import com.google.common.cache.Weigher; import java.io.File; +import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; @@ -107,6 +111,11 @@ public int[] getNodeCount() { return ccm.getNodeCount(); } + @Override + public List getContactPoints() { + return ccm.getContactPoints(); + } + @Override public InetSocketAddress addressOfNode(int n) { return ccm.addressOfNode(n); diff --git a/driver-core/src/test/java/com/datastax/driver/core/CCMConfig.java b/driver-core/src/test/java/com/datastax/driver/core/CCMConfig.java index 5f0fa63932a..dc51f963bc2 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CCMConfig.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CCMConfig.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/CCMException.java b/driver-core/src/test/java/com/datastax/driver/core/CCMException.java index 6ad1d965820..ad1cc7068b5 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CCMException.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CCMException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/CCMTestsSupport.java b/driver-core/src/test/java/com/datastax/driver/core/CCMTestsSupport.java index 8f695a42701..8e8add392e6 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CCMTestsSupport.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CCMTestsSupport.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 static org.assertj.core.api.Assertions.fail; import com.datastax.driver.core.CCMAccess.Workload; +import com.datastax.driver.core.Cluster.Builder; import com.datastax.driver.core.CreateCCM.TestMode; import com.datastax.driver.core.exceptions.InvalidQueryException; import com.google.common.base.Throwables; @@ -55,6 +58,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.ITestResult; +import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; @@ -157,6 +161,11 @@ public int[] getNodeCount() { return delegate.getNodeCount(); } + @Override + public List getContactPoints() { + return delegate.getContactPoints(); + } + @Override public String checkForErrors() { return delegate.checkForErrors(); @@ -631,7 +640,7 @@ public void beforeTestClass(Object testInstance) throws Exception { } catch (Exception e) { LOGGER.error(e.getMessage(), e); errorOut(); - fail(e.getMessage()); + throw e; } } } @@ -706,18 +715,15 @@ public void afterTestClass() throws Exception { /** * Returns the cluster builder to use for this test. * - *

The default implementation returns a vanilla builder. - * - *

It's not required to call {@link - * com.datastax.driver.core.Cluster.Builder#addContactPointsWithPorts}, it will be done - * automatically. + *

The default implementation returns a vanilla builder with contact points and port that match + * the running CCM cluster. Therefore it's not required to call {@link + * Cluster.Builder#addContactPointsWithPorts}, it will be done automatically. * * @return The cluster builder to use for the tests. */ public Cluster.Builder createClusterBuilder() { - return Cluster.builder() - // use a different codec registry for each cluster instance - .withCodecRegistry(new CodecRegistry()); + Cluster.Builder builder = Cluster.builder(); + return configureClusterBuilder(builder); } /** @@ -730,7 +736,18 @@ public Cluster.Builder createClusterBuilder() { * @return The cluster builder to use for the tests. */ public Cluster.Builder createClusterBuilderNoDebouncing() { - return Cluster.builder().withQueryOptions(TestUtils.nonDebouncingQueryOptions()); + return createClusterBuilder().withQueryOptions(TestUtils.nonDebouncingQueryOptions()); + } + + /** + * Configures the builder with contact points and port that match the running CCM cluster. + * Therefore it's not required to call {@link Cluster.Builder#addContactPointsWithPorts}, it will + * be done automatically. + * + * @return The cluster builder (for method chaining). + */ + protected Builder configureClusterBuilder(Builder builder) { + return TestUtils.configureClusterBuilder(builder, ccm()); } /** @@ -963,6 +980,12 @@ protected void initTestCluster(Object testInstance) throws Exception { // add contact points only if the provided builder didn't do so if (builder.getContactPoints().isEmpty()) builder.addContactPoints(getContactPoints()); builder.withPort(ccm.getBinaryPort()); + if (ccm().getCassandraVersion().compareTo(VersionNumber.parse("3.10")) >= 0 + && ccm().getCassandraVersion().compareTo(VersionNumber.parse("4.0-beta5")) < 0) { + // prevent usage of protocol v5 for 3.10 and 3.11 since these versions have the beta + // version of it + builder.withProtocolVersion(ProtocolVersion.V4); + } cluster = register(builder.build()); cluster.init(); } @@ -1117,4 +1140,17 @@ private static T instantiate(Class clazz) return (T) constructor.newInstance(enclosingInstance); } } + + protected boolean isCassandraVersionOrHigher(String version) { + return CCMBridge.getGlobalCassandraVersion().compareTo(VersionNumber.parse(version)) >= 0; + } + + protected void skipTestWithCassandraVersionOrHigher(String version, String testKind) { + if (isCassandraVersionOrHigher(version)) { + throw new SkipException( + String.format( + "%s tests not applicable to cassandra version >= %s (configured: %s)", + testKind, version, CCMBridge.getGlobalCassandraVersion())); + } + } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/CCMWorkload.java b/driver-core/src/test/java/com/datastax/driver/core/CCMWorkload.java index abf35c99636..ed18c9a3a47 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CCMWorkload.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CCMWorkload.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java b/driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java index 711defd08a1..89e0f6c398e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ClockFactoryTest.java b/driver-core/src/test/java/com/datastax/driver/core/ClockFactoryTest.java index fe028c79e91..8847dc43304 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ClockFactoryTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ClockFactoryTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/CloudConfigFactoryTest.java b/driver-core/src/test/java/com/datastax/driver/core/CloudConfigFactoryTest.java new file mode 100644 index 00000000000..96d97faa45c --- /dev/null +++ b/driver-core/src/test/java/com/datastax/driver/core/CloudConfigFactoryTest.java @@ -0,0 +1,251 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.any; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.apache.commons.codec.CharEncoding.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; + +import com.fasterxml.jackson.core.JsonParseException; +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.common.JettySettings; +import com.github.tomakehurst.wiremock.core.Options; +import com.github.tomakehurst.wiremock.http.AdminRequestHandler; +import com.github.tomakehurst.wiremock.http.HttpServer; +import com.github.tomakehurst.wiremock.http.HttpServerFactory; +import com.github.tomakehurst.wiremock.http.StubRequestHandler; +import com.github.tomakehurst.wiremock.jetty9.JettyHttpServer; +import com.google.common.base.Joiner; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URL; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLSession; +import org.apache.commons.io.FileUtils; +import org.eclipse.jetty.io.NetworkTrafficListener; +import org.eclipse.jetty.server.ConnectionFactory; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.server.SslConnectionFactory; +import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class CloudConfigFactoryTest { + + private static final String BUNDLE_PATH = "/cloud/creds.zip"; + + private WireMockServer wireMockServer; + + @BeforeMethod + public void startWireMock() { + wireMockServer = + new WireMockServer( + wireMockConfig() + .httpsPort(30443) + .dynamicPort() + .httpServerFactory(new HttpsServerFactory()) + .needClientAuth(true) + .keystorePath(path("/cloud/identity.jks")) + .keystorePassword("XS78x3GuBWas1OoA5") + .trustStorePath(path("/cloud/trustStore.jks")) + .trustStorePassword("48ZY5r06BmpVLKxPg")); + wireMockServer.start(); + } + + @AfterMethod + public void stopWireMock() { + wireMockServer.stop(); + } + + @Test + public void should_load_config_from_local_filesystem() throws Exception { + // given + URL configFile = getClass().getResource(BUNDLE_PATH); + mockProxyMetadataService(jsonMetadata()); + // when + CloudConfigFactory cloudConfigFactory = new CloudConfigFactory(); + CloudConfig cloudConfig = cloudConfigFactory.createCloudConfig(configFile.openStream()); + // then + assertCloudConfig(cloudConfig); + } + + @Test + public void should_load_config_from_external_location() throws Exception { + // given + mockHttpSecureBundle(secureBundle()); + mockProxyMetadataService(jsonMetadata()); + // when + URL configFile = new URL("http", "localhost", wireMockServer.port(), BUNDLE_PATH); + CloudConfigFactory cloudConfigFactory = new CloudConfigFactory(); + CloudConfig cloudConfig = cloudConfigFactory.createCloudConfig(configFile.openStream()); + // then + assertCloudConfig(cloudConfig); + } + + @Test + public void should_throw_when_bundle_not_found() throws Exception { + // given + wireMockServer.stubFor(any(urlEqualTo(BUNDLE_PATH)).willReturn(aResponse().withStatus(404))); + // when + URL configFile = new URL("http", "localhost", wireMockServer.port(), BUNDLE_PATH); + CloudConfigFactory cloudConfigFactory = new CloudConfigFactory(); + try { + cloudConfigFactory.createCloudConfig(configFile.openStream()); + } catch (FileNotFoundException ex) { + assertThat(ex).hasMessageContaining(configFile.toExternalForm()); + } + } + + @Test + public void should_throw_when_bundle_not_readable() throws Exception { + // given + mockHttpSecureBundle("not a zip file".getBytes(UTF_8)); + // when + URL configFile = new URL("http", "localhost", wireMockServer.port(), BUNDLE_PATH); + CloudConfigFactory cloudConfigFactory = new CloudConfigFactory(); + try { + cloudConfigFactory.createCloudConfig(configFile.openStream()); + } catch (IllegalStateException ex) { + assertThat(ex).hasMessageContaining("Invalid bundle: missing file config.json"); + } + } + + @Test + public void should_throw_when_metadata_not_found() throws Exception { + // given + mockHttpSecureBundle(secureBundle()); + wireMockServer.stubFor( + any(urlPathEqualTo("/metadata")).willReturn(aResponse().withStatus(404))); + // when + URL configFile = new URL("http", "localhost", wireMockServer.port(), BUNDLE_PATH); + CloudConfigFactory cloudConfigFactory = new CloudConfigFactory(); + try { + cloudConfigFactory.createCloudConfig(configFile.openStream()); + } catch (FileNotFoundException ex) { + assertThat(ex).hasMessageContaining("metadata"); + } + } + + @Test + public void should_throw_when_metadata_not_readable() throws Exception { + // given + mockHttpSecureBundle(secureBundle()); + mockProxyMetadataService("not a valid json payload"); + // when + URL configFile = new URL("http", "localhost", wireMockServer.port(), BUNDLE_PATH); + CloudConfigFactory cloudConfigFactory = new CloudConfigFactory(); + try { + cloudConfigFactory.createCloudConfig(configFile.openStream()); + } catch (JsonParseException ex) { + assertThat(ex).hasMessageContaining("Unrecognized token"); + } + } + + private void mockHttpSecureBundle(byte[] body) { + wireMockServer.stubFor( + any(urlEqualTo(BUNDLE_PATH)) + .willReturn( + aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/octet-stream") + .withBody(body))); + } + + private void mockProxyMetadataService(String jsonMetadata) { + wireMockServer.stubFor( + any(urlPathEqualTo("/metadata")) + .willReturn( + aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody(jsonMetadata))); + } + + private byte[] secureBundle() throws IOException { + return FileUtils.readFileToByteArray(new File(path(BUNDLE_PATH))); + } + + private String jsonMetadata() throws IOException { + return Joiner.on('\n').join(FileUtils.readLines(new File(path("/cloud/metadata.json")))); + } + + private String path(String resource) { + return getClass().getResource(resource).getFile(); + } + + private void assertCloudConfig(CloudConfig config) { + InetSocketAddress expectedProxyAddress = InetSocketAddress.createUnresolved("localhost", 30002); + assertThat(config.getLocalDatacenter()).isEqualTo("dc1"); + assertThat(config.getProxyAddress()).isEqualTo(expectedProxyAddress); + assertThat(config.getEndPoints()).extracting("proxyAddress").containsOnly(expectedProxyAddress); + assertThat(config.getEndPoints()) + .extracting("serverName") + .containsExactly( + "4ac06655-f861-49f9-881e-3fee22e69b94", + "2af7c253-3394-4a0d-bfac-f1ad81b5154d", + "b17b6e2a-3f48-4d6a-81c1-20a0a1f3192a"); + assertThat(config.getSslOptions()).isNotNull().isInstanceOf(SSLOptions.class); + } + + static { + javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier( + new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession sslSession) { + return hostname.equals("localhost"); + } + }); + } + + // see https://github.com/tomakehurst/wiremock/issues/874 + private static class HttpsServerFactory implements HttpServerFactory { + @Override + public HttpServer buildHttpServer( + final Options options, + AdminRequestHandler adminRequestHandler, + StubRequestHandler stubRequestHandler) { + return new JettyHttpServer(options, adminRequestHandler, stubRequestHandler) { + @Override + protected ServerConnector createServerConnector( + String bindAddress, + JettySettings jettySettings, + int port, + NetworkTrafficListener listener, + ConnectionFactory... connectionFactories) { + if (port == options.httpsSettings().port()) { + SslConnectionFactory sslConnectionFactory = + (SslConnectionFactory) connectionFactories[0]; + SslContextFactory sslContextFactory = sslConnectionFactory.getSslContextFactory(); + sslContextFactory.setKeyStorePassword(options.httpsSettings().keyStorePassword()); + connectionFactories = + new ConnectionFactory[] {sslConnectionFactory, connectionFactories[1]}; + } + return super.createServerConnector( + bindAddress, jettySettings, port, listener, connectionFactories); + } + }; + } + } +} diff --git a/driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java b/driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java index 92ca9bfcb5a..941254a183c 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,8 @@ protected ClusterAssert(Cluster actual) { public ClusterAssert usesControlHost(int node) { String expectedAddress = TestUtils.ipOfNode(node); Host controlHost = actual.manager.controlConnection.connectedHost(); - assertThat(controlHost.getAddress().getHostAddress()).isEqualTo(expectedAddress); + assertThat(controlHost.getEndPoint().resolve().getAddress().getHostAddress()) + .isEqualTo(expectedAddress); return this; } diff --git a/driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java b/driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java index 4c0d8ef42ca..e2f88dedf9d 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,6 +71,7 @@ public void should_handle_failing_or_missing_contact_points() throws UnknownHost // - 1 is an actual Scassandra instance that will accept connections: scassandra = TestUtils.createScassandraServer(); scassandra.start(); + ScassandraCluster.primeSystemLocalRow(scassandra); int port = scassandra.getBinaryPort(); // - the remaining 4 are fake servers that will throw connect timeouts: @@ -106,6 +109,8 @@ public void should_handle_failing_or_missing_contact_points() throws UnknownHost cluster = Cluster.builder() .withPort(scassandra.getBinaryPort()) + // scassandra supports max V4 protocol + .withProtocolVersion(ProtocolVersion.V4) .addContactPoints( ipOfNode(1), failingHosts.get(0).address, @@ -183,8 +188,7 @@ public void should_not_schedule_reconnections_before_init_complete() { new FakeHost(TestUtils.ipOfNode(0), 9042, THROWING_CONNECT_TIMEOUTS), new FakeHost(TestUtils.ipOfNode(1), 9042, THROWING_CONNECT_TIMEOUTS)); // Use a low reconnection interval and keep the default connect timeout (5 seconds). So if a - // reconnection was scheduled, - // we would see a call to the reconnection policy. + // reconnection was scheduled, we would see a call to the reconnection policy. CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(100)); Cluster cluster = diff --git a/driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java b/driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java index e7a62993b42..340b3f49376 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -174,9 +176,7 @@ private class CreateClusterAndCheckConnections CreateClusterAndCheckConnections(CountDownLatch startSignal) { this.startSignal = startSignal; this.cluster = - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() .withPoolingOptions( new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1)) .withNettyOptions(channelMonitor.nettyOptions()) diff --git a/driver-core/src/test/java/com/datastax/driver/core/ClusterWidePercentileTrackerTest.java b/driver-core/src/test/java/com/datastax/driver/core/ClusterWidePercentileTrackerTest.java index 57b28253522..7b5876b0c5a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ClusterWidePercentileTrackerTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ClusterWidePercentileTrackerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/CodecRegistryTest.java b/driver-core/src/test/java/com/datastax/driver/core/CodecRegistryTest.java index bbfe99a4bab..fae6ed77f44 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CodecRegistryTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CodecRegistryTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ColumnDefinitionsAssert.java b/driver-core/src/test/java/com/datastax/driver/core/ColumnDefinitionsAssert.java index be28488b8ad..f6ba1e401c6 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ColumnDefinitionsAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ColumnDefinitionsAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ColumnDefinitionsTest.java b/driver-core/src/test/java/com/datastax/driver/core/ColumnDefinitionsTest.java index 88da5cbd578..c584e2477c7 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ColumnDefinitionsTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ColumnDefinitionsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ColumnMetadataAssert.java b/driver-core/src/test/java/com/datastax/driver/core/ColumnMetadataAssert.java index 2aac944177e..68a00ec8851 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ColumnMetadataAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ColumnMetadataAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/CompressionTest.java b/driver-core/src/test/java/com/datastax/driver/core/CompressionTest.java index 8dc25c54a0c..e0b2d32c87e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CompressionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CompressionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ConditionChecker.java b/driver-core/src/test/java/com/datastax/driver/core/ConditionChecker.java index ba537d5c649..f9789f10abb 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ConditionChecker.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ConditionChecker.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java b/driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java index 7292e8889a0..4f29dd274c3 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ConnectionReleaseTest.java b/driver-core/src/test/java/com/datastax/driver/core/ConnectionReleaseTest.java index e785edddd5e..915d0898b46 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ConnectionReleaseTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ConnectionReleaseTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 +84,7 @@ public void should_release_connection_before_completing_future() throws Exceptio cluster = Cluster.builder() - .addContactPoints(hostAddress.getAddress()) + .addContactPoint(hostEndPoint) .withPort(scassandra.getBinaryPort()) .withPoolingOptions( new PoolingOptions() diff --git a/driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java b/driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java index 73e5610dc0a..78165b6a441 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java b/driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java index d3230177b37..90edb28b1d0 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/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, @@ -17,9 +19,12 @@ import static com.datastax.driver.core.Assertions.assertThat; import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; +import static com.datastax.driver.core.ScassandraCluster.SELECT_LOCAL; +import static com.datastax.driver.core.ScassandraCluster.SELECT_LOCAL_RPC_ADDRESS_AND_PORT; import static com.datastax.driver.core.ScassandraCluster.SELECT_PEERS; +import static com.datastax.driver.core.ScassandraCluster.SELECT_PEERS_DSE68; +import static com.datastax.driver.core.ScassandraCluster.SELECT_PEERS_V2; import static com.datastax.driver.core.ScassandraCluster.datacenter; -import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions; import static com.google.common.collect.Lists.newArrayList; import static org.scassandra.http.client.PrimingRequest.then; @@ -31,6 +36,8 @@ import com.datastax.driver.core.policies.ReconnectionPolicy; import com.datastax.driver.core.utils.CassandraVersion; import com.google.common.base.Function; +import com.google.common.base.Optional; +import com.google.common.collect.Collections2; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -42,12 +49,15 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Map; +import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.log4j.Level; +import org.scassandra.http.client.PrimingClient; import org.scassandra.http.client.PrimingRequest; +import org.scassandra.http.client.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.DataProvider; @@ -80,9 +90,7 @@ public void should_prevent_simultaneous_reconnection_attempts() throws Interrupt // this host Cluster cluster = register( - Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() .withReconnectionPolicy(reconnectionPolicy) .withLoadBalancingPolicy(loadBalancingPolicy) .build()); @@ -110,12 +118,7 @@ public void should_prevent_simultaneous_reconnection_attempts() throws Interrupt @CassandraVersion("2.1.0") public void should_parse_UDT_definitions_when_using_default_protocol_version() { // First driver instance: create UDT - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) - .build()); + Cluster cluster = register(createClusterBuilder().build()); Session session = cluster.connect(); session.execute( "create keyspace ks WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); @@ -123,12 +126,7 @@ public void should_parse_UDT_definitions_when_using_default_protocol_version() { cluster.close(); // Second driver instance: read UDT definition - Cluster cluster2 = - register( - Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) - .build()); + Cluster cluster2 = register(createClusterBuilder().build()); UserType fooType = cluster2.getMetadata().getKeyspace("ks").getUserType("foo"); assertThat(fooType.getFieldNames()).containsExactly("i"); @@ -147,18 +145,13 @@ public void should_parse_UDT_definitions_when_using_default_protocol_version() { @CCMConfig(numberOfNodes = 3) public void should_reestablish_if_control_node_decommissioned() throws InterruptedException { InetSocketAddress firstHost = ccm().addressOfNode(1); - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(firstHost.getAddress()) - .withPort(ccm().getBinaryPort()) - .withQueryOptions(nonDebouncingQueryOptions()) - .build()); + Cluster cluster = register(createClusterBuilderNoDebouncing().build()); cluster.init(); // Ensure the control connection host is that of the first node. - InetAddress controlHost = cluster.manager.controlConnection.connectedHost().getAddress(); - assertThat(controlHost).isEqualTo(firstHost.getAddress()); + InetSocketAddress controlHost = + cluster.manager.controlConnection.connectedHost().getEndPoint().resolve(); + assertThat(controlHost).isEqualTo(firstHost); // Decommission the node. ccm().decommission(1); @@ -205,7 +198,14 @@ public void should_randomize_contact_points_when_determining_control_connection( try { cluster.init(); - occurrencesByHost.add(cluster.manager.controlConnection.connectedHost().getAddress()); + occurrencesByHost.add( + cluster + .manager + .controlConnection + .connectedHost() + .getEndPoint() + .resolve() + .getAddress()); } finally { cluster.close(); } @@ -242,17 +242,17 @@ public Integer apply(InetAddress input) { @DataProvider public static Object[][] disallowedNullColumnsInPeerData() { return new Object[][] { - {"host_id", false, true}, + {"host_id", false, false}, // JAVA-2171: host_id does not require extended peer check anymore {"data_center", false, true}, {"rack", false, true}, {"tokens", false, true}, - {"host_id,data_center,rack,tokens", false, true}, + {"data_center,rack,tokens", false, true}, {"rpc_address", false, false}, - {"host_id", true, true}, + {"host_id", true, false}, {"data_center", true, true}, {"rack", true, true}, {"tokens", true, true}, - {"host_id,data_center,rack,tokens", true, true}, + {"data_center,rack,tokens", true, true}, {"native_address", true, false}, {"native_port", true, false}, {"native_address,native_port", true, false}, @@ -337,11 +337,17 @@ static void run_with_null_peer_info(String columns, boolean expectPeer2, boolean cluster.init(); InetAddress node2Address = scassandraCluster.address(2).getAddress(); + String invalidValues = + withPeersV2 + ? columnData + : String.format( + "missing native_transport_address, missing native_transport_port, missing native_transport_port_ssl, %s", + columnData); String expectedError = String.format( "Found invalid row in system.peers: [peer=%s, %s]. " + "This is likely a gossip or snitch issue, this host will be ignored.", - node2Address, columnData); + node2Address, invalidValues); String log = logs.get(); // then: A peer with a null rack should not show up in host metadata, unless allowed via // system property. @@ -408,7 +414,7 @@ public void should_fetch_whole_peers_table_if_broadcast_address_changed() new InetSocketAddress(InetAddress.getByName("1.2.3.4"), scassandras.getBinaryPort()); // host 2 has the old broadcast_address (which is identical to its rpc_broadcast_address) - assertThat(host2.getSocketAddress().getAddress()) + assertThat(host2.getEndPoint().resolve().getAddress()) .isEqualTo(node2OldBroadcastAddress.getAddress()); // simulate a change in host 2 public IP @@ -416,8 +422,13 @@ public void should_fetch_whole_peers_table_if_broadcast_address_changed() ImmutableMap.builder() .put( "peer", node2NewBroadcastAddress.getAddress()) // new broadcast address for host 2 - .put("rpc_address", host2.getAddress()) // rpc_broadcast_address remains unchanged - .put("host_id", UUID.randomUUID()) + .put( + "rpc_address", + host2 + .getEndPoint() + .resolve() + .getAddress()) // rpc_broadcast_address remains unchanged + .put("host_id", host2.getHostId()) .put("data_center", datacenter(1)) .put("rack", "rack1") .put("release_version", "2.1.8") @@ -460,7 +471,7 @@ public void should_fetch_whole_peers_table_if_broadcast_address_changed() .isEqualTo(node2NewBroadcastAddress.getAddress()); // host 2 should keep its old rpc broadcast address - assertThat(host2.getSocketAddress()).isEqualTo(node2RpcAddress); + assertThat(host2.getEndPoint().resolve()).isEqualTo(node2RpcAddress); } finally { cluster.close(); @@ -517,8 +528,8 @@ public void should_use_port_from_peers_v2_table(boolean sharedIP) { } else { assertThat(host).hasNoListenSocketAddress(); } - uniqueAddresses.add(host.getAddress()); - uniqueSocketAddresses.add(host.getSocketAddress()); + uniqueAddresses.add(host.getEndPoint().resolve().getAddress()); + uniqueSocketAddresses.add(host.getEndPoint().resolve()); } if (!sharedIP) { @@ -567,6 +578,338 @@ public void should_connect_when_peers_v2_table_not_present() { } } + /** + * Cassandra 4.0 supports native_address and native_port columns in system.peers_v2. We want to + * validate our ability to build correct metadata when drawing data from these tables. + */ + @Test(groups = "short") + @CCMConfig(createCcm = false) + public void should_extract_hosts_using_native_address_port_from_peersv2() + throws UnknownHostException { + + InetAddress expectedAddress = InetAddress.getByName("4.3.2.1"); + int expectedPort = 2409; + PeerRowState state = + PeerRowState.builder() + .peersV2("native_address", expectedAddress) + .peersV2("native_port", expectedPort) + .expectedAddress(expectedAddress) + .expectedPort(expectedPort) + .build(); + runPeerTest(state); + } + + /** DSE 6.8 includes native_transport_address and native_transport_port in system.peers. */ + @Test(groups = "short") + @CCMConfig(createCcm = false) + public void should_extract_hosts_using_native_transport_address_port_from_peers() + throws UnknownHostException { + + InetAddress expectedAddress = InetAddress.getByName("4.3.2.1"); + int expectedPort = 2409; + PeerRowState state = + PeerRowState.builder() + .peers("native_transport_address", expectedAddress) + .peers("native_transport_port", expectedPort) + .expectedAddress(expectedAddress) + .expectedPort(expectedPort) + .build(); + runPeerTest(state); + } + + /** + * If both native_transport_port and native_transport_port_ssl are present we expect the latter to + * be selected if the Cluster is created with SSL support (i.e. if {@link + * Cluster.Builder#withSSL()} is used). + */ + @Test(groups = "short", enabled = false /* Requires SSL support in scassandra */) + @CCMConfig(createCcm = false) + public void should_extract_hosts_using_native_transport_address_port_ssl_from_peers() + throws UnknownHostException { + + InetAddress expectedAddress = InetAddress.getByName("4.3.2.1"); + int expectedPort = 2409; + PeerRowState state = + PeerRowState.builder() + .peers("native_transport_address", expectedAddress) + .peers("native_transport_port", expectedPort - 100) + .peers("native_transport_port_ssl", expectedPort) + .expectedAddress(expectedAddress) + .expectedPort(expectedPort) + .build(); + runPeerTest(state); + } + + /** + * The default case. If we can't get native_address/port out of system.peers_v2 or + * native_transport_address/port out of system.peers the fall back to rpc_address + a default port + */ + @Test(groups = "short") + @CCMConfig(createCcm = false) + public void should_extract_hosts_using_rpc_address_from_peers() throws UnknownHostException { + + InetAddress expectedAddress = InetAddress.getByName("4.3.2.1"); + PeerRowState state = + PeerRowState.builder() + .peers("rpc_address", expectedAddress) + /* DefaultEndPointFactory isn't happy if we don't have a value for + * both peer and rpc_address */ + .peers("peer", InetAddress.getByName("1.2.3.4")) + .expectedAddress(expectedAddress) + .build(); + runPeerTest(state); + } + + @Test(groups = "short") + @CCMConfig(createCcm = false) + public void should_extract_hosts_port_using_rpc_port_from_local() throws UnknownHostException { + InetAddress expectedAddress = InetAddress.getByName("1.2.3.4"); + int expectedPort = 29042; + PeerRowState state = + PeerRowState.builder() + .local("rpc_address", expectedAddress) + .local("rpc_port", expectedPort) + .build(); + + ScassandraCluster scassandras = + ScassandraCluster.builder().withNodes(2).withPeersV2(state.usePeersV2()).build(); + scassandras.init(); + + Cluster cluster = null; + try { + scassandras.node(1).primingClient().clearAllPrimes(); + PrimingClient primingClient = scassandras.node(1).primingClient(); + primingClient.prime( + PrimingRequest.queryBuilder() + .withQuery("SELECT * FROM system.local WHERE key='local'") + .withThen( + then() + .withColumnTypes(SELECT_LOCAL_RPC_ADDRESS_AND_PORT) + .withRows(state.getLocalRow()) + .build()) + .build()); + cluster = + Cluster.builder() + .addContactPoints(scassandras.address(1).getAddress()) + .withPort(scassandras.getBinaryPort()) + .withNettyOptions(nonQuietClusterCloseOptions) + .build(); + cluster.connect(); + + assertThat(cluster.manager.getControlConnection().connectedHost().getBroadcastRpcAddress()) + .isEqualTo(new InetSocketAddress(expectedAddress, expectedPort)); + } finally { + if (cluster != null) cluster.close(); + scassandras.stop(); + } + } + + private void runPeerTest(PeerRowState state) { + + ScassandraCluster scassandras = + ScassandraCluster.builder().withNodes(2).withPeersV2(state.usePeersV2()).build(); + scassandras.init(); + + Cluster cluster = null; + try { + + scassandras.node(1).primingClient().clearAllPrimes(); + + PrimingClient primingClient = scassandras.node(1).primingClient(); + + /* Note that we always prime system.local; ControlConnection.refreshNodeAndTokenMap() gets angry + * if this is empty */ + primingClient.prime( + PrimingRequest.queryBuilder() + .withQuery("SELECT * FROM system.local WHERE key='local'") + .withThen(then().withColumnTypes(SELECT_LOCAL).withRows(state.getLocalRow()).build()) + .build()); + + if (state.shouldPrimePeers()) { + + primingClient.prime( + PrimingRequest.queryBuilder() + .withQuery("SELECT * FROM system.peers") + .withThen( + then() + .withColumnTypes(state.isDse68() ? SELECT_PEERS_DSE68 : SELECT_PEERS) + .withRows(state.getPeersRow()) + .build()) + .build()); + } + if (state.shouldPrimePeersV2()) { + + primingClient.prime( + PrimingRequest.queryBuilder() + .withQuery("SELECT * FROM system.peers_v2") + .withThen( + then().withColumnTypes(SELECT_PEERS_V2).withRows(state.getPeersV2Row()).build()) + .build()); + } else { + + /* Must return an error code in this case in order to trigger the driver's downgrade to system.peers */ + primingClient.prime( + PrimingRequest.queryBuilder() + .withQuery("SELECT * FROM system.peers_v2") + .withThen(then().withResult(Result.invalid).build())); + } + + cluster = + Cluster.builder() + .addContactPoints(scassandras.address(1).getAddress()) + .withPort(scassandras.getBinaryPort()) + .withNettyOptions(nonQuietClusterCloseOptions) + .build(); + cluster.connect(); + + Collection hostEndPoints = + Collections2.transform( + cluster.getMetadata().allHosts(), + new Function() { + public EndPoint apply(Host host) { + return host.getEndPoint(); + } + }); + assertThat(hostEndPoints).contains(state.getExpectedEndPoint(scassandras)); + } finally { + if (cluster != null) cluster.close(); + scassandras.stop(); + } + } + + static class PeerRowState { + + private final ImmutableMap peers; + private final ImmutableMap peersV2; + private final ImmutableMap local; + + private final InetAddress expectedAddress; + private final Optional expectedPort; + + private final boolean shouldPrimePeers; + private final boolean shouldPrimePeersV2; + + private PeerRowState( + ImmutableMap peers, + ImmutableMap peersV2, + ImmutableMap local, + InetAddress expectedAddress, + Optional expectedPort, + boolean shouldPrimePeers, + boolean shouldPrimePeersV2) { + this.peers = peers; + this.peersV2 = peersV2; + this.local = local; + + this.expectedAddress = expectedAddress; + this.expectedPort = expectedPort; + + this.shouldPrimePeers = shouldPrimePeers; + this.shouldPrimePeersV2 = shouldPrimePeersV2; + } + + public static Builder builder() { + return new Builder(); + } + + public boolean usePeersV2() { + return !this.peersV2.isEmpty(); + } + + public boolean isDse68() { + return this.peers.containsKey("native_transport_address") + || this.peers.containsKey("native_transport_port") + || this.peers.containsKey("native_transport_port_ssl"); + } + + public boolean shouldPrimePeers() { + return this.shouldPrimePeers; + } + + public boolean shouldPrimePeersV2() { + return this.shouldPrimePeersV2; + } + + public ImmutableMap getPeersRow() { + return this.peers; + } + + public ImmutableMap getPeersV2Row() { + return this.peersV2; + } + + public ImmutableMap getLocalRow() { + return this.local; + } + + public EndPoint getExpectedEndPoint(ScassandraCluster cluster) { + return new TranslatedAddressEndPoint( + new InetSocketAddress( + this.expectedAddress, this.expectedPort.or(cluster.getBinaryPort()))); + } + + static class Builder { + + private ImmutableMap.Builder peers = this.basePeerRow(); + private ImmutableMap.Builder peersV2 = this.basePeerRow(); + private ImmutableMap.Builder local = this.basePeerRow(); + + private InetAddress expectedAddress; + private Optional expectedPort = Optional.absent(); + + private boolean shouldPrimePeers = false; + private boolean shouldPrimePeersV2 = false; + + public PeerRowState build() { + return new PeerRowState( + this.peers.build(), + this.peersV2.build(), + this.local.build(), + this.expectedAddress, + this.expectedPort, + this.shouldPrimePeers, + this.shouldPrimePeersV2); + } + + public Builder peers(String name, Object val) { + this.peers.put(name, val); + this.shouldPrimePeers = true; + return this; + } + + public Builder peersV2(String name, Object val) { + this.peersV2.put(name, val); + this.shouldPrimePeersV2 = true; + return this; + } + + public Builder local(String name, Object val) { + this.local.put(name, val); + return this; + } + + public Builder expectedAddress(InetAddress address) { + this.expectedAddress = address; + return this; + } + + public Builder expectedPort(int port) { + this.expectedPort = Optional.of(port); + return this; + } + + private ImmutableMap.Builder basePeerRow() { + return ImmutableMap.builder() + /* Required to support Metadata.addIfAbsent(Host) which is used by host loading code */ + .put("host_id", UUID.randomUUID()) + /* Elements below required to pass peer row validation */ + .put("data_center", datacenter(1)) + .put("rack", "rack1") + .put("tokens", ImmutableSet.of(Long.toString(new Random().nextLong()))); + } + } + } + static class QueryPlanCountingPolicy extends DelegatingLoadBalancingPolicy { final AtomicInteger counter = new AtomicInteger(); @@ -575,6 +918,7 @@ public QueryPlanCountingPolicy(LoadBalancingPolicy delegate) { super(delegate); } + @Override public Iterator newQueryPlan(String loggedKeyspace, Statement statement) { counter.incrementAndGet(); return super.newQueryPlan(loggedKeyspace, statement); diff --git a/driver-core/src/test/java/com/datastax/driver/core/CountingReconnectionPolicy.java b/driver-core/src/test/java/com/datastax/driver/core/CountingReconnectionPolicy.java index 895f3b125d0..d5457421e0f 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CountingReconnectionPolicy.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CountingReconnectionPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/CreateCCM.java b/driver-core/src/test/java/com/datastax/driver/core/CreateCCM.java index d3de15662ac..82c71468d72 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CreateCCM.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CreateCCM.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/CustomPayloadTest.java b/driver-core/src/test/java/com/datastax/driver/core/CustomPayloadTest.java index 0497ad3e60f..4509d51eb03 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CustomPayloadTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CustomPayloadTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/CustomPercentileTrackerTest.java b/driver-core/src/test/java/com/datastax/driver/core/CustomPercentileTrackerTest.java index 443a8e97f71..7c714a9acc7 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CustomPercentileTrackerTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CustomPercentileTrackerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/CustomTypeTest.java b/driver-core/src/test/java/com/datastax/driver/core/CustomTypeTest.java index 264f10b8bee..50f0015acc3 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/CustomTypeTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/CustomTypeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/DataProviders.java b/driver-core/src/test/java/com/datastax/driver/core/DataProviders.java index 58094a52443..ea9897e5546 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/DataProviders.java +++ b/driver-core/src/test/java/com/datastax/driver/core/DataProviders.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/DataTypeAssert.java b/driver-core/src/test/java/com/datastax/driver/core/DataTypeAssert.java index 04f14eb3353..3998d8d89fa 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/DataTypeAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/DataTypeAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/DataTypeClassNameParserTest.java b/driver-core/src/test/java/com/datastax/driver/core/DataTypeClassNameParserTest.java index 123314405f5..2f317971c0a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/DataTypeClassNameParserTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/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, diff --git a/driver-core/src/test/java/com/datastax/driver/core/DataTypeCqlNameParserTest.java b/driver-core/src/test/java/com/datastax/driver/core/DataTypeCqlNameParserTest.java index 5a39b4becdd..5013707423c 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/DataTypeCqlNameParserTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/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/driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java index c30bbd930fe..01742647891 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java b/driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java index 7c08f7e26f7..cdf3583fbf1 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/DataTypeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/DelegatingClusterIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/DelegatingClusterIntegrationTest.java index 14b3f0444fd..07415dd4c76 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/DelegatingClusterIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/DelegatingClusterIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/DelegatingClusterTest.java b/driver-core/src/test/java/com/datastax/driver/core/DelegatingClusterTest.java index 0bee5ec9a8d..430aa5953e9 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/DelegatingClusterTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/DelegatingClusterTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/DirectCompressionTest.java b/driver-core/src/test/java/com/datastax/driver/core/DirectCompressionTest.java index 6bfa4a93618..ea4bd82ad38 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/DirectCompressionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/DirectCompressionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 @@ public class DirectCompressionTest extends CompressionTest { */ @Test(groups = "short") public void should_function_with_snappy_compression() throws Exception { + skipTestWithCassandraVersionOrHigher("4.0.0", "snappy"); compressionTest(ProtocolOptions.Compression.SNAPPY); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/DirectedGraphTest.java b/driver-core/src/test/java/com/datastax/driver/core/DirectedGraphTest.java index 4dcb6fb50b4..9cf804fa83a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/DirectedGraphTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/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/driver-core/src/test/java/com/datastax/driver/core/DseCCMClusterTest.java b/driver-core/src/test/java/com/datastax/driver/core/DseCCMClusterTest.java index ff47b6a652f..5460ae48e9c 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/DseCCMClusterTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/DseCCMClusterTest.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/driver-core/src/test/java/com/datastax/driver/core/DurationCodecTest.java b/driver-core/src/test/java/com/datastax/driver/core/DurationCodecTest.java index 53e1c316a0a..181dd044084 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/DurationCodecTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/DurationCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/DurationIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/DurationIntegrationTest.java index 50dcf9b11e1..16f6a20e15c 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/DurationIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/DurationIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/DurationTest.java b/driver-core/src/test/java/com/datastax/driver/core/DurationTest.java index c17f6cb4ce9..d5649483612 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/DurationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/DurationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/EndPoints.java b/driver-core/src/test/java/com/datastax/driver/core/EndPoints.java new file mode 100644 index 00000000000..2154d1884f1 --- /dev/null +++ b/driver-core/src/test/java/com/datastax/driver/core/EndPoints.java @@ -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. + */ +package com.datastax.driver.core; + +import java.net.InetSocketAddress; + +/** + * Utility class to create endpoints in tests. This serves mainly as a hook to access + * package-private classes. + */ +public class EndPoints { + + public static EndPoint forAddress(InetSocketAddress address) { + return new TranslatedAddressEndPoint(address); + } + + public static EndPoint forAddress(String host, int port) { + return forAddress(new InetSocketAddress(host, port)); + } +} diff --git a/driver-core/src/test/java/com/datastax/driver/core/EventDebouncerIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/EventDebouncerIntegrationTest.java index d72bc2a2d07..0d4e81be899 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/EventDebouncerIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/EventDebouncerIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,12 +49,7 @@ public void should_wait_until_load_balancing_policy_is_fully_initialized() throws InterruptedException { TestLoadBalancingPolicy policy = new TestLoadBalancingPolicy(); final Cluster cluster = - register( - createClusterBuilderNoDebouncing() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) - .withLoadBalancingPolicy(policy) - .build()); + register(createClusterBuilderNoDebouncing().withLoadBalancingPolicy(policy).build()); new Thread() { @Override public void run() { @@ -133,7 +130,8 @@ public void init(Cluster cluster, Collection hosts) { public void onDown(Host host) { if (!init) onDownCalledBeforeInit = true; super.onDown(host); - if (host.getAddress().toString().contains(ipOfNode(3))) onDownCalled.countDown(); + if (host.getEndPoint().resolve().getAddress().toString().contains(ipOfNode(3))) + onDownCalled.countDown(); } void stop() throws InterruptedException { diff --git a/driver-core/src/test/java/com/datastax/driver/core/EventDebouncerTest.java b/driver-core/src/test/java/com/datastax/driver/core/EventDebouncerTest.java index a9f70620ec8..f45ed0a8c47 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/EventDebouncerTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/EventDebouncerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ExportAsStringTest.java b/driver-core/src/test/java/com/datastax/driver/core/ExportAsStringTest.java index beae645ea8b..934bfba791f 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ExportAsStringTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ExportAsStringTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,12 +23,12 @@ import com.datastax.driver.core.schemabuilder.SchemaBuilder; import com.datastax.driver.core.utils.CassandraVersion; import com.google.common.collect.ImmutableMap; -import com.google.common.io.ByteStreams; import com.google.common.io.Closer; -import java.io.ByteArrayOutputStream; +import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; -import java.io.PrintStream; +import java.io.InputStreamReader; +import java.io.StringWriter; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -146,7 +148,7 @@ public void should_create_schema_and_ensure_exported_cql_is_as_expected() { // matter, alphabetical does. session.execute( "CREATE MATERIALIZED VIEW cyclist_by_r_age " - + "AS SELECT age, birthday, name, country " + + "AS SELECT cid, age, birthday, name, country " + "FROM cyclist_mv " + "WHERE age IS NOT NULL AND cid IS NOT NULL " + "PRIMARY KEY (age, cid) " @@ -163,7 +165,7 @@ public void should_create_schema_and_ensure_exported_cql_is_as_expected() { // A materialized view for cyclist_mv, select columns session.execute( "CREATE MATERIALIZED VIEW cyclist_by_age " - + "AS SELECT age, birthday, name, country " + + "AS SELECT cid, age, birthday, name, country " + "FROM cyclist_mv " + "WHERE age IS NOT NULL AND cid IS NOT NULL " + "PRIMARY KEY (age, cid) WITH comment = 'simple view'"); @@ -225,8 +227,15 @@ public void should_create_schema_and_ensure_exported_cql_is_as_expected() { } private String getExpectedCqlString() { - String majorMinor = - ccm().getCassandraVersion().getMajor() + "." + ccm().getCassandraVersion().getMinor(); + VersionNumber cassandraVersion = ccm().getCassandraVersion(); + VersionNumber dseVersion = ccm().getDSEVersion(); + String majorMinor; + if (dseVersion != null && dseVersion.getMajor() == 6 && dseVersion.getMinor() < 8) { + // DSE 6.0 and 6.7 report C* 4.0 but in reality it is C* 3.11 + majorMinor = "3.11"; + } else { + majorMinor = cassandraVersion.getMajor() + "." + cassandraVersion.getMinor(); + } String resourceName = "/export_as_string_test_" + majorMinor + ".cql"; Closer closer = Closer.create(); @@ -239,10 +248,19 @@ private String getExpectedCqlString() { + ")") .isNotNull(); closer.register(is); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PrintStream ps = new PrintStream(baos); - ByteStreams.copy(is, ps); - return baos.toString().trim(); + + BufferedReader in = new BufferedReader(new InputStreamReader(is)); + StringWriter out = new StringWriter(); + + String line; + while ((line = in.readLine()) != null) { + + String trimmedLine = line.trim(); + if (trimmedLine.startsWith("/*") || trimmedLine.startsWith("*")) continue; + out.write(line); + out.write(System.getProperty("line.separator")); + } + return out.toString().trim(); } catch (IOException e) { logger.warn("Failure to read {}", resourceName, e); fail("Unable to read " + resourceName + " is it defined?"); diff --git a/driver-core/src/test/java/com/datastax/driver/core/ExtendedPeerCheckDisabledTest.java b/driver-core/src/test/java/com/datastax/driver/core/ExtendedPeerCheckDisabledTest.java index 145234fa3a4..b4b8c7ed4f7 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ExtendedPeerCheckDisabledTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ExtendedPeerCheckDisabledTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/FakeHost.java b/driver-core/src/test/java/com/datastax/driver/core/FakeHost.java index 26bd956b8ae..4dd70a541a8 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/FakeHost.java +++ b/driver-core/src/test/java/com/datastax/driver/core/FakeHost.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/FetchingTest.java b/driver-core/src/test/java/com/datastax/driver/core/FetchingTest.java index a8cb1acf164..78a86126e22 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/FetchingTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/FetchingTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/FrameLengthTest.java b/driver-core/src/test/java/com/datastax/driver/core/FrameLengthTest.java index 7258f76d5f8..9d799e274b7 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/FrameLengthTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/FrameLengthTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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.driver.core.querybuilder.Insert; import com.datastax.driver.core.schemabuilder.Create; import com.datastax.driver.core.schemabuilder.SchemaBuilder; +import com.datastax.driver.core.utils.CassandraVersion; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Random; @@ -105,22 +108,42 @@ public void onTestContextInitialized() { */ @Test(groups = "isolated") public void should_throw_exception_when_frame_exceeds_configured_max() { + skipTestWithCassandraVersionOrHigher("4.0.0", "frame-size exceeding with default-protocol"); + run_frame_size_exceeding_queries(session()); + } + + /** + * With cassandra 4.0.0+, V5 protocol is default which breaks requests into segments. Force V4 + * protocol to allow us to test frame-size limitation code. + */ + @CassandraVersion("4.0.0") + @Test(groups = "isolated") + public void should_throw_exception_when_frame_exceeds_configured_max_v4_protocol_cassandra4() { + Cluster cluster = + register(createClusterBuilder().withProtocolVersion(ProtocolVersion.V4).build()); + Session session = register(cluster.connect()); + useKeyspace(session, keyspace); + + run_frame_size_exceeding_queries(session); + } + + private void run_frame_size_exceeding_queries(Session session) { try { - session().execute(select().from(tableName).where(eq("k", 0))); + session.execute(select().from(tableName).where(eq("k", 0))); fail("Exception expected"); } catch (FrameTooLongException ftle) { // Expected. } // Both hosts should remain up. - Collection hosts = session().getState().getConnectedHosts(); + Collection hosts = session.getState().getConnectedHosts(); assertThat(hosts).hasSize(2).extractingResultOf("isUp").containsOnly(true); // Should be able to make a query that is less than the max frame size. // Execute multiple time to exercise all hosts. for (int i = 0; i < 10; i++) { ResultSet result = - session().execute(select().from(tableName).where(eq("k", 0)).and(eq("c", 0))); + session.execute(select().from(tableName).where(eq("k", 0)).and(eq("c", 0))); assertThat(result.getAvailableWithoutFetching()).isEqualTo(1); } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/FunctionMetadataAssert.java b/driver-core/src/test/java/com/datastax/driver/core/FunctionMetadataAssert.java index 67aab486302..93ebce19045 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/FunctionMetadataAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/FunctionMetadataAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/FunctionMetadataTest.java b/driver-core/src/test/java/com/datastax/driver/core/FunctionMetadataTest.java index 2e2d8617ba7..1aebf53e315 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/FunctionMetadataTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/FunctionMetadataTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/GettableDataIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/GettableDataIntegrationTest.java index 5872746cd61..38d77520e4e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/GettableDataIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/GettableDataIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 onTestContextInitialized() { @Override public Cluster.Builder createClusterBuilder() { - return Cluster.builder().withCodecRegistry(registry); + return super.createClusterBuilder().withCodecRegistry(registry); } @BeforeClass(groups = "short") diff --git a/driver-core/src/test/java/com/datastax/driver/core/HeapCompressionTest.java b/driver-core/src/test/java/com/datastax/driver/core/HeapCompressionTest.java index d27309eee4f..e330f4bf70f 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/HeapCompressionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/HeapCompressionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,6 +39,7 @@ public void beforeTestClass() throws Exception { */ @Test(groups = "isolated") public void should_function_with_snappy_compression() throws Exception { + skipTestWithCassandraVersionOrHigher("4.0.0", "snappy"); compressionTest(ProtocolOptions.Compression.SNAPPY); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java b/driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java index c4de31642ef..c38600ef16e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -65,7 +67,7 @@ public void stopCapturingLogs() { public void should_send_heartbeat_when_connection_is_inactive() throws InterruptedException { Cluster cluster = Cluster.builder() - .addContactPoints(hostAddress.getAddress()) + .addContactPoint(hostEndPoint) .withPort(scassandra.getBinaryPort()) .withPoolingOptions(new PoolingOptions().setHeartbeatIntervalSeconds(3)) .build(); @@ -156,7 +158,7 @@ public void should_send_heartbeat_when_requests_being_written_but_nothing_receiv throws Exception { Cluster cluster = Cluster.builder() - .addContactPoints(hostAddress.getAddress()) + .addContactPoint(hostEndPoint) .withPort(scassandra.getBinaryPort()) .withPoolingOptions( new PoolingOptions() @@ -264,7 +266,7 @@ public void run() { public void should_not_send_heartbeat_when_disabled() throws InterruptedException { Cluster cluster = Cluster.builder() - .addContactPoints(hostAddress.getAddress()) + .addContactPoint(hostEndPoint) .withPort(scassandra.getBinaryPort()) .withPoolingOptions(new PoolingOptions().setHeartbeatIntervalSeconds(0)) .build(); diff --git a/driver-core/src/test/java/com/datastax/driver/core/HostAssert.java b/driver-core/src/test/java/com/datastax/driver/core/HostAssert.java index 381a5c49735..c0ea4b73ac0 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/HostAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -188,7 +190,7 @@ public HostAssert hasNoDseGraph() { } public HostAssert hasSocketAddress(InetSocketAddress address) { - assertThat(actual.getSocketAddress()).isNotNull().isEqualTo(address); + assertThat(actual.getEndPoint().resolve()).isNotNull().isEqualTo(address); return this; } diff --git a/driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolMultiTest.java b/driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolMultiTest.java index 831fa79c583..f5469a0be02 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolMultiTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolMultiTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java b/driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java index cad07e2ce27..b68a9a9263e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -798,7 +800,7 @@ public void should_trash_on_returning_connection_with_insufficient_streams() thr // On returning of the connection, should detect that there are no available streams and trash // it. assertThat(pool.trash).hasSize(0); - pool.returnConnection(extra1); + pool.returnConnection(extra1, false); assertThat(pool.trash).hasSize(1); } finally { MockRequest.completeAll(allRequests); diff --git a/driver-core/src/test/java/com/datastax/driver/core/HostMetadataIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/HostMetadataIntegrationTest.java index 6d08b3f70b1..019d775f434 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/HostMetadataIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/HostMetadataIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/HostTargetingTest.java b/driver-core/src/test/java/com/datastax/driver/core/HostTargetingTest.java index fcaa3dafc15..de777ce4147 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/HostTargetingTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/HostTargetingTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 @@ public class HostTargetingTest { new Predicate() { @Override public boolean apply(Host host) { - return !host.getAddress().getHostAddress().endsWith("4"); + return !host.getEndPoint().resolve().getAddress().getHostAddress().endsWith("4"); } })); @@ -70,8 +72,12 @@ public void setUp() { @AfterMethod(groups = "short") public void tearDown() { - cluster.close(); - sCluster.stop(); + if (cluster != null) { + cluster.close(); + } + if (sCluster != null) { + sCluster.stop(); + } } private void verifyNoLbpInteractions() { diff --git a/driver-core/src/test/java/com/datastax/driver/core/IndexMetadataAssert.java b/driver-core/src/test/java/com/datastax/driver/core/IndexMetadataAssert.java index 3cc95250247..ab3d49cc7c6 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/IndexMetadataAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/IndexMetadataAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java b/driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java index 3fc7ce4c12d..fce604b3e1b 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/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/driver-core/src/test/java/com/datastax/driver/core/Jdk8SSLEncryptionTest.java b/driver-core/src/test/java/com/datastax/driver/core/Jdk8SSLEncryptionTest.java index 47b3805b532..3df510c7546 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/Jdk8SSLEncryptionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/Jdk8SSLEncryptionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/KeyspaceMetadataAssert.java b/driver-core/src/test/java/com/datastax/driver/core/KeyspaceMetadataAssert.java index 93c40da31b3..87b5810455e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/KeyspaceMetadataAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/KeyspaceMetadataAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java b/driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java index 449c25bff30..ab1c6c34120 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyBootstrapTest.java b/driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyBootstrapTest.java index 26e319bb28e..4d1bd8336f6 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyBootstrapTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyBootstrapTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -52,21 +54,18 @@ public class LoadBalancingPolicyBootstrapTest extends CCMTestsSupport { public void should_init_policy_with_up_contact_points() throws Exception { HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy()); - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withLoadBalancingPolicy(policy) - .build()); + Cluster cluster = register(createClusterBuilder().withLoadBalancingPolicy(policy).build()); try { cluster.init(); + // To support astra, only hosts in Metadata#getContactPoints are passed to init() + // TestUtils#configureClusterBuilder only uses the first host as the contact point + // Remaining hosts are learned after connection via onAdd() assertThat(policy.history) .containsOnly( entry(INIT, TestUtils.findHost(cluster, 1)), - entry(INIT, TestUtils.findHost(cluster, 2))); + entry(ADD, TestUtils.findHost(cluster, 2))); } finally { cluster.close(); } @@ -102,12 +101,14 @@ public void should_send_down_notifications_after_init_when_contact_points_are_do ccm().stop(nodeToStop); ccm().waitForDown(nodeToStop); + // usually only one contact point is used to build the test cluster + // here we explicitly add both endpoints so we can test load + // balancing initial connection when the first connection point is down HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy()); Cluster cluster = register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() + .addContactPoints(ccm().getContactPoints().get(1)) .withLoadBalancingPolicy(policy) .build()); diff --git a/driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyRefreshTest.java b/driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyRefreshTest.java index 16deec726c2..e1829a65558 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyRefreshTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyRefreshTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,33 +43,43 @@ public void changeTheHost(Host theNewHost) { cluster.getConfiguration().getPoolingOptions().refreshConnectedHosts(); } + @Override public void init(Cluster cluster, Collection hosts) { this.cluster = cluster; try { for (Host h : hosts) - if (h.getAddress().equals(InetAddress.getByName(TestUtils.IP_PREFIX + '1'))) - this.theHost = h; + if (h.getEndPoint() + .resolve() + .getAddress() + .equals(InetAddress.getByName(TestUtils.IP_PREFIX + '1'))) this.theHost = h; } catch (Exception e) { throw new RuntimeException(e); } } + @Override public HostDistance distance(Host host) { return host == theHost ? HostDistance.LOCAL : HostDistance.IGNORED; } + @Override public Iterator newQueryPlan(String loggedKeyspace, Statement statement) { return Iterators.singletonIterator(theHost); } + @Override public void onAdd(Host h) {} + @Override public void onRemove(Host h) {} + @Override public void onUp(Host h) {} + @Override public void onDown(Host h) {} + @Override public void close() {} } @@ -77,7 +89,7 @@ public void refreshTest() throws Throwable { // Ugly Host[] hosts = new Host[2]; for (Host h : cluster().getMetadata().getAllHosts()) { - if (h.getAddress().equals(ccm().addressOfNode(1).getAddress())) hosts[0] = h; + if (h.getEndPoint().resolve().equals(ccm().addressOfNode(1))) hosts[0] = h; else hosts[1] = h; } diff --git a/driver-core/src/test/java/com/datastax/driver/core/LocalDateAssert.java b/driver-core/src/test/java/com/datastax/driver/core/LocalDateAssert.java index 4bfa602e76a..78b3871b8e7 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/LocalDateAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/LocalDateAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/LocalDateTest.java b/driver-core/src/test/java/com/datastax/driver/core/LocalDateTest.java index 9ee532ebeaf..474039664af 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/LocalDateTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/LocalDateTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/M3PTokenFactoryTest.java b/driver-core/src/test/java/com/datastax/driver/core/M3PTokenFactoryTest.java index dfde8c1c97e..2e8c79f13be 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/M3PTokenFactoryTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/M3PTokenFactoryTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/M3PTokenIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/M3PTokenIntegrationTest.java index b20077f4048..78ae9019b01 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/M3PTokenIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/M3PTokenIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/M3PTokenVnodeIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/M3PTokenVnodeIntegrationTest.java index 4bd0a467dfa..9d5b027588a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/M3PTokenVnodeIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/M3PTokenVnodeIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/MappingCodec.java b/driver-core/src/test/java/com/datastax/driver/core/MappingCodec.java index d1edfbff503..e734d85b572 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/MappingCodec.java +++ b/driver-core/src/test/java/com/datastax/driver/core/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/driver-core/src/test/java/com/datastax/driver/core/MaterializedViewMetadataAssert.java b/driver-core/src/test/java/com/datastax/driver/core/MaterializedViewMetadataAssert.java index 1ad9fb42372..7df2630e59e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/MaterializedViewMetadataAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/MaterializedViewMetadataAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/MaterializedViewMetadataTest.java b/driver-core/src/test/java/com/datastax/driver/core/MaterializedViewMetadataTest.java index 3fef2c72a1b..404a6b5f7d6 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/MaterializedViewMetadataTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/MaterializedViewMetadataTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/MemoryAppender.java b/driver-core/src/test/java/com/datastax/driver/core/MemoryAppender.java index 7a43ce998f8..ecdad298355 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/MemoryAppender.java +++ b/driver-core/src/test/java/com/datastax/driver/core/MemoryAppender.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/MetadataTest.java b/driver-core/src/test/java/com/datastax/driver/core/MetadataTest.java index 178f4f3f780..d6a5fccf783 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/MetadataTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/MetadataTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 +19,6 @@ import static com.datastax.driver.core.Assertions.assertThat; import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; -import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; import static com.datastax.driver.core.TestUtils.waitForUp; import com.google.common.collect.Maps; @@ -57,13 +58,7 @@ public class MetadataTest extends CCMTestsSupport { @Test(groups = "long") @CCMConfig(numberOfNodes = 3, dirtiesContext = true, createCluster = false) public void should_update_metadata_on_topology_change() { - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) - .withQueryOptions(nonDebouncingQueryOptions()) - .build()); + Cluster cluster = register(createClusterBuilderNoDebouncing().build()); Session session = cluster.connect(); String keyspace = "test"; @@ -170,6 +165,12 @@ public void escapeId_should_quote_reserved_cql_keywords() { assertThat(Metadata.quoteIfNecessary("columnfamily")).isEqualTo("\"columnfamily\""); } + /** @jira_ticket JAVA-2174 */ + @Test(groups = "unit") + public void escapeId_should_quote_empty_keyword() { + assertThat(Metadata.quoteIfNecessary("")).isEqualTo("\"\""); + } + @Test(groups = "unit") public void should_detect_reserved_keywords_in_upper_case() { assertThat(Metadata.isReservedCqlKeyword("COLUMNFAMILY")).isTrue(); diff --git a/driver-core/src/test/java/com/datastax/driver/core/MetricsInFlightTest.java b/driver-core/src/test/java/com/datastax/driver/core/MetricsInFlightTest.java index de667549641..2bb72a36710 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/MetricsInFlightTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/MetricsInFlightTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java b/driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java index ead5fd52cd9..bed176f9206 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 @@ public class MetricsTest extends CCMTestsSupport { @Override public Cluster.Builder createClusterBuilder() { - return Cluster.builder() + return super.createClusterBuilder() .withRetryPolicy( new RetryPolicy() { @Override @@ -141,13 +143,7 @@ public void should_enable_metrics_and_jmx_by_default() throws Exception { */ @Test(groups = "short", expectedExceptions = InstanceNotFoundException.class) public void metrics_should_be_null_when_metrics_disabled() throws Exception { - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withoutMetrics() - .build()); + Cluster cluster = register(createClusterBuilder().withoutMetrics().build()); try { cluster.init(); assertThat(cluster.getMetrics()).isNull(); @@ -169,13 +165,7 @@ public void metrics_should_be_null_when_metrics_disabled() throws Exception { */ @Test(groups = "short", expectedExceptions = InstanceNotFoundException.class) public void should_be_no_jmx_mbean_when_jmx_is_disabled() throws Exception { - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withoutJMXReporting() - .build()); + Cluster cluster = register(createClusterBuilder().withoutJMXReporting().build()); try { cluster.init(); assertThat(cluster.getMetrics()).isNotNull(); diff --git a/driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java b/driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java index 68b4fecc15e..0695553fca1 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,12 +42,7 @@ public class MissingRpcAddressTest extends CCMTestsSupport { public void testMissingRpcAddressAtStartup() throws Exception { deleteNode2RpcAddressFromNode1(); // Use only one contact point to make sure that the control connection is on node1 - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) - .build()); + Cluster cluster = register(createClusterBuilder().build()); cluster.connect(); // Since node2's RPC address is unknown on our control host, it should have been ignored @@ -58,9 +55,7 @@ private void deleteNode2RpcAddressFromNode1() throws Exception { InetSocketAddress firstHost = ccm().addressOfNode(1); Cluster cluster = register( - Cluster.builder() - .addContactPoints(firstHost.getAddress()) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() // ensure we will only connect to node1 .withLoadBalancingPolicy( new WhiteListPolicy( @@ -72,6 +67,14 @@ private void deleteNode2RpcAddressFromNode1() throws Exception { "DELETE rpc_address FROM system.peers WHERE peer = '%s'", ccm().addressOfNode(2).getHostName()); session.execute(deleteStmt); + // For Cassandra 4.0, we also need to remove the info from peers_v2 + if (ccm().getCassandraVersion().nextStable().compareTo(VersionNumber.parse("4.0")) >= 0) { + deleteStmt = + String.format( + "DELETE native_address, native_port FROM system.peers_v2 WHERE peer = '%s' and peer_port = %d", + ccm().addressOfNode(2).getHostName(), ccm().getStoragePort()); + session.execute(deleteStmt); + } session.close(); cluster.close(); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/MockClocks.java b/driver-core/src/test/java/com/datastax/driver/core/MockClocks.java index 171a62abba7..03ad9702ffb 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/MockClocks.java +++ b/driver-core/src/test/java/com/datastax/driver/core/MockClocks.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/NativeTest.java b/driver-core/src/test/java/com/datastax/driver/core/NativeTest.java index e6437d1a019..cc0398319f4 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/NativeTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/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/driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java b/driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java index 321c2878369..65db81694a8 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,9 +75,7 @@ public Object answer(InvocationOnMock invocation) throws Throwable { .afterChannelInitialized(any(SocketChannel.class)); Cluster cluster = register( - Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() .withPoolingOptions( new PoolingOptions() .setConnectionsPerHost( diff --git a/driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java b/driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java index 00a44923c1d..ec895922d59 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/NodeListRefreshDebouncerTest.java b/driver-core/src/test/java/com/datastax/driver/core/NodeListRefreshDebouncerTest.java index b7445259f1a..99f99ccd86a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/NodeListRefreshDebouncerTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/NodeListRefreshDebouncerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -42,13 +44,7 @@ public void setup() { queryOptions.setMaxPendingRefreshNodeListRequests(5); queryOptions.setRefreshSchemaIntervalMillis(0); // Create a separate cluster that will receive the schema events on its control connection. - cluster2 = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withQueryOptions(queryOptions) - .build()); + cluster2 = register(createClusterBuilder().withQueryOptions(queryOptions).build()); cluster2.init(); diff --git a/driver-core/src/test/java/com/datastax/driver/core/NodeRefreshDebouncerTest.java b/driver-core/src/test/java/com/datastax/driver/core/NodeRefreshDebouncerTest.java index 9142290ff15..0fe4b3d5145 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/NodeRefreshDebouncerTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/NodeRefreshDebouncerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,8 +22,8 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; +import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import org.mockito.ArgumentCaptor; import org.testng.annotations.Test; @@ -31,8 +33,8 @@ public class NodeRefreshDebouncerTest extends CCMTestsSupport { /** * Ensures that when a new node is bootstrapped into the cluster, stopped, and then subsequently - * started within {@link QueryOptions#setRefreshNodeIntervalMillis(int)} that an 'onAdd' event - * event is the only one processed and that the {@link Host} is marked up. + * started within {@link QueryOptions#setRefreshNodeIntervalMillis(int)}, then an 'onAdd' event is + * emitted and the {@link Host} is marked up. * *

Since NEW_NODE_DELAY_SECONDS is typically configured with a high value (60 seconds default * in the maven profile) this test can take a very long time. @@ -45,13 +47,7 @@ public void should_call_onAdd_with_bootstrap_stop_start() { int refreshNodeInterval = 30000; QueryOptions queryOptions = new QueryOptions().setRefreshNodeIntervalMillis(refreshNodeInterval); - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) - .withQueryOptions(queryOptions) - .build()); + Cluster cluster = register(createClusterBuilder().withQueryOptions(queryOptions).build()); cluster.connect(); Host.StateListener listener = mock(Host.StateListener.class); cluster.register(listener); @@ -62,16 +58,23 @@ public void should_call_onAdd_with_bootstrap_stop_start() { ArgumentCaptor captor = forClass(Host.class); - // Only register and onAdd should be called, since stop and start should be discarded. verify(listener).onRegister(cluster); long addDelay = refreshNodeInterval + TimeUnit.MILLISECONDS.convert(Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS); verify(listener, timeout(addDelay)).onAdd(captor.capture()); - verifyNoMoreInteractions(listener); - // The hosts state should be UP. - assertThat(captor.getValue().getState()).isEqualTo("UP"); + // The host should eventually come UP + final Host host = captor.getValue(); + ConditionChecker.check() + .that( + new Callable() { + @Override + public Boolean call() { + return host.getState().equals("UP"); + } + }) + .becomesTrue(); assertThat(cluster).host(2).hasState(Host.State.UP); } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/NowInSecondsTest.java b/driver-core/src/test/java/com/datastax/driver/core/NowInSecondsTest.java new file mode 100644 index 00000000000..9568479678c --- /dev/null +++ b/driver-core/src/test/java/com/datastax/driver/core/NowInSecondsTest.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.driver.core; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.datastax.driver.core.utils.CassandraVersion; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +@CassandraVersion("4.0") +public class NowInSecondsTest extends CCMTestsSupport { + + private static final String WRITE_QUERY = "INSERT INTO test (k,v) VALUES (1,1) USING TTL 20"; + private static final Statement READ_STATEMENT = + new SimpleStatement("SELECT TTL(v) FROM test WHERE k = 1"); + + @Override + public Cluster.Builder createClusterBuilder() { + return super.createClusterBuilder().allowBetaProtocolVersion(); + } + + @BeforeMethod(groups = "short") + public void setup() { + execute("DROP TABLE IF EXISTS test", "CREATE TABLE test(k int PRIMARY KEY, v int)"); + } + + @Test(groups = "short") + public void should_use_now_in_seconds_with_simple_statement() { + should_use_now_in_seconds(new SimpleStatement(WRITE_QUERY)); + } + + @Test(groups = "short") + public void should_use_now_in_seconds_with_bound_statement() { + PreparedStatement preparedStatement = session().prepare(WRITE_QUERY); + should_use_now_in_seconds(preparedStatement.bind()); + } + + @Test(groups = "short") + public void should_use_now_in_seconds_with_batch_statement() { + should_use_now_in_seconds( + new BatchStatement(BatchStatement.Type.LOGGED).add(new SimpleStatement(WRITE_QUERY))); + } + + private void should_use_now_in_seconds(Statement writeStatement) { + // When + // insert at t = 0 with TTL 20 + session().execute(writeStatement.setNowInSeconds(0)); + // read TTL at t = 10 + ResultSet rs = session().execute(READ_STATEMENT.setNowInSeconds(10)); + int remainingTtl = rs.one().getInt(0); + + // Then + assertThat(remainingTtl).isEqualTo(10); + } +} diff --git a/driver-core/src/test/java/com/datastax/driver/core/OPPTokenFactoryTest.java b/driver-core/src/test/java/com/datastax/driver/core/OPPTokenFactoryTest.java index adae7ff8240..acad71557e3 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/OPPTokenFactoryTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/OPPTokenFactoryTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 static org.assertj.core.api.Assertions.assertThat; +import com.datastax.driver.core.utils.Bytes; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.List; @@ -46,17 +49,12 @@ public void should_split_range_producing_empty_splits_near_ring_end() { } @Test(groups = "unit") - public void should_strip_trailing_0_bytes() { - Token with0Bytes = token(ByteBuffer.wrap(new byte[] {4, 0, 0, 0})); - Token without0Bytes = token(ByteBuffer.wrap(new byte[] {4})); - Token fromStringWith0Bytes = factory.fromString("040000"); - - assertThat(with0Bytes).isEqualTo(without0Bytes).isEqualTo(fromStringWith0Bytes); - - Token withMixed0Bytes = factory.fromString("0004000400"); - Token withoutMixed0Bytes = factory.fromString("00040004"); + public void should_split_range_where_start_as_int_equals_end_as_int() { + Token start = token(Bytes.fromHexString("0x11")); + Token end = token(Bytes.fromHexString("0x1100")); - assertThat(withMixed0Bytes).isEqualTo(withoutMixed0Bytes); + List splits = factory.split(start, end, 3); + assertThat(splits).containsExactly(end, end); } @Test(groups = "unit") diff --git a/driver-core/src/test/java/com/datastax/driver/core/OPPTokenIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/OPPTokenIntegrationTest.java index ab6f5905596..e1098bddb2d 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/OPPTokenIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/OPPTokenIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,4 +30,10 @@ public OPPTokenIntegrationTest() { protected Token.Factory tokenFactory() { return OPPToken.FACTORY; } + + @Override + public void beforeTestClass(Object testInstance) throws Exception { + skipTestWithCassandraVersionOrHigher("4.0.0", "ByteOrderedPartitioner"); + super.beforeTestClass(testInstance); + } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/OPPTokenVnodeIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/OPPTokenVnodeIntegrationTest.java index 084f8a7a8b3..9d630e81c16 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/OPPTokenVnodeIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/OPPTokenVnodeIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,4 +28,10 @@ public OPPTokenVnodeIntegrationTest() { protected Token.Factory tokenFactory() { return Token.OPPToken.FACTORY; } + + @Override + public void beforeTestClass(Object testInstance) throws Exception { + skipTestWithCassandraVersionOrHigher("4.0.0", "ByteOrderedPartitioner"); + super.beforeTestClass(testInstance); + } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/PagingStateTest.java b/driver-core/src/test/java/com/datastax/driver/core/PagingStateTest.java index 69301d4a223..336ba4b51a9 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/PagingStateTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/PagingStateTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ParseUtilsTest.java b/driver-core/src/test/java/com/datastax/driver/core/ParseUtilsTest.java index bd1436a45d3..b80f9adba55 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ParseUtilsTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ParseUtilsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/PerHostPercentileTrackerTest.java b/driver-core/src/test/java/com/datastax/driver/core/PerHostPercentileTrackerTest.java index 5a57f61607d..f99f570d45a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/PerHostPercentileTrackerTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/PerHostPercentileTrackerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/PercentileTrackerTest.java b/driver-core/src/test/java/com/datastax/driver/core/PercentileTrackerTest.java index bce76053ffd..c6a1a4a6f27 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/PercentileTrackerTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/PercentileTrackerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsIntegrationTest.java index 7dc809d8142..86220860516 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java b/driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java index 6c9d2d939da..565667baef8 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/PreparedIdTest.java b/driver-core/src/test/java/com/datastax/driver/core/PreparedIdTest.java index a2aea01a1ad..640c3ad124a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/PreparedIdTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/PreparedIdTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/PreparedStatementInvalidationTest.java b/driver-core/src/test/java/com/datastax/driver/core/PreparedStatementInvalidationTest.java index 7a72fc73fbf..853e638d99b 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/PreparedStatementInvalidationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/PreparedStatementInvalidationTest.java @@ -1,27 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this 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. - */ - -/* - * Copyright (C) 2012-2017 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 + * http://www.apache.org/licenses/LICENSE-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,23 +26,9 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -/** - * Note: at the time of writing, this test exercises features of an unreleased Cassandra version. To - * test against a local build, run with - * - *

- *   -Dcassandra.version=4.0.0 -Dcassandra.directory=/path/to/cassandra
- * 
- */ @CassandraVersion("4.0") public class PreparedStatementInvalidationTest extends CCMTestsSupport { - @Override - public Cluster.Builder createClusterBuilder() { - // TODO remove when protocol v5 is stable in C* 4 - return super.createClusterBuilderNoDebouncing().allowBetaProtocolVersion(); - } - @BeforeMethod(groups = "short", alwaysRun = true) public void setup() throws Exception { execute("CREATE TABLE prepared_statement_invalidation_test (a int PRIMARY KEY, b int, c int);"); diff --git a/driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java b/driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java index d53ad6bc6e9..67a669d6ee0 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -546,11 +548,7 @@ public void should_set_routing_key_on_case_sensitive_keyspace_and_table() { @Test(groups = "short", expectedExceptions = InvalidQueryException.class) public void should_fail_when_prepared_on_another_cluster() throws Exception { - Cluster otherCluster = - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .build(); + Cluster otherCluster = createClusterBuilder().build(); try { PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?"); @@ -577,9 +575,7 @@ public void should_fail_when_prepared_on_another_cluster() throws Exception { public void should_not_allow_unbound_value_on_bound_statement_when_protocol_lesser_than_v4() { Cluster cluster = register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() .withProtocolVersion(ccm().getProtocolVersion(ProtocolVersion.V3)) .build()); Session session = cluster.connect(); @@ -592,6 +588,9 @@ public void should_not_allow_unbound_value_on_bound_statement_when_protocol_less fail("Should not have executed statement with UNSET values in protocol V3"); } catch (IllegalStateException e) { assertThat(e.getMessage()).contains("Unset value at index 1"); + } finally { + session.close(); + cluster.close(); } } @@ -609,9 +608,7 @@ public void should_not_allow_unbound_value_on_bound_statement_when_protocol_less public void should_not_allow_unbound_value_on_batch_statement_when_protocol_lesser_than_v4() { Cluster cluster = register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() .withProtocolVersion(ccm().getProtocolVersion(ProtocolVersion.V3)) .build()); Session session = cluster.connect(); @@ -625,6 +622,9 @@ public void should_not_allow_unbound_value_on_batch_statement_when_protocol_less fail("Should not have executed statement with UNSET values in protocol V3"); } catch (IllegalStateException e) { assertThat(e.getMessage()).contains("Unset value at index 1"); + } finally { + session.close(); + cluster.close(); } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/PrimitiveTypeSamples.java b/driver-core/src/test/java/com/datastax/driver/core/PrimitiveTypeSamples.java index 3580a228d61..8055ac12cd4 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/PrimitiveTypeSamples.java +++ b/driver-core/src/test/java/com/datastax/driver/core/PrimitiveTypeSamples.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ProtocolBetaVersionTest.java b/driver-core/src/test/java/com/datastax/driver/core/ProtocolBetaVersionTest.java index da9cb4d13bf..974e390d47e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ProtocolBetaVersionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ProtocolBetaVersionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,17 +18,28 @@ package com.datastax.driver.core; import static com.datastax.driver.core.ProtocolVersion.V4; -import static com.datastax.driver.core.ProtocolVersion.V5; +import static com.datastax.driver.core.ProtocolVersion.V6; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import com.datastax.driver.core.utils.CassandraVersion; +import org.testng.SkipException; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests for the new USE_BETA flag introduced in protocol v5 and Cassandra 3.10. */ @CassandraVersion("3.10") +@CCMConfig(createCluster = false) public class ProtocolBetaVersionTest extends CCMTestsSupport { + @BeforeClass + public void checkNotCassandra4OrHigher() { + if (ccm().getCassandraVersion().getMajor() > 3) { + throw new SkipException( + "ProtocolBetaVersionTest should only be executed against C* versions >= 3.10 and < 4.0"); + } + } + /** * Verifies that the cluster builder fails when version is explicitly set and user attempts to set * beta flag. @@ -34,8 +47,7 @@ public class ProtocolBetaVersionTest extends CCMTestsSupport { * @jira_ticket JAVA-1248 */ @Test(groups = "short") - public void should_not_initialize_when_version_explicitly_required_and_beta_flag_is_set() - throws Exception { + public void should_not_initialize_when_version_explicitly_required_and_beta_flag_is_set() { try { Cluster.builder() .addContactPoints(getContactPoints()) @@ -57,8 +69,7 @@ public void should_not_initialize_when_version_explicitly_required_and_beta_flag * @jira_ticket JAVA-1248 */ @Test(groups = "short") - public void should_not_initialize_when_beta_flag_is_set_and_version_explicitly_required() - throws Exception { + public void should_not_initialize_when_beta_flag_is_set_and_version_explicitly_required() { try { Cluster.builder() .addContactPoints(getContactPoints()) @@ -75,23 +86,22 @@ public void should_not_initialize_when_beta_flag_is_set_and_version_explicitly_r /** * Verifies that the driver CANNOT connect to 3.10 with the following combination of options: - * Version V5 Flag UNSET + * Version V6 Flag UNSET * * @jira_ticket JAVA-1248 */ @Test(groups = "short") - public void should_not_connect_when_beta_version_explicitly_required_and_flag_not_set() - throws Exception { + public void should_not_connect_when_beta_version_explicitly_required_and_flag_not_set() { try { Cluster.builder() .addContactPoints(getContactPoints()) .withPort(ccm().getBinaryPort()) - .withProtocolVersion(V5) + .withProtocolVersion(V6) .build(); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { assertThat(e.getMessage()) - .startsWith("Can not use V5 protocol version. Newest supported protocol version is: V4"); + .startsWith("Can not use V6 protocol version. Newest supported protocol version is: V5"); } } @@ -101,12 +111,8 @@ public void should_not_connect_when_beta_version_explicitly_required_and_flag_no * * @jira_ticket JAVA-1248 */ - @Test(groups = "short") - public void should_connect_with_beta_when_no_version_explicitly_required_and_flag_set() - throws Exception { - // Note: when the driver's ProtocolVersion.NEWEST_SUPPORTED will be incremented to V6 or higher - // a renegotiation will start taking place here and will downgrade the version from V6 to V5, - // but the test should remain valid since it's executed against 3.10 exclusively + @Test(groups = "short", enabled = false) + public void should_connect_with_beta_when_no_version_explicitly_required_and_flag_set() { Cluster cluster = Cluster.builder() .addContactPoints(getContactPoints()) @@ -114,22 +120,22 @@ public void should_connect_with_beta_when_no_version_explicitly_required_and_fla .allowBetaProtocolVersion() .build(); cluster.connect(); - assertThat(cluster.getConfiguration().getProtocolOptions().getProtocolVersion()).isEqualTo(V5); + assertThat(cluster.getConfiguration().getProtocolOptions().getProtocolVersion()).isEqualTo(V6); } /** * Verifies that the driver can connect to 3.10 with the following combination of options: Version * UNSET Flag UNSET Expected version: V4 * + *

This test has been disabled as of driver 3.11 because v5 is not beta anymore in the driver. + * As a consequence, protocol negotiation without specifying an initial version is not possible + * anymore against C* >= 3.10 and < 4.0. + * * @jira_ticket JAVA-1248 */ - @Test(groups = "short") + @Test(groups = "short", enabled = false) public void - should_connect_after_renegotiation_when_no_version_explicitly_required_and_flag_not_set() - throws Exception { - // Note: when the driver's ProtocolVersion.NEWEST_SUPPORTED will be incremented to V6 or higher - // the renegotiation will start downgrading the version from V6 to V4 instead of V5 to V4, - // but the test should remain valid since it's executed against 3.10 exclusively + should_connect_after_renegotiation_when_no_version_explicitly_required_and_flag_not_set() { Cluster cluster = Cluster.builder() .addContactPoints(getContactPoints()) diff --git a/driver-core/src/test/java/com/datastax/driver/core/ProtocolOptionsTest.java b/driver-core/src/test/java/com/datastax/driver/core/ProtocolOptionsTest.java index ebc8129a163..26ea95cc9f5 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ProtocolOptionsTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ProtocolOptionsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ProtocolV1Test.java b/driver-core/src/test/java/com/datastax/driver/core/ProtocolV1Test.java index 2415bea8aad..bb06cdb2b45 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ProtocolV1Test.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ProtocolV1Test.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ProtocolVersionRenegotiationTest.java b/driver-core/src/test/java/com/datastax/driver/core/ProtocolVersionRenegotiationTest.java index 927fbb89cac..f0c7fd07a08 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ProtocolVersionRenegotiationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ProtocolVersionRenegotiationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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.driver.core; import static com.datastax.driver.core.ProtocolVersion.V1; -import static com.datastax.driver.core.ProtocolVersion.V4; import static com.datastax.driver.core.ProtocolVersion.V5; +import static com.datastax.driver.core.ProtocolVersion.V6; import static org.assertj.core.api.Assertions.assertThat; import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException; @@ -26,6 +28,7 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +@CCMConfig(createCluster = false) public class ProtocolVersionRenegotiationTest extends CCMTestsSupport { private ProtocolVersion protocolVersion; @@ -37,7 +40,7 @@ public void setUp() { /** @jira_ticket JAVA-1367 */ @Test(groups = "short") - public void should_succeed_when_version_provided_and_matches() throws Exception { + public void should_succeed_when_version_provided_and_matches() { Cluster cluster = connectWithVersion(protocolVersion); assertThat(actualProtocolVersion(cluster)).isEqualTo(protocolVersion); } @@ -45,7 +48,7 @@ public void should_succeed_when_version_provided_and_matches() throws Exception /** @jira_ticket JAVA-1367 */ @Test(groups = "short") @CassandraVersion("3.8") - public void should_fail_when_version_provided_and_too_low_3_8_plus() throws Exception { + public void should_fail_when_version_provided_and_too_low_3_8_plus() { UnsupportedProtocolVersionException e = connectWithUnsupportedVersion(V1); assertThat(e.getUnsupportedVersion()).isEqualTo(V1); // post-CASSANDRA-11464: server replies with client's version @@ -54,30 +57,31 @@ public void should_fail_when_version_provided_and_too_low_3_8_plus() throws Exce /** @jira_ticket JAVA-1367 */ @Test(groups = "short") - public void should_fail_when_version_provided_and_too_high() throws Exception { - if (ccm().getCassandraVersion().compareTo(VersionNumber.parse("2.2")) >= 0) { - throw new SkipException("Server supports protocol V4"); + public void should_fail_when_version_provided_and_too_high() { + if (ccm().getCassandraVersion().compareTo(VersionNumber.parse("3.10")) >= 0) { + throw new SkipException("Server supports protocol V5"); } - UnsupportedProtocolVersionException e = connectWithUnsupportedVersion(V4); - assertThat(e.getUnsupportedVersion()).isEqualTo(V4); - // pre-CASSANDRA-11464: server replies with its own version - assertThat(e.getServerVersion()).isEqualTo(protocolVersion); + UnsupportedProtocolVersionException e = connectWithUnsupportedVersion(V5); + assertThat(e.getUnsupportedVersion()).isEqualTo(V5); + // see CASSANDRA-11464: for C* < 3.0.9 and 3.8, server replies with its own version; + // otherwise it replies with the client's version. + assertThat(e.getServerVersion()).isIn(V5, protocolVersion); } /** @jira_ticket JAVA-1367 */ @Test(groups = "short") - public void should_fail_when_beta_allowed_and_too_high() throws Exception { - if (ccm().getCassandraVersion().compareTo(VersionNumber.parse("3.10")) >= 0) { - throw new SkipException("Server supports protocol protocol V5 beta"); + public void should_fail_when_beta_allowed_and_too_high() { + if (ccm().getCassandraVersion().compareTo(VersionNumber.parse("4.0.0")) >= 0) { + throw new SkipException("Server supports protocol protocol V6 beta"); } UnsupportedProtocolVersionException e = connectWithUnsupportedBetaVersion(); - assertThat(e.getUnsupportedVersion()).isEqualTo(V5); + assertThat(e.getUnsupportedVersion()).isEqualTo(V6); } /** @jira_ticket JAVA-1367 */ @Test(groups = "short") @CCMConfig(version = "2.1.16", createCluster = false) - public void should_negotiate_when_no_version_provided() throws Exception { + public void should_negotiate_when_no_version_provided() { if (protocolVersion.compareTo(ProtocolVersion.NEWEST_SUPPORTED) >= 0) { throw new SkipException("Server supports newest protocol version driver supports"); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java b/driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java index 4add41fa5fe..d23661f2bd8 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -243,7 +245,7 @@ public void should_log_exception_from_the_given_result( } else if (expectedException == BootstrappingException.class) { // Special case BootstrappingException, it's wrapped in NHAE since it's always retried. assertThat(e).isInstanceOf(NoHostAvailableException.class); - assertThat(((NoHostAvailableException) e).getErrors().get(hostAddress)) + assertThat(((NoHostAvailableException) e).getErrors().get(hostEndPoint)) .isInstanceOf(expectedException); } else { assertThat(e).isInstanceOf(expectedException); diff --git a/driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java b/driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java index 432633dd893..cec0b7c69e6 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,64 @@ public void should_log_normal_queries() throws Exception { // Tests with query parameters (log level TRACE) + /** @jira_ticket JAVA-2857 */ + @Test(groups = "short") + @CassandraVersion("2.0.0") + public void should_log_simple_statements_without_parameters() throws Exception { + // given + normal.setLevel(TRACE); + queryLogger = QueryLogger.builder().build(); + cluster().register(queryLogger); + + // when + String query = "UPDATE test SET c_int = 42 WHERE pk = 42"; + SimpleStatement stmt = new SimpleStatement(query); + session().execute(stmt); + + // then + String line = normalAppender.waitAndGet(10000); + assertThat(line).contains("Query completed normally").contains(query); + } + + /** @jira_ticket JAVA-2857 */ + @Test(groups = "short") + @CassandraVersion("2.0.0") + public void should_log_bound_statements_without_parameters() throws Exception { + // given + normal.setLevel(TRACE); + queryLogger = QueryLogger.builder().build(); + cluster().register(queryLogger); + + // when + String query = "UPDATE test SET c_int = 42 WHERE pk = 42"; + PreparedStatement ps = session().prepare(query); + BoundStatement bs = ps.bind(); + session().execute(bs); + + // then + String line = normalAppender.waitAndGet(10000); + assertThat(line).contains("Query completed normally").contains(query); + } + + /** @jira_ticket JAVA-2857 */ + @Test(groups = "short") + @CassandraVersion("2.0.0") + public void should_log_built_statements_without_parameters() throws Exception { + // given + normal.setLevel(TRACE); + queryLogger = QueryLogger.builder().build(); + cluster().register(queryLogger); + + // when + // both c_int and pk will be inlined + BuiltStatement update = update("test").with(set("c_int", 42)).where(eq("pk", 42)); + session().execute(update); + + // then + String line = normalAppender.waitAndGet(10000); + assertThat(line).contains("Query completed normally").contains(update.getQueryString()); + } + @Test(groups = "short") @CassandraVersion("2.0.0") public void should_log_non_null_named_parameter_bound_statements() throws Exception { diff --git a/driver-core/src/test/java/com/datastax/driver/core/QueryOptionsTest.java b/driver-core/src/test/java/com/datastax/driver/core/QueryOptionsTest.java index 36f4ea0d86a..f0d4b4f34fe 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/QueryOptionsTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/QueryOptionsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/QueryTimestampTest.java b/driver-core/src/test/java/com/datastax/driver/core/QueryTimestampTest.java index 27289bf6ea6..e92f8d06a45 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/QueryTimestampTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/QueryTimestampTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,8 +20,8 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; +import com.datastax.driver.core.Cluster.Builder; import com.datastax.driver.core.Metrics.Errors; -import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy; import com.datastax.driver.core.utils.CassandraVersion; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -37,15 +39,19 @@ public void onTestContextInitialized() { @Override public Cluster.Builder createClusterBuilder() { - return Cluster.builder() - .withTimestampGenerator( - new TimestampGenerator() { - @Override - public long next() { - return timestampFromGenerator; - } - }) - .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); + @SuppressWarnings("deprecation") + Builder builder = + super.createClusterBuilder() + .withTimestampGenerator( + new TimestampGenerator() { + @Override + public long next() { + return timestampFromGenerator; + } + }) + .withRetryPolicy( + com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy.INSTANCE); + return builder; } @BeforeMethod(groups = "short") diff --git a/driver-core/src/test/java/com/datastax/driver/core/QueryTracker.java b/driver-core/src/test/java/com/datastax/driver/core/QueryTracker.java index 3ab852a3b8a..7890c4549f3 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/QueryTracker.java +++ b/driver-core/src/test/java/com/datastax/driver/core/QueryTracker.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -92,7 +94,8 @@ public void query( for (ListenableFuture future : futures) { try { ResultSet result = Uninterruptibles.getUninterruptibly(future, 1, TimeUnit.SECONDS); - InetSocketAddress address = result.getExecutionInfo().getQueriedHost().getSocketAddress(); + InetSocketAddress address = + result.getExecutionInfo().getQueriedHost().getEndPoint().resolve(); InetAddress coordinator = address.getAddress(); Integer n = coordinators.get(coordinator); coordinators.put(coordinator, n == null ? 1 : n + 1); @@ -108,7 +111,8 @@ public void query( } if (cause instanceof CoordinatorException) { - assertThat(((CoordinatorException) cause).getAddress()).isEqualTo(expectedHost); + assertThat(((CoordinatorException) cause).getEndPoint().resolve()) + .isEqualTo(expectedHost); } } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/RPTokenFactoryTest.java b/driver-core/src/test/java/com/datastax/driver/core/RPTokenFactoryTest.java index e678115d9f4..2f682cbaae2 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/RPTokenFactoryTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/RPTokenFactoryTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/RPTokenIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/RPTokenIntegrationTest.java index de1520a081f..bb181559ef2 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/RPTokenIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/RPTokenIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/RPTokenVnodeIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/RPTokenVnodeIntegrationTest.java index aefb98543f0..d0a186c8500 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/RPTokenVnodeIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/RPTokenVnodeIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ReadTimeoutTest.java b/driver-core/src/test/java/com/datastax/driver/core/ReadTimeoutTest.java index 251488afcaa..e1c6b339324 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ReadTimeoutTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ReadTimeoutTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java b/driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java index 31dafba37b4..1ce02b024c1 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,9 +57,8 @@ public void should_ignore_recommissioned_node_on_reconnection_attempt() throws E // Now start the driver that will connect to node2 and node3, and consider node1 down mainCluster = - Cluster.builder() - .addContactPoints(mainCcm.addressOfNode(2).getAddress()) - .withPort(mainCcm.getBinaryPort()) + TestUtils.configureClusterBuilder( + Cluster.builder(), mainCcm, mainCcm.addressOfNode(2).getAddress()) .withQueryOptions(nonDebouncingQueryOptions()) .build(); mainCluster.connect(); @@ -89,9 +90,8 @@ public void should_ignore_recommissioned_node_on_control_connection_reconnect() // Start the driver, the control connection will be on node2 mainCluster = - Cluster.builder() - .addContactPoints(mainCcm.addressOfNode(2).getAddress()) - .withPort(mainCcm.getBinaryPort()) + TestUtils.configureClusterBuilder( + Cluster.builder(), mainCcm, mainCcm.addressOfNode(2).getAddress()) .withQueryOptions(nonDebouncingQueryOptions()) .build(); mainCluster.connect(); @@ -134,9 +134,8 @@ public void should_ignore_recommissioned_node_on_session_init() throws Exception // Start the driver, it should only connect to node 2 mainCluster = - Cluster.builder() - .addContactPoints(mainCcm.addressOfNode(2).getAddress()) - .withPort(mainCcm.getBinaryPort()) + TestUtils.configureClusterBuilder( + Cluster.builder(), mainCcm, mainCcm.addressOfNode(2).getAddress()) .withQueryOptions(nonDebouncingQueryOptions()) .build(); @@ -181,9 +180,8 @@ public void should_ignore_node_that_does_not_support_protocol_version_on_session // Start the driver, it should only connect to node 2 mainCluster = - Cluster.builder() - .addContactPoints(mainCcm.addressOfNode(2).getAddress()) - .withPort(mainCcm.getBinaryPort()) + TestUtils.configureClusterBuilder( + Cluster.builder(), mainCcm, mainCcm.addressOfNode(2).getAddress()) .withQueryOptions(nonDebouncingQueryOptions()) .build(); diff --git a/driver-core/src/test/java/com/datastax/driver/core/ReconnectionPolicyTest.java b/driver-core/src/test/java/com/datastax/driver/core/ReconnectionPolicyTest.java index 19a557c4b96..5fc54280eeb 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ReconnectionPolicyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ReconnectionPolicyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java b/driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java index 9362653e6d7..5f872409cb2 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/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, @@ -31,7 +33,6 @@ import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.Uninterruptibles; import java.io.IOException; -import java.net.InetSocketAddress; import java.util.Collections; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; @@ -51,9 +52,7 @@ public class ReconnectionTest extends CCMTestsSupport { public void should_reconnect_after_full_connectivity_loss() throws InterruptedException { Cluster cluster = register( - Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis)) .build()); cluster.connect(); @@ -93,9 +92,7 @@ public void should_keep_reconnecting_on_authentication_error() throws Interrupte CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra"); Cluster cluster = register( - Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() // Start with the correct auth so that we can initialize the server .withAuthProvider(authProvider) .withReconnectionPolicy(reconnectionPolicy) @@ -142,12 +139,7 @@ public void should_cancel_reconnection_attempts() throws InterruptedException { new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis)); Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) - .withReconnectionPolicy(reconnectionPolicy) - .build()); + register(createClusterBuilder().withReconnectionPolicy(reconnectionPolicy).build()); cluster.connect(); // Stop a node and cancel the reconnection attempts to it @@ -174,9 +166,7 @@ public void should_trigger_one_time_reconnect() throws InterruptedException, IOE TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy()); Cluster cluster = register( - Cluster.builder() - .addContactPointsWithPorts(ccm().addressOfNode(1)) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() .withLoadBalancingPolicy(loadBalancingPolicy) .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis)) .build()); @@ -231,9 +221,7 @@ public void should_use_connection_from_reconnection_in_pool() { SocketOptions socketOptions = spy(new SocketOptions()); Cluster cluster = register( - Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() .withReconnectionPolicy(new ConstantReconnectionPolicy(5000)) .withLoadBalancingPolicy(loadBalancingPolicy) .withSocketOptions(socketOptions) @@ -284,7 +272,7 @@ static class CountingAuthProvider extends PlainTextAuthProvider { } @Override - public Authenticator newAuthenticator(InetSocketAddress host, String authenticator) { + public Authenticator newAuthenticator(EndPoint host, String authenticator) { count.incrementAndGet(); return super.newAuthenticator(host, authenticator); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java b/driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java index 4fe2a333037..dbeb48f1eea 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,13 +42,10 @@ public void should_refresh_single_connected_host() { PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions()); Cluster cluster = register( - Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) + createClusterBuilderNoDebouncing() .withPoolingOptions(poolingOptions) .withLoadBalancingPolicy(loadBalancingPolicy) .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)) - .withQueryOptions(TestUtils.nonDebouncingQueryOptions()) .build()); Session session = cluster.connect(); diff --git a/driver-core/src/test/java/com/datastax/driver/core/ReplicationFactorTest.java b/driver-core/src/test/java/com/datastax/driver/core/ReplicationFactorTest.java new file mode 100644 index 00000000000..3611646f270 --- /dev/null +++ b/driver-core/src/test/java/com/datastax/driver/core/ReplicationFactorTest.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.driver.core; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.testng.annotations.Test; + +public class ReplicationFactorTest { + + @Test(groups = "unit") + public void should_parse_factor_from_string() { + ReplicationFactor transFactor = ReplicationFactor.fromString("3/1"); + assertThat(transFactor.fullReplicas()).isEqualTo(2); + assertThat(transFactor.hasTransientReplicas()).isTrue(); + assertThat(transFactor.transientReplicas()).isEqualTo(1); + + ReplicationFactor factor = ReplicationFactor.fromString("3"); + assertThat(factor.fullReplicas()).isEqualTo(3); + assertThat(factor.hasTransientReplicas()).isFalse(); + assertThat(factor.transientReplicas()).isEqualTo(0); + } + + @Test(groups = "unit") + public void should_create_string_from_factor() { + ReplicationFactor transFactor = new ReplicationFactor(3, 1); + assertThat(transFactor.toString()).isEqualTo("3/1"); + ReplicationFactor factor = new ReplicationFactor(3); + assertThat(factor.toString()).isEqualTo("3"); + } +} diff --git a/driver-core/src/test/java/com/datastax/driver/core/ReplicationStrategyTest.java b/driver-core/src/test/java/com/datastax/driver/core/ReplicationStrategyTest.java index 5615623cbc2..2d935e718b3 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ReplicationStrategyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ReplicationStrategyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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.driver.core; +import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; @@ -87,4 +90,77 @@ public void createUnspecifiedStrategyTest() throws Exception { assertNull(strategy); } + + @Test(groups = "unit") + public void simpleStrategyEqualsTest() { + ReplicationStrategy rf3_1 = + ReplicationStrategy.create( + ImmutableMap.builder() + .put("class", "SimpleStrategy") + .put("replication_factor", "3") + .build()); + + ReplicationStrategy rf3_2 = + ReplicationStrategy.create( + ImmutableMap.builder() + .put("class", "SimpleStrategy") + .put("replication_factor", "3") + .build()); + + ReplicationStrategy rf2_1 = + ReplicationStrategy.create( + ImmutableMap.builder() + .put("class", "SimpleStrategy") + .put("replication_factor", "2") + .build()); + + //noinspection EqualsWithItself + assertThat(rf3_1).isEqualTo(rf3_1); + assertThat(rf3_1).isEqualTo(rf3_2); + assertThat(rf3_1).isNotEqualTo(rf2_1); + } + + public void networkTopologyStrategyEqualsTest() { + ReplicationStrategy network_dc1x2_dc2x2_1 = + ReplicationStrategy.create( + ImmutableMap.builder() + .put("class", "NetworkTopologyStrategy") + .put("dc1", "2") + .put("dc2", "2") + .build()); + ReplicationStrategy network_dc1x2_dc2x2_2 = + ReplicationStrategy.create( + ImmutableMap.builder() + .put("class", "NetworkTopologyStrategy") + .put("dc1", "2") + .put("dc2", "2") + .build()); + ReplicationStrategy network_dc1x1_dc2x2_1 = + ReplicationStrategy.create( + ImmutableMap.builder() + .put("class", "NetworkTopologyStrategy") + .put("dc1", "1") + .put("dc2", "2") + .build()); + ReplicationStrategy network_dc1x2_dc3x2_1 = + ReplicationStrategy.create( + ImmutableMap.builder() + .put("class", "NetworkTopologyStrategy") + .put("dc1", "2") + .put("dc3", "2") + .build()); + ReplicationStrategy network_dc1x2_1 = + ReplicationStrategy.create( + ImmutableMap.builder() + .put("class", "NetworkTopologyStrategy") + .put("dc1", "2") + .build()); + + //noinspection EqualsWithItself + assertThat(network_dc1x2_dc2x2_1).isEqualTo(network_dc1x2_dc2x2_1); + assertThat(network_dc1x2_dc2x2_1).isEqualTo(network_dc1x2_dc2x2_2); + assertThat(network_dc1x2_dc2x2_1).isNotEqualTo(network_dc1x1_dc2x2_1); + assertThat(network_dc1x2_dc2x2_1).isNotEqualTo(network_dc1x2_dc3x2_1); + assertThat(network_dc1x2_dc2x2_1).isNotEqualTo(network_dc1x2_1); + } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java b/driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java index 22d7aad2dc8..b045e5ba16b 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 RequestHandlerTest { - @Test(groups = "long") + @Test(groups = "short") public void should_handle_race_between_response_and_cancellation() { final Scassandra scassandra = TestUtils.createScassandraServer(); Cluster cluster = null; @@ -38,6 +40,7 @@ public void should_handle_race_between_response_and_cancellation() { try { // Use a mock server that takes a constant time to reply scassandra.start(); + ScassandraCluster.primeSystemLocalRow(scassandra); List> rows = Collections.>singletonList(ImmutableMap.of("key", 1)); scassandra diff --git a/driver-core/src/test/java/com/datastax/driver/core/ResultSetAssert.java b/driver-core/src/test/java/com/datastax/driver/core/ResultSetAssert.java index 6664ee1ebe3..34013cedb69 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ResultSetAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ResultSetAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ReusedStreamIdTest.java b/driver-core/src/test/java/com/datastax/driver/core/ReusedStreamIdTest.java index 577d724d11c..ac78f84a125 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ReusedStreamIdTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ReusedStreamIdTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java b/driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java index 3b4b160a4ec..1ae24cbc478 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java b/driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java index c9a01089363..3db7d8b9125 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -76,12 +78,7 @@ public void should_not_connect_with_ssl_without_trusting_server_cert( groups = "short", expectedExceptions = {NoHostAvailableException.class}) public void should_not_connect_without_ssl_but_node_uses_ssl() throws Exception { - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .build()); + Cluster cluster = register(createClusterBuilder().build()); cluster.connect(); } @@ -99,11 +96,7 @@ public void should_reconnect_with_ssl_on_node_up(SslImplementation sslImplementa throws Exception { Cluster cluster = register( - Cluster.builder() - .addContactPoints(this.getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withSSL(getSSLOptions(sslImplementation, true, true)) - .build()); + createClusterBuilder().withSSL(getSSLOptions(sslImplementation, true, true)).build()); cluster.connect(); diff --git a/driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java b/driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java index 97a9434938d..f4f69045f6e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,13 +53,7 @@ public static Object[][] sslImplementation() { * be raised here if connection cannot be established. */ protected void connectWithSSLOptions(SSLOptions sslOptions) throws Exception { - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withSSL(sslOptions) - .build()); + Cluster cluster = register(createClusterBuilder().withSSL(sslOptions).build()); cluster.connect(); } @@ -69,13 +65,7 @@ protected void connectWithSSLOptions(SSLOptions sslOptions) throws Exception { * be raised here if connection cannot be established. */ protected void connectWithSSL() throws Exception { - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withSSL() - .build()); + Cluster cluster = register(createClusterBuilder().withSSL().build()); cluster.connect(); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/ScassandraCluster.java b/driver-core/src/test/java/com/datastax/driver/core/ScassandraCluster.java index 6db989b8511..aa3a46b1455 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ScassandraCluster.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ScassandraCluster.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,15 +36,17 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import com.google.common.collect.Sets; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.TreeSet; -import java.util.UUID; import java.util.concurrent.TimeUnit; import org.scassandra.Scassandra; import org.scassandra.ScassandraFactory; @@ -50,6 +54,7 @@ import org.scassandra.http.client.PrimingClient; import org.scassandra.http.client.PrimingRequest; import org.scassandra.http.client.Result; +import org.scassandra.http.client.types.ColumnMetadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -232,7 +237,7 @@ public InetSocketAddress listenAddress(int dc, int node) { public Host host(Cluster cluster, int dc, int node) { InetSocketAddress address = address(dc, node); for (Host host : cluster.getMetadata().getAllHosts()) { - if (host.getSocketAddress().equals(address)) { + if (host.getEndPoint().resolve().equals(address)) { return host; } } @@ -255,7 +260,11 @@ public void init() { public void stop() { logger.debug("Stopping ScassandraCluster."); for (Scassandra node : instances) { - node.stop(); + try { + node.stop(); + } catch (Exception e) { + logger.error("Could not stop node " + node, e); + } } } @@ -299,7 +308,11 @@ public void stopDC(Cluster cluster, int dc) { public void stop(Cluster cluster, int node) { logger.debug("Stopping node {}.", node); Scassandra scassandra = node(node); - scassandra.stop(); + try { + scassandra.stop(); + } catch (Exception e) { + logger.error("Could not stop node " + scassandra, e); + } assertThat(cluster).host(node).goesDownWithin(10, TimeUnit.SECONDS); } @@ -552,7 +565,7 @@ private void primeMetadata(Scassandra node) { ImmutableMap.builder().put("cluster_name", "scassandra").build(); client.prime( PrimingRequest.queryBuilder() - .withQuery("select cluster_name from system.local") + .withQuery("select cluster_name from system.local where key = 'local'") .withThen( then() .withColumnTypes(SELECT_CLUSTER_NAME) @@ -608,6 +621,22 @@ private Object getPeerInfo(int dc, int node, String property, Object defaultValu column("schema_version", UUID) }; + /* system.peers was re-worked for DSE 6.8 */ + public static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_PEERS_DSE68 = { + column("peer", INET), + column("rpc_address", INET), + column("data_center", TEXT), + column("rack", TEXT), + column("release_version", TEXT), + column("tokens", set(TEXT)), + column("host_id", UUID), + column("graph", BOOLEAN), + column("schema_version", UUID), + column("native_transport_address", INET), + column("native_transport_port", INT), + column("native_transport_port_ssl", INT) + }; + public static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_PEERS_V2 = { column("peer", INET), column("peer_port", INT), @@ -629,14 +658,14 @@ private Object getPeerInfo(int dc, int node, String property, Object defaultValu column("cluster_name", TEXT), column("cql_version", TEXT), column("data_center", TEXT), + column("graph", BOOLEAN), + column("host_id", UUID), column("listen_address", INET), column("partitioner", TEXT), column("rack", TEXT), column("release_version", TEXT), - column("tokens", set(TEXT)), - column("graph", BOOLEAN), - column("host_id", UUID), - column("schema_version", UUID) + column("schema_version", UUID), + column("tokens", set(TEXT)) }; public static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_LOCAL_V2 = { @@ -647,15 +676,36 @@ private Object getPeerInfo(int dc, int node, String property, Object defaultValu column("cluster_name", TEXT), column("cql_version", TEXT), column("data_center", TEXT), + column("graph", BOOLEAN), + column("host_id", UUID), column("listen_address", INET), column("listen_port", INT), column("partitioner", TEXT), column("rack", TEXT), column("release_version", TEXT), - column("tokens", set(TEXT)), - column("graph", BOOLEAN), + column("schema_version", UUID), + column("tokens", set(TEXT)) + }; + + public static final org.scassandra.http.client.types.ColumnMetadata[] + SELECT_LOCAL_RPC_ADDRESS_AND_PORT = { + column("key", TEXT), + column("bootstrapped", TEXT), + column("broadcast_address", INET), + column("broadcast_port", INT), + column("cluster_name", TEXT), + column("cql_version", TEXT), + column("data_center", TEXT), column("host_id", UUID), - column("schema_version", UUID) + column("listen_address", INET), + column("listen_port", INT), + column("partitioner", TEXT), + column("rack", TEXT), + column("release_version", TEXT), + column("rpc_address", INET), + column("rpc_port", INT), + column("schema_version", UUID), + column("tokens", set(TEXT)) }; static final org.scassandra.http.client.types.ColumnMetadata[] SELECT_CLUSTER_NAME = { @@ -720,6 +770,24 @@ private Object getPeerInfo(int dc, int node, String property, Object defaultValu column("validator", TEXT), }; + // Primes a minimal system.local row on an Scassandra node. + // We need a host_id so that the driver can store it in Metadata.hosts + public static void primeSystemLocalRow(Scassandra scassandra) { + Set localMetadata = Sets.newHashSet(SELECT_LOCAL); + Map row = new HashMap(); + row.put("host_id", java.util.UUID.randomUUID()); + scassandra + .primingClient() + .prime( + PrimingRequest.queryBuilder() + .withQuery("SELECT * FROM system.local WHERE key='local'") + .withThen( + then() + .withColumnTypes( + localMetadata.toArray(new ColumnMetadata[localMetadata.size()])) + .withRows(Collections.>singletonList(row)))); + } + public static ScassandraClusterBuilder builder() { return new ScassandraClusterBuilder(); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java b/driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java index 50e488547f2..68a6ea67832 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,8 @@ import org.scassandra.http.client.ActivityClient; import org.scassandra.http.client.CurrentClient; import org.scassandra.http.client.PrimingClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; @@ -36,9 +40,11 @@ */ public abstract class ScassandraTestBase { + private static final Logger logger = LoggerFactory.getLogger(ScassandraTestBase.class); + protected Scassandra scassandra; - protected InetSocketAddress hostAddress; + protected EndPoint hostEndPoint; protected PrimingClient primingClient; @@ -55,12 +61,19 @@ public void beforeTestClass() { primingClient = scassandra.primingClient(); activityClient = scassandra.activityClient(); currentClient = scassandra.currentClient(); - hostAddress = new InetSocketAddress(ip, scassandra.getBinaryPort()); + hostEndPoint = + new TranslatedAddressEndPoint(new InetSocketAddress(ip, scassandra.getBinaryPort())); } @AfterClass(groups = {"short", "long"}) public void afterTestClass() { - if (scassandra != null) scassandra.stop(); + if (scassandra != null) { + try { + scassandra.stop(); + } catch (Exception e) { + logger.error("Could not stop node " + scassandra, e); + } + } } @BeforeMethod(groups = {"short", "long"}) @@ -69,12 +82,13 @@ public void resetClients() { activityClient.clearAllRecordedActivity(); primingClient.clearAllPrimes(); currentClient.enableListener(); + ScassandraCluster.primeSystemLocalRow(scassandra); } protected Cluster.Builder createClusterBuilder() { return Cluster.builder() .withPort(scassandra.getBinaryPort()) - .addContactPoints(hostAddress.getAddress()) + .addContactPoint(hostEndPoint) .withPort(scassandra.getBinaryPort()) .withPoolingOptions( new PoolingOptions() @@ -84,7 +98,7 @@ protected Cluster.Builder createClusterBuilder() { } protected Host retrieveSingleHost(Cluster cluster) { - Host host = cluster.getMetadata().getHost(hostAddress); + Host host = cluster.getMetadata().getHost(hostEndPoint); if (host == null) { fail("Unable to retrieve host"); } @@ -103,15 +117,18 @@ public abstract static class PerClassCluster extends ScassandraTestBase { protected Host host; + @Override @BeforeClass(groups = {"short", "long"}) public void beforeTestClass() { super.beforeTestClass(); + ScassandraCluster.primeSystemLocalRow(scassandra); Cluster.Builder builder = createClusterBuilder(); cluster = builder.build(); host = retrieveSingleHost(cluster); session = cluster.connect(); } + @Override @AfterClass(groups = {"short", "long"}) public void afterTestClass() { if (cluster != null) cluster.close(); diff --git a/driver-core/src/test/java/com/datastax/driver/core/SchemaAgreementTest.java b/driver-core/src/test/java/com/datastax/driver/core/SchemaAgreementTest.java index 283e7b3ff5a..a2722671512 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SchemaAgreementTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SchemaAgreementTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/SchemaChangesCCTest.java b/driver-core/src/test/java/com/datastax/driver/core/SchemaChangesCCTest.java index 972f668eba5..7cb08d97d22 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SchemaChangesCCTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SchemaChangesCCTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,22 +60,10 @@ public class SchemaChangesCCTest extends CCMTestsSupport { public void should_receive_changes_made_while_control_connection_is_down_on_reconnect() throws Exception { ToggleablePolicy lbPolicy = new ToggleablePolicy(Policies.defaultLoadBalancingPolicy()); - Cluster cluster = - register( - Cluster.builder() - .withLoadBalancingPolicy(lbPolicy) - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) - .build()); + Cluster cluster = register(createClusterBuilder().withLoadBalancingPolicy(lbPolicy).build()); // Put cluster2 control connection on node 2 so it doesn't go down (to prevent noise for // debugging). - Cluster cluster2 = - register( - Cluster.builder() - .withLoadBalancingPolicy(lbPolicy) - .addContactPoints(getContactPoints().get(1)) - .withPort(ccm().getBinaryPort()) - .build()); + Cluster cluster2 = register(createClusterBuilder().withLoadBalancingPolicy(lbPolicy).build()); SchemaChangeListener listener = mock(SchemaChangeListener.class); cluster.init(); @@ -110,7 +100,12 @@ public void should_receive_changes_made_while_control_connection_is_down_on_reco // Perform some schema changes that we'll validate when the control connection comes back. session2.execute("drop keyspace ks2"); session2.execute("drop table ks1.tbl2"); - session2.execute("alter keyspace ks1 with durable_writes=false"); + + // Modifying keyspaces with a node down is not possible in 4.0+ (CASSANDRA-14404) + if (!isCassandraVersionOrHigher("4.0.0")) { + session2.execute("alter keyspace ks1 with durable_writes=false"); + } + session2.execute("alter table ks1.tbl1 add new_col varchar"); session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks3", 1)); session2.execute("create table ks1.tbl3 (k text primary key, v text)"); @@ -164,8 +159,11 @@ public void should_receive_changes_made_while_control_connection_is_down_on_reco .isDurableWrites() .isEqualTo(prealteredKeyspace); - // New metadata should reflect that the durable writes attribute changed. - assertThat(alteredKeyspace.getValue()).hasName("ks1").isNotDurableWrites(); + // Modifying keyspaces with a node down is not possible in 4.0+ (CASSANDRA-14404) + if (!isCassandraVersionOrHigher("4.0.0")) { + // New metadata should reflect that the durable writes attribute changed. + assertThat(alteredKeyspace.getValue()).hasName("ks1").isNotDurableWrites(); + } // Ensure the alter table event shows up. ArgumentCaptor alteredTable = ArgumentCaptor.forClass(TableMetadata.class); diff --git a/driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java b/driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java index f500a3d96af..1193031c812 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import java.util.List; +import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import org.mockito.ArgumentCaptor; import org.testng.annotations.AfterClass; @@ -80,18 +83,11 @@ public class SchemaChangesTest extends CCMTestsSupport { @BeforeClass(groups = "short") public void setup() throws InterruptedException { - Cluster.Builder builder = - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withQueryOptions(nonDebouncingQueryOptions()); - cluster1 = builder.build(); - cluster2 = builder.build(); + cluster1 = createClusterBuilderNoDebouncing().build(); + cluster2 = createClusterBuilderNoDebouncing().build(); schemaDisabledCluster = spy( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() .withClusterName("schema-disabled") .withQueryOptions(nonDebouncingQueryOptions().setMetadataEnabled(false)) .build()); @@ -192,6 +188,40 @@ public void should_notify_of_table_update(String keyspace) throws InterruptedExc assertThat(m.getKeyspace(keyspace).getTable("table1")).hasColumn("j"); } + /** + * JAVA-2204: Make sure we don't accidentally store new table instances in an old keyspace + * instance, otherwise this will create a memory leak if a client holds onto a stale table + * instance (in particular, the object mapper does). + */ + @Test(groups = "short") + public void should_not_update_tables_on_stale_keyspace_instance() throws InterruptedException { + final Cluster cluster1 = session1.getCluster(); + final String keyspaceName = "lowercase"; + execute(CREATE_TABLE, keyspaceName); + final KeyspaceMetadata oldKeyspace = cluster1.getMetadata().getKeyspace(keyspaceName); + TableMetadata oldTable = oldKeyspace.getTable("table1"); + + // Force a full refresh + cluster1.getConfiguration().getQueryOptions().setMetadataEnabled(false); + cluster1.getConfiguration().getQueryOptions().setMetadataEnabled(true); + ConditionChecker.check() + .that( + new Callable() { + @Override + public Boolean call() { + return cluster1.getMetadata().getKeyspace(keyspaceName) == oldKeyspace; + } + }) + .becomesFalse(); + + // Before the fix, the schema parser updated the old keyspace's tables during a full refresh: + // oldTable -> oldKeyspace -> newTable + // If the client held onto the initial table instance, successive refreshes would grow the chain + // over time: + // table1 -> keyspace1 -> table2 -> keyspace2 -> ... + assertThat(oldKeyspace.getTable("table1")).isSameAs(oldTable); + } + /** * Verifies that when a table is updated that its associated views remain accessible from the * table via {@link TableMetadata#getView(String)}. @@ -217,7 +247,7 @@ public void should_retain_view_on_table_update(String keyspace) throws Interrupt // Create view and ensure event is received and metadata is updated session1.execute( String.format( - "CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c)", + "CREATE MATERIALIZED VIEW %s.mv1 AS SELECT pk, c FROM %s.table1 WHERE c IS NOT NULL AND pk IS NOT NULL PRIMARY KEY (pk, c)", keyspace, keyspace)); for (SchemaChangeListener listener : listeners) { ArgumentCaptor viewAdded = @@ -466,7 +496,7 @@ public void should_notify_of_view_creation(String keyspace) { session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace)); session1.execute( String.format( - "CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c)", + "CREATE MATERIALIZED VIEW %s.mv1 AS SELECT pk, c FROM %s.table1 WHERE c IS NOT NULL AND pk IS NOT NULL PRIMARY KEY (pk, c)", keyspace, keyspace)); for (SchemaChangeListener listener : listeners) { ArgumentCaptor removed = @@ -485,7 +515,7 @@ public void should_notify_of_view_update(String keyspace) { session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace)); session1.execute( String.format( - "CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c) WITH compaction = { 'class' : 'SizeTieredCompactionStrategy' }", + "CREATE MATERIALIZED VIEW %s.mv1 AS SELECT pk, c FROM %s.table1 WHERE c IS NOT NULL AND pk IS NOT NULL PRIMARY KEY (pk, c) WITH compaction = { 'class' : 'SizeTieredCompactionStrategy' }", keyspace, keyspace)); for (SchemaChangeListener listener : listeners) { ArgumentCaptor removed = @@ -536,7 +566,7 @@ public void should_notify_of_view_drop(String keyspace) { session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace)); session1.execute( String.format( - "CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c)", + "CREATE MATERIALIZED VIEW %s.mv1 AS SELECT pk, c FROM %s.table1 WHERE c IS NOT NULL AND pk IS NOT NULL PRIMARY KEY (pk, c)", keyspace, keyspace)); session1.execute(String.format("DROP MATERIALIZED VIEW %s.mv1", keyspace)); for (SchemaChangeListener listener : listeners) { @@ -620,9 +650,7 @@ public void should_notify_of_keyspace_drop(String keyspace) throws InterruptedEx @Test(groups = "short", expectedExceptions = IllegalStateException.class) public void should_throw_illegal_state_exception_on_newToken_with_metadata_disabled() { Cluster cluster = - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() .withQueryOptions(nonDebouncingQueryOptions().setMetadataEnabled(false)) .build(); @@ -644,9 +672,7 @@ public void should_throw_illegal_state_exception_on_newToken_with_metadata_disab @Test(groups = "short", expectedExceptions = IllegalStateException.class) public void should_throw_illegal_state_exception_on_newTokenRange_with_metadata_disabled() { Cluster cluster = - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() .withQueryOptions(nonDebouncingQueryOptions().setMetadataEnabled(false)) .build(); diff --git a/driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java b/driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java index 65c3a727f13..2c92ba23c7a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,13 +61,7 @@ public void setup() { queryOptions.setRefreshSchemaIntervalMillis(DEBOUNCE_TIME); queryOptions.setMaxPendingRefreshSchemaRequests(5); // Create a separate cluster that will receive the schema events on its control connection. - cluster2 = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withQueryOptions(queryOptions) - .build()); + cluster2 = register(createClusterBuilder().withQueryOptions(queryOptions).build()); session2 = cluster2.connect(); // Create a spy of the Cluster's control connection and replace it with the spy. diff --git a/driver-core/src/test/java/com/datastax/driver/core/SegmentBuilderTest.java b/driver-core/src/test/java/com/datastax/driver/core/SegmentBuilderTest.java new file mode 100644 index 00000000000..557c8c66b87 --- /dev/null +++ b/driver-core/src/test/java/com/datastax/driver/core/SegmentBuilderTest.java @@ -0,0 +1,310 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +import io.netty.buffer.ByteBufAllocator; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import io.netty.channel.embedded.EmbeddedChannel; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class SegmentBuilderTest { + + private static final Message.ProtocolEncoder REQUEST_ENCODER = + new Message.ProtocolEncoder(ProtocolVersion.V5); + + // The constant names denote the total encoded size, including the frame header + private static final Message.Request _38B_REQUEST = new Requests.Query("SELECT * FROM table"); + private static final Message.Request _51B_REQUEST = + new Requests.Query("SELECT * FROM table WHERE id = 1"); + private static final Message.Request _1KB_REQUEST = + new Requests.Query( + "SELECT * FROM table WHERE id = ?", + new Requests.QueryProtocolOptions( + Message.Request.Type.QUERY, + ConsistencyLevel.ONE, + new ByteBuffer[] {ByteBuffer.allocate(967)}, + Collections.emptyMap(), + false, + -1, + null, + ConsistencyLevel.SERIAL, + Long.MIN_VALUE, + Integer.MIN_VALUE), + false); + + private static final EmbeddedChannel MOCK_CHANNEL = new EmbeddedChannel(); + private static final ChannelHandlerContext CONTEXT = Mockito.mock(ChannelHandlerContext.class); + + @BeforeClass(groups = "unit") + public static void setup() { + // This is the only method called by our test implementation + when(CONTEXT.newPromise()) + .thenAnswer( + new Answer() { + @Override + public ChannelPromise answer(InvocationOnMock invocation) { + return MOCK_CHANNEL.newPromise(); + } + }); + } + + @Test(groups = "unit") + public void should_concatenate_frames_when_under_limit() { + TestSegmentBuilder builder = new TestSegmentBuilder(CONTEXT, 100); + + ChannelPromise requestPromise1 = newPromise(); + builder.addRequest(_38B_REQUEST, requestPromise1); + ChannelPromise requestPromise2 = newPromise(); + builder.addRequest(_51B_REQUEST, requestPromise2); + // Nothing produced yet since we would still have room for more frames + assertThat(builder.segments).isEmpty(); + + builder.flush(); + assertThat(builder.segments).hasSize(1); + assertThat(builder.segmentPromises).hasSize(1); + Segment segment = builder.segments.get(0); + assertThat(segment.getPayload().readableBytes()).isEqualTo(38 + 51); + assertThat(segment.isSelfContained()).isTrue(); + ChannelPromise segmentPromise = builder.segmentPromises.get(0); + assertForwards(segmentPromise, requestPromise1, requestPromise2); + } + + @Test(groups = "unit") + public void should_start_new_segment_when_over_limit() { + TestSegmentBuilder builder = new TestSegmentBuilder(CONTEXT, 100); + + ChannelPromise requestPromise1 = newPromise(); + builder.addRequest(_38B_REQUEST, requestPromise1); + ChannelPromise requestPromise2 = newPromise(); + builder.addRequest(_51B_REQUEST, requestPromise2); + ChannelPromise requestPromise3 = newPromise(); + builder.addRequest(_38B_REQUEST, requestPromise3); + // Adding the 3rd frame brings the total size over 100, so a first segment should be emitted + // with the first two messages: + assertThat(builder.segments).hasSize(1); + + ChannelPromise requestPromise4 = newPromise(); + builder.addRequest(_38B_REQUEST, requestPromise4); + builder.flush(); + assertThat(builder.segments).hasSize(2); + + Segment segment1 = builder.segments.get(0); + assertThat(segment1.getPayload().readableBytes()).isEqualTo(38 + 51); + assertThat(segment1.isSelfContained()).isTrue(); + ChannelPromise segmentPromise1 = builder.segmentPromises.get(0); + assertForwards(segmentPromise1, requestPromise1, requestPromise2); + Segment segment2 = builder.segments.get(1); + assertThat(segment2.getPayload().readableBytes()).isEqualTo(38 + 38); + assertThat(segment2.isSelfContained()).isTrue(); + ChannelPromise segmentPromise2 = builder.segmentPromises.get(1); + assertForwards(segmentPromise2, requestPromise3, requestPromise4); + } + + @Test(groups = "unit") + public void should_start_new_segment_when_at_limit() { + TestSegmentBuilder builder = new TestSegmentBuilder(CONTEXT, 38 + 51); + + ChannelPromise requestPromise1 = newPromise(); + builder.addRequest(_38B_REQUEST, requestPromise1); + ChannelPromise requestPromise2 = newPromise(); + builder.addRequest(_51B_REQUEST, requestPromise2); + ChannelPromise requestPromise3 = newPromise(); + builder.addRequest(_38B_REQUEST, requestPromise3); + assertThat(builder.segments).hasSize(1); + + ChannelPromise requestPromise4 = newPromise(); + builder.addRequest(_51B_REQUEST, requestPromise4); + builder.flush(); + assertThat(builder.segments).hasSize(2); + + Segment segment1 = builder.segments.get(0); + assertThat(segment1.getPayload().readableBytes()).isEqualTo(38 + 51); + assertThat(segment1.isSelfContained()).isTrue(); + ChannelPromise segmentPromise1 = builder.segmentPromises.get(0); + assertForwards(segmentPromise1, requestPromise1, requestPromise2); + Segment segment2 = builder.segments.get(1); + assertThat(segment2.getPayload().readableBytes()).isEqualTo(38 + 51); + assertThat(segment2.isSelfContained()).isTrue(); + ChannelPromise segmentPromise2 = builder.segmentPromises.get(1); + assertForwards(segmentPromise2, requestPromise3, requestPromise4); + } + + @Test(groups = "unit") + public void should_split_large_frame() { + TestSegmentBuilder builder = new TestSegmentBuilder(CONTEXT, 100); + + ChannelPromise parentPromise = newPromise(); + builder.addRequest(_1KB_REQUEST, parentPromise); + + assertThat(builder.segments).hasSize(11); + assertThat(builder.segmentPromises).hasSize(11); + for (int i = 0; i < 11; i++) { + Segment slice = builder.segments.get(i); + assertThat(slice.getPayload().readableBytes()).isEqualTo(i == 10 ? 24 : 100); + assertThat(slice.isSelfContained()).isFalse(); + } + } + + @Test(groups = "unit") + public void should_succeed_parent_write_if_all_slices_successful() { + TestSegmentBuilder builder = new TestSegmentBuilder(CONTEXT, 100); + + ChannelPromise parentPromise = newPromise(); + builder.addRequest(_1KB_REQUEST, parentPromise); + + assertThat(builder.segments).hasSize(11); + assertThat(builder.segmentPromises).hasSize(11); + + for (int i = 0; i < 11; i++) { + assertThat(parentPromise.isDone()).isFalse(); + builder.segmentPromises.get(i).setSuccess(); + } + + assertThat(parentPromise.isDone()).isTrue(); + } + + @Test(groups = "unit") + public void should_fail_parent_write_if_any_slice_fails() { + TestSegmentBuilder builder = new TestSegmentBuilder(CONTEXT, 100); + + ChannelPromise parentPromise = newPromise(); + builder.addRequest(_1KB_REQUEST, parentPromise); + + assertThat(builder.segments).hasSize(11); + + // Complete a few slices successfully + for (int i = 0; i < 5; i++) { + builder.segmentPromises.get(i).setSuccess(); + } + assertThat(parentPromise.isDone()).isFalse(); + + // Fail a slice, the parent should fail immediately + Exception mockException = new Exception("test"); + builder.segmentPromises.get(5).setFailure(mockException); + assertThat(parentPromise.isDone()).isTrue(); + assertThat(parentPromise.cause()).isEqualTo(mockException); + + // The remaining slices should have been cancelled + for (int i = 6; i < 11; i++) { + assertThat(builder.segmentPromises.get(i).isCancelled()).isTrue(); + } + } + + @Test(groups = "unit") + public void should_split_large_frame_when_exact_multiple() { + TestSegmentBuilder builder = new TestSegmentBuilder(CONTEXT, 256); + + ChannelPromise parentPromise = newPromise(); + builder.addRequest(_1KB_REQUEST, parentPromise); + + assertThat(builder.segments).hasSize(4); + assertThat(builder.segmentPromises).hasSize(4); + for (int i = 0; i < 4; i++) { + Segment slice = builder.segments.get(i); + assertThat(slice.getPayload().readableBytes()).isEqualTo(256); + assertThat(slice.isSelfContained()).isFalse(); + } + } + + @Test(groups = "unit") + public void should_mix_small_frames_and_large_frames() { + TestSegmentBuilder builder = new TestSegmentBuilder(CONTEXT, 100); + + ChannelPromise requestPromise1 = newPromise(); + builder.addRequest(_38B_REQUEST, requestPromise1); + ChannelPromise requestPromise2 = newPromise(); + builder.addRequest(_51B_REQUEST, requestPromise2); + + // Large frame: process immediately, does not impact accumulated small frames + ChannelPromise requestPromise3 = newPromise(); + builder.addRequest(_1KB_REQUEST, requestPromise3); + assertThat(builder.segments).hasSize(11); + + // Another small frames bring us above the limit + ChannelPromise requestPromise4 = newPromise(); + builder.addRequest(_38B_REQUEST, requestPromise4); + assertThat(builder.segments).hasSize(12); + + // One last frame and finish + ChannelPromise requestPromise5 = newPromise(); + builder.addRequest(_38B_REQUEST, requestPromise5); + builder.flush(); + assertThat(builder.segments).hasSize(13); + assertThat(builder.segmentPromises).hasSize(13); + + for (int i = 0; i < 11; i++) { + Segment slice = builder.segments.get(i); + assertThat(slice.getPayload().readableBytes()).isEqualTo(i == 10 ? 24 : 100); + assertThat(slice.isSelfContained()).isFalse(); + } + + Segment smallMessages1 = builder.segments.get(11); + assertThat(smallMessages1.getPayload().readableBytes()).isEqualTo(38 + 51); + assertThat(smallMessages1.isSelfContained()).isTrue(); + ChannelPromise segmentPromise1 = builder.segmentPromises.get(11); + assertForwards(segmentPromise1, requestPromise1, requestPromise2); + Segment smallMessages2 = builder.segments.get(12); + assertThat(smallMessages2.getPayload().readableBytes()).isEqualTo(38 + 38); + assertThat(smallMessages2.isSelfContained()).isTrue(); + ChannelPromise segmentPromise2 = builder.segmentPromises.get(12); + assertForwards(segmentPromise2, requestPromise4, requestPromise5); + } + + private static ChannelPromise newPromise() { + return MOCK_CHANNEL.newPromise(); + } + + private void assertForwards(ChannelPromise segmentPromise, ChannelPromise... requestPromises) { + for (ChannelPromise requestPromise : requestPromises) { + assertThat(requestPromise.isDone()).isFalse(); + } + segmentPromise.setSuccess(); + for (ChannelPromise requestPromise : requestPromises) { + assertThat(requestPromise.isSuccess()).isTrue(); + } + } + + // Test implementation that simply stores segments and promises in the order they were produced. + static class TestSegmentBuilder extends SegmentBuilder { + + List segments = new ArrayList(); + List segmentPromises = new ArrayList(); + + TestSegmentBuilder(ChannelHandlerContext context, int maxPayloadLength) { + super(context, ByteBufAllocator.DEFAULT, REQUEST_ENCODER, maxPayloadLength); + } + + @Override + protected void processSegment(Segment segment, ChannelPromise segmentPromise) { + segments.add(segment); + segmentPromises.add(segmentPromise); + } + } +} diff --git a/driver-core/src/test/java/com/datastax/driver/core/SegmentCodecTest.java b/driver-core/src/test/java/com/datastax/driver/core/SegmentCodecTest.java new file mode 100644 index 00000000000..72ce1f1b032 --- /dev/null +++ b/driver-core/src/test/java/com/datastax/driver/core/SegmentCodecTest.java @@ -0,0 +1,144 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +import com.datastax.driver.core.ProtocolOptions.Compression; +import com.datastax.driver.core.SegmentCodec.Header; +import com.datastax.driver.core.exceptions.CrcMismatchException; +import com.google.common.base.Strings; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.UnpooledByteBufAllocator; +import org.testng.annotations.Test; + +public class SegmentCodecTest { + + public static final SegmentCodec CODEC_NO_COMPRESSION = + new SegmentCodec(UnpooledByteBufAllocator.DEFAULT, Compression.NONE); + public static final SegmentCodec CODEC_LZ4 = + new SegmentCodec(UnpooledByteBufAllocator.DEFAULT, Compression.LZ4); + + @Test(groups = "unit") + public void should_encode_uncompressed_header() { + ByteBuf header = CODEC_NO_COMPRESSION.encodeHeader(5, -1, true); + + byte byte0 = header.getByte(2); + byte byte1 = header.getByte(1); + byte byte2 = header.getByte(0); + + assertThat(bits(byte0) + bits(byte1) + bits(byte2)) + .isEqualTo( + "000000" // padding (6 bits) + + "1" // selfContainedFlag + + "00000000000000101" // length (17 bits) + ); + } + + @Test(groups = "unit") + public void should_encode_compressed_header() { + ByteBuf header = CODEC_LZ4.encodeHeader(5, 12, true); + + byte byte0 = header.getByte(4); + byte byte1 = header.getByte(3); + byte byte2 = header.getByte(2); + byte byte3 = header.getByte(1); + byte byte4 = header.getByte(0); + + assertThat(bits(byte0) + bits(byte1) + bits(byte2) + bits(byte3) + bits(byte4)) + .isEqualTo( + "00000" // padding (5 bits) + + "1" // selfContainedFlag + + "00000000000001100" // uncompressed length (17 bits) + + "00000000000000101" // compressed length (17 bits) + ); + } + + /** + * Checks that we correctly use 8 bytes when we left-shift the uncompressed length, to avoid + * overflows. + */ + @Test(groups = "unit") + public void should_encode_compressed_header_when_aligned_uncompressed_length_overflows() { + ByteBuf header = CODEC_LZ4.encodeHeader(5, Segment.MAX_PAYLOAD_LENGTH, true); + + byte byte0 = header.getByte(4); + byte byte1 = header.getByte(3); + byte byte2 = header.getByte(2); + byte byte3 = header.getByte(1); + byte byte4 = header.getByte(0); + + assertThat(bits(byte0) + bits(byte1) + bits(byte2) + bits(byte3) + bits(byte4)) + .isEqualTo( + "00000" // padding (5 bits) + + "1" // selfContainedFlag + + "11111111111111111" // uncompressed length (17 bits) + + "00000000000000101" // compressed length (17 bits) + ); + } + + @Test(groups = "unit") + public void should_decode_uncompressed_payload() { + // Assembling the test data manually would have little value because it would be very similar to + // our production code. So simply use that production code, assuming it's correct. + ByteBuf buffer = CODEC_NO_COMPRESSION.encodeHeader(5, -1, true); + Header header = CODEC_NO_COMPRESSION.decodeHeader(buffer); + assertThat(header.payloadLength).isEqualTo(5); + assertThat(header.uncompressedPayloadLength).isEqualTo(-1); + assertThat(header.isSelfContained).isTrue(); + } + + @Test(groups = "unit") + public void should_decode_compressed_payload() { + ByteBuf buffer = CODEC_LZ4.encodeHeader(5, 12, true); + Header header = CODEC_LZ4.decodeHeader(buffer); + assertThat(header.payloadLength).isEqualTo(5); + assertThat(header.uncompressedPayloadLength).isEqualTo(12); + assertThat(header.isSelfContained).isTrue(); + } + + @Test(groups = "unit") + public void should_fail_to_decode_if_corrupted() { + ByteBuf buffer = CODEC_NO_COMPRESSION.encodeHeader(5, -1, true); + + // Flip a random byte + for (int bitOffset = 0; bitOffset < 47; bitOffset++) { + int byteOffset = bitOffset / 8; + int shift = bitOffset % 8; + + ByteBuf slice = buffer.slice(buffer.readerIndex() + byteOffset, 1); + slice.markReaderIndex(); + byte byteToCorrupt = slice.readByte(); + slice.resetReaderIndex(); + slice.writerIndex(slice.readerIndex()); + slice.writeByte((byteToCorrupt & 0xFF) ^ (1 << shift)); + + try { + CODEC_NO_COMPRESSION.decodeHeader(buffer.duplicate()); + fail("Expected CrcMismatchException"); + } catch (CrcMismatchException e) { + // expected + } + } + } + + private static String bits(byte b) { + return Strings.padStart(Integer.toBinaryString(b & 0xFF), 8, '0'); + } +} diff --git a/driver-core/src/test/java/com/datastax/driver/core/SegmentToFrameDecoderTest.java b/driver-core/src/test/java/com/datastax/driver/core/SegmentToFrameDecoderTest.java new file mode 100644 index 00000000000..bf0689dd04e --- /dev/null +++ b/driver-core/src/test/java/com/datastax/driver/core/SegmentToFrameDecoderTest.java @@ -0,0 +1,122 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +import static com.datastax.driver.core.Message.Response.Type.READY; +import static com.datastax.driver.core.Message.Response.Type.RESULT; +import static org.assertj.core.api.Assertions.assertThat; + +import com.datastax.driver.core.Frame.Header; +import com.datastax.driver.core.Frame.Header.Flag; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.UnpooledByteBufAllocator; +import io.netty.channel.embedded.EmbeddedChannel; +import java.util.EnumSet; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class SegmentToFrameDecoderTest { + + private static final ByteBuf SMALL_BODY_1 = buffer(128); + private static final Header SMALL_HEADER_1 = + new Header( + ProtocolVersion.V5, + EnumSet.noneOf(Flag.class), + 2, + READY.opcode, + SMALL_BODY_1.readableBytes()); + + private static final ByteBuf SMALL_BODY_2 = buffer(1024); + private static final Header SMALL_HEADER_2 = + new Header( + ProtocolVersion.V5, + EnumSet.noneOf(Flag.class), + 7, + RESULT.opcode, + SMALL_BODY_2.readableBytes()); + + private static final ByteBuf LARGE_BODY = buffer(256 * 1024); + private static final Header LARGE_HEADER = + new Header( + ProtocolVersion.V5, + EnumSet.noneOf(Flag.class), + 12, + RESULT.opcode, + LARGE_BODY.readableBytes()); + + private EmbeddedChannel channel; + + @BeforeMethod(groups = "unit") + public void setup() { + channel = new EmbeddedChannel(); + channel.pipeline().addLast(new SegmentToFrameDecoder()); + } + + @Test(groups = "unit") + public void should_decode_self_contained() { + ByteBuf payload = UnpooledByteBufAllocator.DEFAULT.buffer(); + appendFrame(SMALL_HEADER_1, SMALL_BODY_1, payload); + appendFrame(SMALL_HEADER_2, SMALL_BODY_2, payload); + + channel.writeInbound(new Segment(payload, true)); + + Frame frame1 = (Frame) channel.readInbound(); + Header header1 = frame1.header; + assertThat(header1.streamId).isEqualTo(SMALL_HEADER_1.streamId); + assertThat(header1.opcode).isEqualTo(SMALL_HEADER_1.opcode); + assertThat(frame1.body).isEqualTo(SMALL_BODY_1); + + Frame frame2 = (Frame) channel.readInbound(); + Header header2 = frame2.header; + assertThat(header2.streamId).isEqualTo(SMALL_HEADER_2.streamId); + assertThat(header2.opcode).isEqualTo(SMALL_HEADER_2.opcode); + assertThat(frame2.body).isEqualTo(SMALL_BODY_2); + } + + @Test(groups = "unit") + public void should_decode_sequence_of_slices() { + ByteBuf encodedFrame = UnpooledByteBufAllocator.DEFAULT.buffer(); + appendFrame(LARGE_HEADER, LARGE_BODY, encodedFrame); + + do { + ByteBuf payload = + encodedFrame.readSlice( + Math.min(Segment.MAX_PAYLOAD_LENGTH, encodedFrame.readableBytes())); + channel.writeInbound(new Segment(payload, false)); + } while (encodedFrame.isReadable()); + + Frame frame = (Frame) channel.readInbound(); + Header header = frame.header; + assertThat(header.streamId).isEqualTo(LARGE_HEADER.streamId); + assertThat(header.opcode).isEqualTo(LARGE_HEADER.opcode); + assertThat(frame.body).isEqualTo(LARGE_BODY); + } + + private static final ByteBuf buffer(int length) { + ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.buffer(length); + // Contents don't really matter, keep all zeroes + buffer.writerIndex(buffer.readerIndex() + length); + return buffer; + } + + private static void appendFrame(Header frameHeader, ByteBuf frameBody, ByteBuf payload) { + frameHeader.encodeInto(payload); + // this method doesn't affect the body's indices: + payload.writeBytes(frameBody, frameBody.readerIndex(), frameBody.readableBytes()); + } +} diff --git a/driver-core/src/test/java/com/datastax/driver/core/SessionAssert.java b/driver-core/src/test/java/com/datastax/driver/core/SessionAssert.java index c2e3348b3c7..4d4d8c7025e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SessionAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SessionAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/SessionErrorTest.java b/driver-core/src/test/java/com/datastax/driver/core/SessionErrorTest.java index 7225732ff7e..5fdeab5975e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SessionErrorTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SessionErrorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java b/driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java index cc6940575af..cbc0fadb927 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 +19,6 @@ import static com.datastax.driver.core.Assertions.assertThat; import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; -import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; import static com.google.common.collect.Lists.newArrayList; import static java.util.concurrent.TimeUnit.MINUTES; import static org.assertj.core.api.Assertions.fail; @@ -40,11 +41,8 @@ public void connectionLeakTest() throws Exception { channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS); Cluster cluster = register( - Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) + createClusterBuilderNoDebouncing() .withNettyOptions(channelMonitor.nettyOptions()) - .withQueryOptions(nonDebouncingQueryOptions()) .build()); cluster.init(); @@ -102,12 +100,7 @@ public void should_not_leak_session_when_wrong_keyspace() throws Exception { channelMonitor = new SocketChannelMonitor(); channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS); Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withPort(ccm().getBinaryPort()) - .withNettyOptions(channelMonitor.nettyOptions()) - .build()); + register(createClusterBuilder().withNettyOptions(channelMonitor.nettyOptions()).build()); cluster.init(); assertThat(cluster.manager.sessions.size()).isEqualTo(0); try { diff --git a/driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java b/driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java index b80ba5e2182..ca792c3eda1 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,9 +101,7 @@ public void sessions_should_not_leak_connections() { // override inherited field with a new cluster object and ensure 0 sessions and connections channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS); stressCluster = - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) + createClusterBuilder() .withPoolingOptions( new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1)) .withNettyOptions(channelMonitor.nettyOptions()) diff --git a/driver-core/src/test/java/com/datastax/driver/core/SessionTest.java b/driver-core/src/test/java/com/datastax/driver/core/SessionTest.java index 9608cdadac3..e71d90d8e08 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SessionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/SimpleJSONParserTest.java b/driver-core/src/test/java/com/datastax/driver/core/SimpleJSONParserTest.java index c16f9466c72..4a987dd875c 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SimpleJSONParserTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SimpleJSONParserTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/SimpleStatementIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/SimpleStatementIntegrationTest.java index cbbd716e554..591a393e877 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SimpleStatementIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SimpleStatementIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java b/driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java index 41c1639ac38..8f827c89fb0 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/SimpleStrategyTest.java b/driver-core/src/test/java/com/datastax/driver/core/SimpleStrategyTest.java index ff7819d6b9f..91cf49dc3ad 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SimpleStrategyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SimpleStrategyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/SingleConnectionPoolTest.java b/driver-core/src/test/java/com/datastax/driver/core/SingleConnectionPoolTest.java index 23442d3d641..21c5e79a324 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SingleConnectionPoolTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SingleConnectionPoolTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java index 95b2bd123f1..8992a3a7fbd 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/SortingLoadBalancingPolicy.java b/driver-core/src/test/java/com/datastax/driver/core/SortingLoadBalancingPolicy.java index 9a46325db63..cda97f77cc0 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SortingLoadBalancingPolicy.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SortingLoadBalancingPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,8 +36,8 @@ public class SortingLoadBalancingPolicy implements LoadBalancingPolicy { new Comparator() { @Override public int compare(Host host1, Host host2) { - byte[] address1 = host1.getAddress().getAddress(); - byte[] address2 = host2.getAddress().getAddress(); + byte[] address1 = host1.getEndPoint().resolve().getAddress().getAddress(); + byte[] address2 = host2.getEndPoint().resolve().getAddress().getAddress(); return UnsignedBytes.compare( address1[address1.length - 1], address2[address2.length - 1]); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java b/driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java index dcc9075caf2..75eae4bccac 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/StartupOptionTest.java b/driver-core/src/test/java/com/datastax/driver/core/StartupOptionTest.java index 06adc010449..b4a294d36de 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/StartupOptionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/StartupOptionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 @@ public void should_send_driver_name_and_version() { for (Row row : result) { assertThat(row.getString("driver_version")).isEqualTo(Cluster.getDriverVersion()); - assertThat(row.getString("driver_name")).isEqualTo("DataStax Java Driver"); + assertThat(row.getString("driver_name")).isEqualTo("Apache Cassandra Java Driver"); } } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/StateListenerBase.java b/driver-core/src/test/java/com/datastax/driver/core/StateListenerBase.java index a2504839ce7..24108ca0878 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/StateListenerBase.java +++ b/driver-core/src/test/java/com/datastax/driver/core/StateListenerBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java b/driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java index eb77f2bf2ca..bb05d3a4175 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/StatementIdempotenceTest.java b/driver-core/src/test/java/com/datastax/driver/core/StatementIdempotenceTest.java index fd4549d3957..20f0b99b3a6 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/StatementIdempotenceTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/StatementIdempotenceTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/StatementSizeTest.java b/driver-core/src/test/java/com/datastax/driver/core/StatementSizeTest.java index cd1b87dffb0..d824d2365c9 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/StatementSizeTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/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/driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java b/driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java index 82416c567f4..c19153c571f 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 @@ public void onTestContextInitialized() { @Override public Cluster.Builder createClusterBuilder() { - return Cluster.builder() + return super.createClusterBuilder() .withLoadBalancingPolicy(loadBalancingPolicy) .withSpeculativeExecutionPolicy(speculativeExecutionPolicy) .withRetryPolicy(retryPolicy); diff --git a/driver-core/src/test/java/com/datastax/driver/core/StreamIdGeneratorTest.java b/driver-core/src/test/java/com/datastax/driver/core/StreamIdGeneratorTest.java index f2bb147203b..278df134908 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/StreamIdGeneratorTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/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/driver-core/src/test/java/com/datastax/driver/core/TableMetadataAssert.java b/driver-core/src/test/java/com/datastax/driver/core/TableMetadataAssert.java index 5e82f5d4ba7..18ac9dbcb26 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TableMetadataAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TableMetadataAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/TableMetadataCDCTest.java b/driver-core/src/test/java/com/datastax/driver/core/TableMetadataCDCTest.java index b14236b8303..011f0f069fe 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TableMetadataCDCTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TableMetadataCDCTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java b/driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java index 53c5696d5e1..88717c72dd5 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -295,13 +297,41 @@ public void should_parse_compact_table_with_multiple_clustering_columns() { @Test(groups = "short") public void should_parse_table_options() { - VersionNumber version = TestUtils.findHost(cluster(), 1).getCassandraVersion(); + VersionNumber version = ccm().getCassandraVersion(); + VersionNumber dseVersion = ccm().getDSEVersion(); + boolean isRealCassandra4 = + version.getMajor() > 3 + && (dseVersion == null || dseVersion.compareTo(VersionNumber.parse("6.8")) >= 0); // given String cql; - // Cassandra 3.0 + - if (version.getMajor() > 2) { + // Cassandra 4.0 + + if (isRealCassandra4) { + cql = + String.format( + "CREATE TABLE %s.with_options (\n" + + " k text,\n" + + " c1 int,\n" + + " c2 int,\n" + + " i int,\n" + + " PRIMARY KEY (k, c1, c2)\n" + + ") WITH CLUSTERING ORDER BY (c1 DESC, c2 ASC)\n" + + " AND additional_write_policy = '99p'\n" + + " AND read_repair = 'BLOCKING'\n" + + " AND speculative_retry = '99.9p'\n" + + " AND gc_grace_seconds = 42\n" + + " AND bloom_filter_fp_chance = 0.01\n" + + " AND caching = { 'keys' : 'ALL', 'rows_per_partition' : 10 }\n" + + " AND comment = 'My awesome table'\n" + + " AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'sstable_size_in_mb' : 15 }\n" + + " AND compression = { 'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor', 'chunk_length_kb' : 128 }\n" + + " AND crc_check_chance = 0.5\n" // available from C* 3.0 + + " AND memtable_flush_period_in_ms = 1000;", + keyspace); + + // Cassandra 3.0 + + } else if (version.compareTo(VersionNumber.parse("3.0")) >= 0) { cql = String.format( "CREATE TABLE %s.with_options (\n" @@ -401,8 +431,62 @@ public void should_parse_table_options() { .hasType(cint()); assertThat(table); - // Cassandra 3.8 + - if (version.getMajor() > 3 || (version.getMajor() == 3 && version.getMinor() >= 8)) { + // Cassandra 4.0 + + if (isRealCassandra4) { + + assertThat(table.getOptions().getGcGraceInSeconds()).isEqualTo(42); + assertThat(table.getOptions().getBloomFilterFalsePositiveChance()).isEqualTo(0.01); + assertThat(table.getOptions().getComment()).isEqualTo("My awesome table"); + assertThat(table.getOptions().getCaching()).contains(entry("keys", "ALL")); + assertThat(table.getOptions().getCaching()).contains(entry("rows_per_partition", "10")); + assertThat(table.getOptions().getCompaction()) + .contains(entry("class", "org.apache.cassandra.db.compaction.LeveledCompactionStrategy")); + assertThat(table.getOptions().getCompaction()).contains(entry("sstable_size_in_mb", "15")); + assertThat(table.getOptions().getCompression()) + .contains( + entry( + "class", + "org.apache.cassandra.io.compress.SnappyCompressor")); // sstable_compression + // becomes class + assertThat(table.getOptions().getCompression()) + .contains(entry("chunk_length_in_kb", "128")); // note the "in" prefix + assertThat(table.getOptions().getDefaultTimeToLive()).isEqualTo(0); + assertThat(table.getOptions().getSpeculativeRetry()) + .isEqualTo(dseVersion == null ? "99.9p" : "99.9PERCENTILE"); + assertThat(table.getOptions().getIndexInterval()).isNull(); + assertThat(table.getOptions().getMinIndexInterval()).isEqualTo(128); + assertThat(table.getOptions().getMaxIndexInterval()).isEqualTo(2048); + assertThat(table.getOptions().getReplicateOnWrite()).isTrue(); // default + assertThat(table.getOptions().getCrcCheckChance()).isEqualTo(0.5); + assertThat(table.getOptions().getExtensions()).isEmpty(); // default + assertThat(table.getOptions().getMemtableFlushPeriodInMs()).isEqualTo(1000); + assertThat(table.asCQLQuery()) + .contains("additional_write_policy = '99p'") + .contains("read_repair = 'BLOCKING'") + .contains("gc_grace_seconds = 42") + .contains("bloom_filter_fp_chance = 0.01") + .contains("comment = 'My awesome table'") + .contains("'keys' : 'ALL'") + .contains("'rows_per_partition' : 10") + .contains("'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy'") + .contains("'sstable_size_in_mb' : 15") + .contains( + "'class' : 'org.apache.cassandra.io.compress.SnappyCompressor'") // sstable_compression becomes class + .contains("'chunk_length_in_kb' : 128") // note the "in" prefix + .contains("default_time_to_live = 0") + .contains( + dseVersion == null + ? "speculative_retry = '99.9p'" + : "speculative_retry = '99.9PERCENTILE'") + .contains("min_index_interval = 128") + .contains("max_index_interval = 2048") + .contains("crc_check_chance = 0.5") + .contains("cdc = false") + .contains("memtable_flush_period_in_ms = 1000") + .doesNotContain(" index_interval") + .doesNotContain("replicate_on_write"); + // Cassandra 3.8 + + } else if (version.compareTo(VersionNumber.parse("3.8")) >= 0) { assertThat(table.getOptions().getReadRepairChance()).isEqualTo(0.5); assertThat(table.getOptions().getLocalReadRepairChance()).isEqualTo(0.6); @@ -454,7 +538,7 @@ public void should_parse_table_options() { .doesNotContain(" index_interval") .doesNotContain("replicate_on_write"); // Cassandra 3.0 + - } else if (version.getMajor() > 2) { + } else if (version.compareTo(VersionNumber.parse("3.0")) >= 0) { assertThat(table.getOptions().getReadRepairChance()).isEqualTo(0.5); assertThat(table.getOptions().getLocalReadRepairChance()).isEqualTo(0.6); @@ -645,6 +729,18 @@ public void should_parse_table_options() { .doesNotContain("cdc") .doesNotContain("memtable_flush_period_in_ms"); // 2.0 + } + + // Also check that the generated CQL is valid and creates an identical table + session().execute("DROP TABLE " + table.getName()); + session().execute(table.asCQLQuery()); + TableMetadata actual = + cluster() + .getMetadata() + .getKeyspace(table.getKeyspace().getName()) + .getTable(table.getName()); + + assertThat(actual.getOptions()).isEqualTo(table.getOptions()); + assertThat(actual.asCQLQuery(true)).isEqualTo(table.asCQLQuery(true)); } /** diff --git a/driver-core/src/test/java/com/datastax/driver/core/TestListener.java b/driver-core/src/test/java/com/datastax/driver/core/TestListener.java index ea7135cbe25..3a05de58a9b 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TestListener.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TestListener.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/TestUtils.java b/driver-core/src/test/java/com/datastax/driver/core/TestUtils.java index 363bf5e9e29..6e1ff3a9588 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TestUtils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.SECONDS; +import com.datastax.driver.core.Cluster.Builder; import com.datastax.driver.core.policies.RoundRobinPolicy; import com.datastax.driver.core.policies.WhiteListPolicy; import com.google.common.base.Predicate; @@ -657,7 +660,7 @@ public static Host findOrWaitForHost( new StateListenerBase() { @Override public void onAdd(Host host) { - if (host.getAddress().getHostAddress().equals(address)) { + if (host.getEndPoint().resolve().getAddress().getHostAddress().equals(address)) { // for a new node, because of this we also listen for add events. addSignal.countDown(); } @@ -689,7 +692,7 @@ public static Host findHost(Cluster cluster, String address) { // create the Cluster // (JAVA-860 will solve that) for (Host host : cluster.getMetadata().allHosts()) { - if (host.getAddress().getHostAddress().equals(address)) return host; + if (host.getEndPoint().resolve().getAddress().getHostAddress().equals(address)) return host; } return null; } @@ -814,14 +817,42 @@ public static boolean pingPort(InetAddress address, int port) { public static Cluster buildControlCluster(Cluster cluster, CCMAccess ccm) { Host controlHost = cluster.manager.controlConnection.connectedHost(); List singleAddress = - Collections.singletonList(controlHost.getSocketAddress()); - return Cluster.builder() - .addContactPoints(controlHost.getSocketAddress().getAddress()) - .withPort(ccm.getBinaryPort()) + Collections.singletonList(controlHost.getEndPoint().resolve()); + return configureClusterBuilder(Cluster.builder(), ccm) .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress)) .build(); } + /** + * Configures the builder with one contact point and port matching the given CCM cluster. + * Therefore it's not required to call {@link Cluster.Builder#addContactPoints}, it will be done + * automatically. + * + * @return The cluster builder (for method chaining). + */ + public static Builder configureClusterBuilder(Builder builder, CCMAccess ccm) { + // add only one contact point to force node1 to become the control host; some tests rely on + // that. + return configureClusterBuilder(builder, ccm, ccm.getContactPoints().get(0)); + } + + /** + * Configures the builder with binary port matching the given CCM cluster and with the given + * contact points. Therefore it's not required to call {@link Cluster.Builder#addContactPoints}, + * it will be done automatically. + * + * @return The cluster builder (for method chaining). + */ + public static Builder configureClusterBuilder( + Builder builder, CCMAccess ccm, InetAddress... contactPoints) { + builder + // use a different codec registry for each cluster instance + .withCodecRegistry(new CodecRegistry()) + .addContactPoints(contactPoints) + .withPort(ccm.getBinaryPort()); + return builder; + } + /** @return a {@link QueryOptions} that disables debouncing by setting intervals to 0ms. */ public static QueryOptions nonDebouncingQueryOptions() { return new QueryOptions() @@ -868,6 +899,8 @@ public static void executeNoFail(Callable task, boolean logException) { task.call(); } catch (Exception e) { if (logException) logger.error(e.getMessage(), e); + } catch (AssertionError e) { + if (logException) logger.error(e.getMessage(), e); } } @@ -981,14 +1014,18 @@ public static Level setLogLevel(String logger, Level newLevel) { /** * Throws a {@link SkipException} if the input {@link CCMAccess} does not support compact storage - * (C* 4.0+) + * (C* 4.0+ or DSE 6.0+). * * @param ccm cluster to check against */ public static void compactStorageSupportCheck(CCMAccess ccm) { - if (ccm.getCassandraVersion().compareTo(VersionNumber.parse("4.0.0")) >= 0) { + if (ccm.getCassandraVersion().nextStable().compareTo(VersionNumber.parse("4.0")) >= 0) { throw new SkipException( "Compact tables are not allowed in Cassandra starting with 4.0 version"); } + if (ccm.getDSEVersion() != null + && ccm.getDSEVersion().compareTo(VersionNumber.parse("6.0")) >= 0) { + throw new SkipException("Compact tables are not allowed in DSE starting with 6.0 version"); + } } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGeneratorTest.java b/driver-core/src/test/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGeneratorTest.java index 51cdd02a49b..6fdf9378b49 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGeneratorTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGeneratorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/ThreadingOptionsTest.java b/driver-core/src/test/java/com/datastax/driver/core/ThreadingOptionsTest.java index 40313473105..f0bc1c9f3e7 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/ThreadingOptionsTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/ThreadingOptionsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java b/driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java index ecf36c2e87b..0111f5cedbf 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 +65,7 @@ public Cluster.Builder createClusterBuilder() { channelMonitor = register(new SocketChannelMonitor()); PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(HostDistance.LOCAL, 8, 8); - return Cluster.builder() + return super.createClusterBuilder() .withPoolingOptions(poolingOptions) .withNettyOptions(channelMonitor.nettyOptions()) .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)); diff --git a/driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java index d491b34e04b..f9bbeaa820a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -298,8 +300,8 @@ public void should_expose_tokens_per_host() { // Note that this relies on all queries going to node 1, which is why we use a WhiteList LBP // in setup(). boolean isControlHost = - host.getSocketAddress() - .equals(cluster().manager.controlConnection.connectionRef.get().address); + host.getEndPoint() + .equals(cluster().manager.controlConnection.connectionRef.get().endPoint); Row row; if (isControlHost) { row = session().execute("select tokens from system.local").one(); diff --git a/driver-core/src/test/java/com/datastax/driver/core/TokenRangeAssert.java b/driver-core/src/test/java/com/datastax/driver/core/TokenRangeAssert.java index 0c3647d6406..9dc25541311 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TokenRangeAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/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/driver-core/src/test/java/com/datastax/driver/core/TokenRangeTest.java b/driver-core/src/test/java/com/datastax/driver/core/TokenRangeTest.java index 6fd501f4b6a..4c0a9b8cb3c 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TokenRangeTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/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/driver-core/src/test/java/com/datastax/driver/core/TracingTest.java b/driver-core/src/test/java/com/datastax/driver/core/TracingTest.java index f8e09b689fb..14ae502546a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TracingTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TracingTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat; -import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy; +import com.datastax.driver.core.Cluster.Builder; import com.datastax.driver.core.utils.CassandraVersion; import com.google.common.util.concurrent.Uninterruptibles; import java.util.List; @@ -32,7 +34,12 @@ public class TracingTest extends CCMTestsSupport { @Override public Cluster.Builder createClusterBuilder() { - return Cluster.builder().withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); + @SuppressWarnings("deprecation") + Builder builder = + Cluster.builder() + .withRetryPolicy( + com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy.INSTANCE); + return builder; } @Override diff --git a/driver-core/src/test/java/com/datastax/driver/core/TrafficMetersTest.java b/driver-core/src/test/java/com/datastax/driver/core/TrafficMetersTest.java index 2dc3d7a632e..c503fb3fab1 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TrafficMetersTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TrafficMetersTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/TransientReplicationTest.java b/driver-core/src/test/java/com/datastax/driver/core/TransientReplicationTest.java new file mode 100644 index 00000000000..cd29bcf18e5 --- /dev/null +++ b/driver-core/src/test/java/com/datastax/driver/core/TransientReplicationTest.java @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.core; + +import static com.datastax.driver.core.Assertions.assertThat; +import static org.testng.Assert.fail; + +import com.datastax.driver.core.exceptions.InvalidQueryException; +import com.datastax.driver.core.schemabuilder.SchemaBuilder; +import com.datastax.driver.core.schemabuilder.TableOptions; +import com.datastax.driver.core.utils.CassandraVersion; +import com.google.common.collect.ImmutableMap; +import java.util.Map; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +@CassandraVersion(value = "4.0.0", description = "Transient Replication is for Cassandra 4.0+") +@CCMConfig(config = "enable_transient_replication:true") +public class TransientReplicationTest extends CCMTestsSupport { + + private static final String TRANSIENT_REPLICATION_KEYSPACE = "transient_rep_ks"; + + @BeforeClass(groups = "short") + public void createKeyspace() { + Map replicationOptions = + ImmutableMap.of("class", "SimpleStrategy", "replication_factor", "3/1"); + + // create keyspace + session() + .execute( + SchemaBuilder.createKeyspace(TRANSIENT_REPLICATION_KEYSPACE) + .with() + .replication(replicationOptions)); + + // verify the replication factor in the metadata + assertThat(cluster().getMetadata().getKeyspace(TRANSIENT_REPLICATION_KEYSPACE).getReplication()) + .containsEntry("replication_factor", "3/1"); + } + + @AfterClass(groups = "short") + public void dropKeyspace() { + session().execute("drop keyspace " + TRANSIENT_REPLICATION_KEYSPACE); + } + + @Test(groups = "short") + public void should_handle_read_reapir_none() { + // create a table with read_repair set to 'NONE' + Session session = cluster().connect(TRANSIENT_REPLICATION_KEYSPACE); + session.execute( + SchemaBuilder.createTable("valid_table") + .addPartitionKey("pk", DataType.text()) + .addColumn("data", DataType.text()) + .withOptions() + .readRepair(TableOptions.ReadRepairValue.NONE)); + TableOptionsMetadata options = + cluster() + .getMetadata() + .getKeyspace(TRANSIENT_REPLICATION_KEYSPACE) + .getTable("valid_table") + .getOptions(); + + assertThat(options.getReadRepair()).isEqualTo("NONE"); + // assert that the default additional_write_policy exists as well + assertThat(options.getAdditionalWritePolicy()).isEqualTo("99p"); + } + + @Test(groups = "short") + public void should_fail_to_create_table_with_read_repair_blocking() { + /** + * Attempt to create a table with the default read_repair 'BLOCKING'. This should fail when the + * keyspace uses transient replicas. + */ + try { + Session session = cluster().connect(TRANSIENT_REPLICATION_KEYSPACE); + session.execute( + SchemaBuilder.createTable("invalid_table") + .addPartitionKey("pk", DataType.text()) + .addColumn("data", DataType.text())); + fail( + "Create table with default read_repair ('BLOCKING') is not supported when keyspace uses transient replicas."); + } catch (InvalidQueryException iqe) { + assertThat(iqe) + .hasMessageContaining( + "read_repair must be set to 'NONE' for transiently replicated keyspaces"); + } + } +} diff --git a/driver-core/src/test/java/com/datastax/driver/core/TupleTest.java b/driver-core/src/test/java/com/datastax/driver/core/TupleTest.java index f37d2dcce5c..5c0188b90b5 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TupleTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TupleTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecAssert.java b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecAssert.java index 2394a0b92b1..cdfd42d68dd 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecCollectionsIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecCollectionsIntegrationTest.java index a571ff0f11f..2a2d6ea57dc 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecCollectionsIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecCollectionsIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecEncapsulationIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecEncapsulationIntegrationTest.java index 44c60a8b75e..5bfad36f6f4 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecEncapsulationIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecEncapsulationIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedCollectionsIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedCollectionsIntegrationTest.java index 0df90dfd088..4982b4e8772 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedCollectionsIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedCollectionsIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedUDTAndTupleIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedUDTAndTupleIntegrationTest.java index dca8d46ae86..05e7e42961e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedUDTAndTupleIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecNestedUDTAndTupleIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecNumbersIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecNumbersIntegrationTest.java index d3f009b560f..27161f030f2 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecNumbersIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecNumbersIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecOverlappingJavaTypeIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecOverlappingJavaTypeIntegrationTest.java index 3b25b25adc7..c67492ffa1d 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecOverlappingJavaTypeIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecOverlappingJavaTypeIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 @@ public void onTestContextInitialized() { } public Cluster.Builder createClusterBuilder() { - return Cluster.builder() + return super.createClusterBuilder() .withCodecRegistry(new CodecRegistry().register(new IntToStringCodec())); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecTest.java b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecTest.java index 5bae527b41f..68a172f44d8 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecTupleIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecTupleIntegrationTest.java index 3d7a68f7133..79bee457fe2 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecTupleIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecTupleIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,17 +99,13 @@ public void should_handle_partial_tuples_with_default_codecs() { @Test(groups = "short") public void should_handle_tuples_with_custom_codecs() { - CodecRegistry codecRegistry = new CodecRegistry(); - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withCodecRegistry(codecRegistry) - .build()); + Cluster cluster = register(createClusterBuilder().build()); Session session = cluster.connect(keyspace); setUpTupleTypes(cluster); - codecRegistry.register(new LocationCodec(TypeCodec.tuple(locationType))); + cluster + .getConfiguration() + .getCodecRegistry() + .register(new LocationCodec(TypeCodec.tuple(locationType))); session.execute(insertQuery, uuid, "John Doe", locationValue); ResultSet rows = session.execute(selectQuery, uuid); Row row = rows.one(); @@ -129,17 +127,13 @@ public void should_handle_tuples_with_custom_codecs() { @Test(groups = "short") public void should_handle_partial_tuples_with_custom_codecs() { - CodecRegistry codecRegistry = new CodecRegistry(); - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withCodecRegistry(codecRegistry) - .build()); + Cluster cluster = register(createClusterBuilder().build()); Session session = cluster.connect(keyspace); setUpTupleTypes(cluster); - codecRegistry.register(new LocationCodec(TypeCodec.tuple(locationType))); + cluster + .getConfiguration() + .getCodecRegistry() + .register(new LocationCodec(TypeCodec.tuple(locationType))); session.execute(insertQuery, uuid, "John Doe", partialLocationValueInserted); ResultSet rows = session.execute(selectQuery, uuid); Row row = rows.one(); diff --git a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecUDTIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecUDTIntegrationTest.java index c92580782d3..7c78bb8e33b 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/TypeCodecUDTIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/TypeCodecUDTIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -74,19 +76,14 @@ public void should_handle_udts_with_default_codecs() { @Test(groups = "short") public void should_handle_udts_with_custom_codecs() { - CodecRegistry codecRegistry = new CodecRegistry(); - Cluster cluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .withCodecRegistry(codecRegistry) - .build()); + Cluster cluster = register(createClusterBuilder().build()); Session session = cluster.connect(keyspace); setUpUserTypes(cluster); TypeCodec addressTypeCodec = TypeCodec.userType(addressType); TypeCodec phoneTypeCodec = TypeCodec.userType(phoneType); - codecRegistry + cluster + .getConfiguration() + .getCodecRegistry() .register(new AddressCodec(addressTypeCodec, Address.class)) .register(new PhoneCodec(phoneTypeCodec, Phone.class)); session.execute(insertQuery, uuid, "John Doe", address); diff --git a/driver-core/src/test/java/com/datastax/driver/core/UnresolvedUserTypeTest.java b/driver-core/src/test/java/com/datastax/driver/core/UnresolvedUserTypeTest.java index 5ce5355197d..32e7a454e30 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/UnresolvedUserTypeTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/UnresolvedUserTypeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -104,19 +106,12 @@ Creates the following acyclic graph (edges directed upwards public void should_resolve_nested_user_types() throws ExecutionException, InterruptedException { // Each CREATE TYPE statement in getTableDefinitions() has triggered a partial schema refresh - // that - // should have used previous UDT definitions for dependencies. + // that should have used previous UDT definitions for dependencies. checkUserTypes(cluster().getMetadata()); // Create a different Cluster instance to force a full refresh where all UDTs are loaded at - // once. - // The parsing logic should sort them to make sure they are loaded in the right order. - Cluster newCluster = - register( - Cluster.builder() - .addContactPoints(getContactPoints()) - .withPort(ccm().getBinaryPort()) - .build()); + // once. The parsing logic should sort them to make sure they are loaded in the right order. + Cluster newCluster = register(createClusterBuilder().build()); checkUserTypes(newCluster.getMetadata()); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java b/driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java index 3f783ca6f1c..a911253c187 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -604,4 +606,19 @@ public void should_indicate_user_type_is_not_frozen() { PreparedStatement pst = session().prepare("SELECT v FROM not_frozen_table WHERE k = ?"); assertThat(pst.getVariables().getType(0)).isNotFrozen(); } + + @Test(groups = "short") + public void should_handle_udt_named_like_a_collection() { + execute( + "CREATE TYPE tuple(a text)", + "CREATE TYPE list(a text)", + "CREATE TYPE frozen(a text)", + "CREATE TYPE udt(tuple frozen, frozen frozen, " + + "m map,frozen>)"); + UserType udt = cluster().getMetadata().getKeyspace(keyspace).getUserType("udt"); + assertThat(udt.getFieldType("tuple")).isInstanceOf(UserType.class); + assertThat(udt.getFieldType("frozen")).isInstanceOf(UserType.class); + assertThat((udt.getFieldType("m").getTypeArguments().get(0))).isInstanceOf(UserType.class); + assertThat((udt.getFieldType("m").getTypeArguments().get(1))).isInstanceOf(UserType.class); + } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/VersionNumberAssert.java b/driver-core/src/test/java/com/datastax/driver/core/VersionNumberAssert.java index b138e447eef..d2c8fea5373 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/VersionNumberAssert.java +++ b/driver-core/src/test/java/com/datastax/driver/core/VersionNumberAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/VersionNumberTest.java b/driver-core/src/test/java/com/datastax/driver/core/VersionNumberTest.java index 2494fada318..1f0e0cead5c 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/VersionNumberTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/VersionNumberTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/VirtualTableMetadataTest.java b/driver-core/src/test/java/com/datastax/driver/core/VirtualTableMetadataTest.java index fa3acc64337..55b99cdf93b 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/VirtualTableMetadataTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/VirtualTableMetadataTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/WarningsTest.java b/driver-core/src/test/java/com/datastax/driver/core/WarningsTest.java index f3db41a4c12..fbfea9afc80 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/WarningsTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/WarningsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 +25,6 @@ import org.testng.annotations.Test; @CCMConfig(config = {"batch_size_warn_threshold_in_kb:5"}) -@CassandraVersion("2.2.0") public class WarningsTest extends CCMTestsSupport { @Override @@ -32,22 +33,117 @@ public void onTestContextInitialized() { } @Test(groups = "short") - public void should_expose_warnings_on_execution_info() { + @CassandraVersion("2.2.0") + public void should_expose_warnings_on_execution_info() throws Exception { // the default batch size warn threshold is 5 * 1024 bytes, but after CASSANDRA-10876 there must - // be - // multiple mutations in a batch to trigger this warning so the batch includes 2 different + // be multiple mutations in a batch to trigger this warning so the batch includes 2 different // inserts. - ResultSet rs = - session() - .execute( - String.format( - "BEGIN UNLOGGED BATCH\n" - + "INSERT INTO foo (k, v) VALUES (1, '%s')\n" - + "INSERT INTO foo (k, v) VALUES (2, '%s')\n" - + "APPLY BATCH", - Strings.repeat("1", 2 * 1024), Strings.repeat("1", 3 * 1024))); - - List warnings = rs.getExecutionInfo().getWarnings(); - assertThat(warnings).hasSize(1); + final String query = + String.format( + "BEGIN UNLOGGED BATCH\n" + + "INSERT INTO foo (k, v) VALUES (1, '%s')\n" + + "INSERT INTO foo (k, v) VALUES (2, '%s')\n" + + "APPLY BATCH", + Strings.repeat("1", 2 * 1024), Strings.repeat("1", 3 * 1024)); + MemoryAppender logAppender = new MemoryAppender(); + logAppender.enableFor(RequestHandler.class); + try { + ResultSet rs = session().execute(query); + List warnings = rs.getExecutionInfo().getWarnings(); + // some versions of Cassandra will generate more than 1 log for this query + assertThat(warnings).isNotEmpty(); + // also assert that by default, the warning is logged and truncated to + // DEFAULT_MAX_QUERY_STRING_LENGTH + String log = logAppender.waitAndGet(2000); + assertThat(log).isNotEmpty(); + assertThat(log) + .startsWith("Query '") + // query will only be logged up to QueryLogger.DEFAULT_MAX_QUERY_STRING_LENGTH characters + .contains(query.substring(0, QueryLogger.DEFAULT_MAX_QUERY_STRING_LENGTH)) + .contains("' generated server side warning(s): ") + .contains("Batch") + .contains(keyspace + ".foo") + .contains(" is of size") + .contains(", exceeding specified threshold"); + } finally { + logAppender.disableFor(RequestHandler.class); + } + } + + @Test(groups = "short") + @CassandraVersion("3.0.0") + public void should_execute_query_and_log_server_side_warnings() throws Exception { + // Assert that logging of server-side query warnings is NOT disabled + assertThat(Boolean.getBoolean(RequestHandler.DISABLE_QUERY_WARNING_LOGS)).isFalse(); + + // Given a query that will produce server side warnings that will be embedded in the + // ExecutionInfo + final String query = "SELECT count(*) FROM foo;"; + SimpleStatement statement = new SimpleStatement(query); + // When the query is executed + MemoryAppender logAppender = new MemoryAppender(); + logAppender.enableFor(RequestHandler.class); + try { + ResultSet rs = session().execute(statement); + // Then the result has 1 Row + Row row = rs.one(); + assertThat(row).isNotNull(); + // And there is a server side warning captured in the ResultSet's ExecutionInfo + ExecutionInfo ei = rs.getExecutionInfo(); + List warnings = ei.getWarnings(); + assertThat(warnings).isNotEmpty(); + assertThat(warnings.size()).isEqualTo(1); + assertThat(warnings.get(0)).isEqualTo("Aggregation query used without partition key"); + // And the driver logged the server side warning + String log = logAppender.waitAndGet(2000); + assertThat(log).isNotEmpty(); + assertThat(log) + .startsWith( + "Query '[0 bound values] " + + query + + "' generated server side warning(s): Aggregation query used without partition key"); + } finally { + logAppender.disableFor(RequestHandler.class); + } + } + + @Test(groups = "isolated") + @CassandraVersion("3.0.0") + public void should_execute_query_and_not_log_server_side_warnings() throws Exception { + // Get the system property value for disabling logging server side warnings + final String disabledLogFlag = + System.getProperty(RequestHandler.DISABLE_QUERY_WARNING_LOGS, "false"); + // assert that logs are NOT disabled + assertThat(disabledLogFlag).isEqualTo("false"); + // Disable the logs + System.setProperty(RequestHandler.DISABLE_QUERY_WARNING_LOGS, "true"); + try { + // Given a query that will produce server side warnings that will be embedded in the + // ExecutionInfo + SimpleStatement statement = new SimpleStatement("SELECT count(*) FROM foo"); + // When the query is executed + MemoryAppender logAppender = new MemoryAppender(); + logAppender.enableFor(RequestHandler.class); + try { + ResultSet rs = session().execute(statement); + // Then the result has 1 Row + Row row = rs.one(); + assertThat(row).isNotNull(); + // And there is a server side warning captured in the ResultSet's ExecutionInfo + ExecutionInfo ei = rs.getExecutionInfo(); + List warnings = ei.getWarnings(); + assertThat(warnings).isNotEmpty(); + assertThat(warnings.size()).isEqualTo(1); + assertThat(warnings.get(0)).isEqualTo("Aggregation query used without partition key"); + // And the driver did NOT log the server side warning + String log = logAppender.waitAndGet(2000); + assertThat(log).isNullOrEmpty(); + } finally { + logAppender.disableFor(RequestHandler.class); + } + } finally { + // reset the logging flag + System.setProperty(RequestHandler.DISABLE_QUERY_WARNING_LOGS, disabledLogFlag); + } } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/cloud/CloudTest.java b/driver-core/src/test/java/com/datastax/driver/core/cloud/CloudTest.java new file mode 100644 index 00000000000..7e91543861c --- /dev/null +++ b/driver-core/src/test/java/com/datastax/driver/core/cloud/CloudTest.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.driver.core.cloud; + +import static com.datastax.driver.core.cloud.SniProxyServer.CERTS_BUNDLE_SUFFIX; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.any; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.EndPoint; +import com.datastax.driver.core.PlainTextAuthProvider; +import com.datastax.driver.core.ProtocolVersion; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.exceptions.AuthenticationException; +import com.github.tomakehurst.wiremock.WireMockServer; +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URL; +import org.parboiled.common.FileUtils; +import org.testng.annotations.AfterClass; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class CloudTest { + + private SniProxyServer proxy = new SniProxyServer(); + + private WireMockServer wireMockServer; + + @BeforeClass(groups = "short") + public void startProxy() { + proxy.startProxy(); + } + + @BeforeMethod(groups = "short") + public void startWireMock() { + wireMockServer = new WireMockServer(wireMockConfig().dynamicPort().dynamicHttpsPort()); + wireMockServer.start(); + } + + @AfterMethod(groups = "short") + public void stopWireMock() { + wireMockServer.stop(); + } + + @AfterClass(groups = "short", alwaysRun = true) + public void stopProxy() throws Exception { + proxy.stopProxy(); + } + + @Test(groups = "short") + public void should_connect_to_proxy_using_absolute_path() { + Session session = + Cluster.builder() + .withCloudSecureConnectBundle(proxy.getSecureBundleFile()) + .withProtocolVersion(ProtocolVersion.V4) + .build() + .connect(); + ResultSet set = session.execute("select * from system.local"); + assertThat(set).isNotNull(); + } + + @Test(groups = "short") + public void should_connect_to_proxy_using_non_normalized_path() { + String path = + String.format("%s/%s", proxy.getProxyRootPath(), "certs/bundles/../bundles/creds-v1.zip"); + Session session = + Cluster.builder() + .withCloudSecureConnectBundle(new File(path)) + .withProtocolVersion(ProtocolVersion.V4) + .build() + .connect(); + ResultSet set = session.execute("select * from system.local"); + assertThat(set).isNotNull(); + } + + @Test(groups = "short") + public void should_connect_to_proxy_using_file_provided_by_the_http_URL() throws IOException { + // given + wireMockServer.stubFor( + any(urlEqualTo(CERTS_BUNDLE_SUFFIX)) + .willReturn( + aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/octet-stream") + .withBody(FileUtils.readAllBytes(proxy.getSecureBundleFile())))); + + URL configFile = + new URL(String.format("http://localhost:%d%s", wireMockServer.port(), CERTS_BUNDLE_SUFFIX)); + + // when + Session session = + Cluster.builder() + .withCloudSecureConnectBundle(configFile) + .withProtocolVersion(ProtocolVersion.V4) + .build() + .connect(); + + // then + ResultSet set = session.execute("select * from system.local"); + assertThat(set).isNotNull(); + } + + @Test(groups = "short") + public void should_connect_to_proxy_using_file_provided_by_input_stream() throws IOException { + // given + wireMockServer.stubFor( + any(urlEqualTo(CERTS_BUNDLE_SUFFIX)) + .willReturn( + aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/octet-stream") + .withBody(FileUtils.readAllBytes(proxy.getSecureBundleFile())))); + + URL configFile = + new URL(String.format("http://localhost:%d%s", wireMockServer.port(), CERTS_BUNDLE_SUFFIX)); + + // when + Session session = + Cluster.builder() + .withCloudSecureConnectBundle(configFile.openStream()) + .withProtocolVersion(ProtocolVersion.V4) + .build() + .connect(); + + // then + ResultSet set = session.execute("select * from system.local"); + assertThat(set).isNotNull(); + } + + @Test(groups = "short") + public void should_connect_to_proxy_using_auth_provider() { + Session session = + Cluster.builder() + .withCloudSecureConnectBundle(proxy.getSecureBundleNoCredsPath()) + .withAuthProvider(new PlainTextAuthProvider("cassandra", "cassandra")) + .withProtocolVersion(ProtocolVersion.V4) + .build() + .connect(); + ResultSet set = session.execute("select * from system.local"); + assertThat(set).isNotNull(); + } + + @Test(groups = "short") + public void should_not_connect_to_proxy_bad_creds() { + try { + Session session = + Cluster.builder() + .withCloudSecureConnectBundle(proxy.getSecureBundleNoCredsPath()) + .withProtocolVersion(ProtocolVersion.V4) + .build() + .connect(); + fail("Expected an AuthenticationException"); + } catch (AuthenticationException e) { + assertThat(e).hasMessageStartingWith("Authentication error on host"); + } + } + + @Test(groups = "short") + public void should_not_connect_to_proxy() { + try { + Session session = + Cluster.builder() + .withCloudSecureConnectBundle(proxy.getSecureBundleUnreachable()) + .withProtocolVersion(ProtocolVersion.V4) + .build() + .connect(); + fail("Expected an IllegalStateException"); + } catch (IllegalStateException e) { + assertThat(e).hasMessageStartingWith("Cannot construct cloud config from the cloudConfigUrl"); + } + } + + @Test(groups = "short") + public void should_not_allow_contact_points_and_cloud() { + try { + Session session = + Cluster.builder() + .addContactPoint("127.0.0.1") + .withCloudSecureConnectBundle(proxy.getSecureBundleNoCredsPath()) + .withCredentials("cassandra", "cassandra") + .withProtocolVersion(ProtocolVersion.V4) + .build() + .connect(); + fail("Expected an IllegalStateException"); + } catch (IllegalStateException e) { + assertThat(e) + .hasMessageStartingWith( + "Can't use withCloudSecureConnectBundle if you've already called addContactPoint(s)"); + } + } + + @Test(groups = "short") + public void should_not_allow_cloud_with_contact_points_string() { + try { + Session session = + Cluster.builder() + .withCloudSecureConnectBundle(proxy.getSecureBundleNoCredsPath()) + .addContactPoint("127.0.0.1") + .withCredentials("cassandra", "cassandra") + .withProtocolVersion(ProtocolVersion.V4) + .build() + .connect(); + fail("Expected an IllegalStateException"); + } catch (IllegalStateException e) { + assertThat(e) + .hasMessageStartingWith( + "Can't use addContactPoint(s) if you've already called withCloudSecureConnectBundle"); + } + } + + @Test(groups = "short") + public void should_not_allow_cloud_with_contact_points_endpoint() { + try { + Session session = + Cluster.builder() + .withCloudSecureConnectBundle(proxy.getSecureBundleNoCredsPath()) + .addContactPoint( + new EndPoint() { + @Override + public InetSocketAddress resolve() { + return null; + } + }) + .withCredentials("cassandra", "cassandra") + .withProtocolVersion(ProtocolVersion.V4) + .build() + .connect(); + fail("Expected an IllegalStateException"); + } catch (IllegalStateException e) { + assertThat(e) + .hasMessageStartingWith( + "Can't use addContactPoint(s) if you've already called withCloudSecureConnectBundle"); + } + } +} diff --git a/driver-core/src/test/java/com/datastax/driver/core/cloud/SniProxyServer.java b/driver-core/src/test/java/com/datastax/driver/core/cloud/SniProxyServer.java new file mode 100644 index 00000000000..59c3e0c51e4 --- /dev/null +++ b/driver-core/src/test/java/com/datastax/driver/core/cloud/SniProxyServer.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.driver.core.cloud; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import org.apache.commons.exec.CommandLine; +import org.apache.commons.exec.DefaultExecutor; +import org.apache.commons.exec.ExecuteStreamHandler; +import org.apache.commons.exec.ExecuteWatchdog; +import org.apache.commons.exec.Executor; +import org.apache.commons.exec.LogOutputStream; +import org.apache.commons.exec.PumpStreamHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SniProxyServer { + private static final Logger logger = LoggerFactory.getLogger(SniProxyServer.class); + private final File proxyPath; + private boolean isRunning = false; + + static final String CERTS_BUNDLE_SUFFIX = "/certs/bundles/creds-v1.zip"; + + public SniProxyServer() { + proxyPath = new File(System.getProperty("proxy.path", "./")); + } + + public void startProxy() { + CommandLine run = CommandLine.parse(proxyPath + "/run.sh"); + execute(run); + isRunning = true; + } + + public void stopProxy() { + if (isRunning) { + CommandLine findImageId = + CommandLine.parse("docker ps -a -q --filter ancestor=single_endpoint"); + String id = execute(findImageId); + CommandLine stop = CommandLine.parse("docker kill " + id); + execute(stop); + isRunning = false; + } + } + + public boolean isRunning() { + return isRunning; + } + + public File getProxyRootPath() { + return proxyPath; + } + + public File getSecureBundleFile() { + return new File(proxyPath + CERTS_BUNDLE_SUFFIX); + } + + public File getSecureBundleNoCredsPath() { + return new File(proxyPath + "/certs/bundles/creds-v1-wo-creds.zip"); + } + + public File getSecureBundleUnreachable() { + return new File(proxyPath + "/certs/bundles/creds-v1-unreachable.zip"); + } + + private String execute(CommandLine cli) { + logger.debug("Executing: " + cli); + ExecuteWatchdog watchDog = new ExecuteWatchdog(TimeUnit.MINUTES.toMillis(10)); + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + LogOutputStream errStream = + new LogOutputStream() { + @Override + protected void processLine(String line, int logLevel) { + logger.error("sniendpointerr> {}", line); + } + }; + try { + Executor executor = new DefaultExecutor(); + ExecuteStreamHandler streamHandler = new PumpStreamHandler(outStream, errStream); + executor.setStreamHandler(streamHandler); + executor.setWatchdog(watchDog); + executor.setWorkingDirectory(proxyPath); + int retValue = executor.execute(cli); + if (retValue != 0) { + logger.error( + "Non-zero exit code ({}) returned from executing ccm command: {}", retValue, cli); + } + return outStream.toString(); + } catch (IOException ex) { + if (watchDog.killedProcess()) { + throw new RuntimeException("The command '" + cli + "' was killed after 10 minutes"); + } else { + throw new RuntimeException("The command '" + cli + "' failed to execute", ex); + } + } + } +} diff --git a/driver-core/src/test/java/com/datastax/driver/core/exceptions/ConnectionExceptionTest.java b/driver-core/src/test/java/com/datastax/driver/core/exceptions/ConnectionExceptionTest.java index ddaac252e5b..d8244526557 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/exceptions/ConnectionExceptionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/exceptions/ConnectionExceptionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; -import java.net.InetSocketAddress; +import com.datastax.driver.core.EndPoints; import org.testng.annotations.Test; public class ConnectionExceptionTest { @@ -26,7 +28,7 @@ public class ConnectionExceptionTest { /** @jira_ticket JAVA-1139 */ @Test(groups = "unit") public void getHost_should_return_null_if_address_is_null() { - assertNull(new ConnectionException(null, "Test message").getHost()); + assertNull(new ConnectionException(null, "Test message").getEndPoint()); } /** @jira_ticket JAVA-1139 */ @@ -39,17 +41,16 @@ public void getMessage_should_return_message_if_address_is_null() { @Test(groups = "unit") public void getMessage_should_return_message_if_address_is_unresolved() { assertEquals( - new ConnectionException( - InetSocketAddress.createUnresolved("127.0.0.1", 9042), "Test message") + new ConnectionException(EndPoints.forAddress("127.0.0.1", 9042), "Test message") .getMessage(), - "[127.0.0.1:9042] Test message"); + "[/127.0.0.1:9042] Test message"); } /** @jira_ticket JAVA-1139 */ @Test(groups = "unit") public void getMessage_should_return_message_if_address_is_resolved() { assertEquals( - new ConnectionException(new InetSocketAddress("127.0.0.1", 9042), "Test message") + new ConnectionException(EndPoints.forAddress("127.0.0.1", 9042), "Test message") .getMessage(), "[/127.0.0.1:9042] Test message"); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsScassandraTest.java b/driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsScassandraTest.java index e3326b1d1a7..1c9c5e87f9e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsScassandraTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsScassandraTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,59 +29,34 @@ import com.datastax.driver.core.Host; import com.datastax.driver.core.Metrics; import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.ScassandraCluster; +import com.datastax.driver.core.ScassandraTestBase; import com.datastax.driver.core.Session; import com.datastax.driver.core.TestUtils; import com.datastax.driver.core.WriteType; import com.datastax.driver.core.policies.FallthroughRetryPolicy; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import java.util.List; -import java.util.Map; -import org.scassandra.Scassandra; import org.scassandra.http.client.PrimingRequest; import org.scassandra.http.client.Result; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -public class ExceptionsScassandraTest { +public class ExceptionsScassandraTest extends ScassandraTestBase { - protected ScassandraCluster scassandras; protected Cluster cluster; protected Metrics.Errors errors; protected Host host1; protected Session session; - @BeforeClass(groups = "short") - public void beforeClass() { - scassandras = ScassandraCluster.builder().withNodes(1).build(); - scassandras.init(); - } - @BeforeMethod(groups = "short") public void beforeMethod() { - cluster = - Cluster.builder() - .addContactPoints(scassandras.address(1).getAddress()) - .withPort(scassandras.getBinaryPort()) - .withRetryPolicy(FallthroughRetryPolicy.INSTANCE) - .build(); + cluster = createClusterBuilder().withRetryPolicy(FallthroughRetryPolicy.INSTANCE).build(); session = cluster.connect(); host1 = TestUtils.findHost(cluster, 1); errors = cluster.getMetrics().getErrorMetrics(); - - for (Scassandra node : scassandras.nodes()) { - node.primingClient().clearAllPrimes(); - node.activityClient().clearAllRecordedActivity(); - } } @Test(groups = "short") public void should_throw_proper_unavailable_exception() { - simulateError(1, unavailable); + simulateError(unavailable); try { query(); fail("expected an UnavailableException"); @@ -90,32 +67,30 @@ public void should_throw_proper_unavailable_exception() { assertThat(e.getConsistencyLevel()).isEqualTo(LOCAL_ONE); assertThat(e.getAliveReplicas()).isEqualTo(0); assertThat(e.getRequiredReplicas()).isEqualTo(1); - assertThat(e.getAddress()).isEqualTo(host1.getSocketAddress()); - assertThat(e.getHost()).isEqualTo(host1.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(host1.getEndPoint()); } } @Test(groups = "short") public void should_throw_proper_read_timeout_exception() { - simulateError(1, read_request_timeout); + simulateError(read_request_timeout); try { query(); fail("expected a ReadTimeoutException"); } catch (ReadTimeoutException e) { assertThat(e.getMessage()) .isEqualTo( - "Cassandra timeout during read query at consistency LOCAL_ONE (1 responses were required but only 0 replica responded)"); + "Cassandra timeout during read query at consistency LOCAL_ONE (1 responses were required but only 0 replica responded). In case this was generated during read repair, the consistency level is not representative of the actual consistency."); assertThat(e.getConsistencyLevel()).isEqualTo(LOCAL_ONE); assertThat(e.getReceivedAcknowledgements()).isEqualTo(0); assertThat(e.getRequiredAcknowledgements()).isEqualTo(1); - assertThat(e.getAddress()).isEqualTo(host1.getSocketAddress()); - assertThat(e.getHost()).isEqualTo(host1.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(host1.getEndPoint()); } } @Test(groups = "short") public void should_throw_proper_write_timeout_exception() { - simulateError(1, write_request_timeout); + simulateError(write_request_timeout); try { query(); fail("expected a WriteTimeoutException"); @@ -127,44 +102,19 @@ public void should_throw_proper_write_timeout_exception() { assertThat(e.getReceivedAcknowledgements()).isEqualTo(0); assertThat(e.getRequiredAcknowledgements()).isEqualTo(1); assertThat(e.getWriteType()).isEqualTo(WriteType.SIMPLE); - assertThat(e.getAddress()).isEqualTo(host1.getSocketAddress()); - assertThat(e.getHost()).isEqualTo(host1.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(host1.getEndPoint()); } } - protected void simulateError(int hostNumber, Result result) { - scassandras - .node(hostNumber) - .primingClient() - .prime( - PrimingRequest.queryBuilder() - .withQuery("mock query") - .withThen(then().withResult(result)) - .build()); - } - - private static List> row(String key, String value) { - return ImmutableList.>of(ImmutableMap.of(key, value)); + private void simulateError(Result result) { + primingClient.prime( + PrimingRequest.queryBuilder() + .withQuery("mock query") + .withThen(then().withResult(result)) + .build()); } protected ResultSet query() { - return query(session); - } - - protected ResultSet query(Session session) { return session.execute("mock query"); } - - @AfterMethod(groups = "short", alwaysRun = true) - public void afterMethod() { - for (Scassandra node : scassandras.nodes()) { - node.primingClient().clearAllPrimes(); - } - if (cluster != null) cluster.close(); - } - - @AfterClass(groups = "short", alwaysRun = true) - public void afterClass() { - if (scassandras != null) scassandras.stop(); - } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsTest.java b/driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsTest.java index 1f7552bba3b..93a8bfd9672 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,16 +24,17 @@ import com.datastax.driver.core.CCMTestsSupport; import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.EndPoint; +import com.datastax.driver.core.EndPoints; import com.datastax.driver.core.TestUtils; import com.datastax.driver.core.WriteType; -import java.net.InetSocketAddress; import org.testng.annotations.Test; /** Tests Exception classes with separate clusters per test, when applicable */ public class ExceptionsTest extends CCMTestsSupport { - private InetSocketAddress address1 = new InetSocketAddress("127.0.0.1", 9042); - private InetSocketAddress address2 = new InetSocketAddress("127.0.0.2", 9042); + private EndPoint endPoint1 = EndPoints.forAddress("127.0.0.1", 9042); + private EndPoint endPoint2 = EndPoints.forAddress("127.0.0.2", 9042); /** * Tests the AlreadyExistsException. Create a keyspace twice and a table twice. Catch and test all @@ -63,8 +66,8 @@ public void alreadyExistsException() throws Throwable { assertEquals(e.getKeyspace(), keyspace.toLowerCase()); assertEquals(e.getTable(), null); assertEquals(e.wasTableCreation(), false); - assertEquals(e.getHost(), ccm().addressOfNode(1).getAddress()); - assertEquals(e.getAddress(), ccm().addressOfNode(1)); + assertEquals(e.getEndPoint().resolve().getAddress(), ccm().addressOfNode(1).getAddress()); + assertEquals(e.getEndPoint().resolve(), ccm().addressOfNode(1)); } session().execute(cqlCommands[1]); @@ -77,8 +80,8 @@ public void alreadyExistsException() throws Throwable { assertEquals(e.getKeyspace(), keyspace.toLowerCase()); assertEquals(e.getTable(), table.toLowerCase()); assertEquals(e.wasTableCreation(), true); - assertEquals(e.getHost(), ccm().addressOfNode(1).getAddress()); - assertEquals(e.getAddress(), ccm().addressOfNode(1)); + assertEquals(e.getEndPoint().resolve().getAddress(), ccm().addressOfNode(1).getAddress()); + assertEquals(e.getEndPoint().resolve(), ccm().addressOfNode(1)); } } @@ -127,48 +130,42 @@ public void driverInternalError() throws Exception { @Test(groups = "unit") public void should_create_proper_already_exists_exception_for_keyspaces() { - AlreadyExistsException e = new AlreadyExistsException(address1, "keyspace1", ""); + AlreadyExistsException e = new AlreadyExistsException(endPoint1, "keyspace1", ""); assertThat(e.getMessage()).isEqualTo("Keyspace keyspace1 already exists"); assertThat(e.getKeyspace()).isEqualTo("keyspace1"); assertThat(e.getTable()).isNull(); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); - e = e.copy(address2); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); + e = e.copy(endPoint2); assertThat(e.getMessage()).isEqualTo("Keyspace keyspace1 already exists"); assertThat(e.getKeyspace()).isEqualTo("keyspace1"); assertThat(e.getTable()).isNull(); - assertThat(e.getAddress()).isEqualTo(address2); - assertThat(e.getHost()).isEqualTo(address2.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(endPoint2); } @Test(groups = "unit") public void should_create_proper_already_exists_exception_for_tables() { - AlreadyExistsException e = new AlreadyExistsException(address1, "keyspace1", "table1"); + AlreadyExistsException e = new AlreadyExistsException(endPoint1, "keyspace1", "table1"); assertThat(e.getMessage()).isEqualTo("Table keyspace1.table1 already exists"); assertThat(e.getKeyspace()).isEqualTo("keyspace1"); assertThat(e.getTable()).isEqualTo("table1"); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); - e = e.copy(address2); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); + e = e.copy(endPoint2); assertThat(e.getMessage()).isEqualTo("Table keyspace1.table1 already exists"); assertThat(e.getKeyspace()).isEqualTo("keyspace1"); assertThat(e.getTable()).isEqualTo("table1"); - assertThat(e.getAddress()).isEqualTo(address2); - assertThat(e.getHost()).isEqualTo(address2.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(endPoint2); } @Test(groups = "unit") public void should_create_proper_bootstrapping_exception() { - BootstrappingException e = new BootstrappingException(address1, "Sorry mate"); + BootstrappingException e = new BootstrappingException(endPoint1, "Sorry mate"); assertThat(e.getMessage()) - .isEqualTo("Queried host (" + address1 + ") was bootstrapping: Sorry mate"); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); + .isEqualTo("Queried host (" + endPoint1 + ") was bootstrapping: Sorry mate"); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); e = e.copy(); assertThat(e.getMessage()) - .isEqualTo("Queried host (" + address1 + ") was bootstrapping: Sorry mate"); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); + .isEqualTo("Queried host (" + endPoint1 + ") was bootstrapping: Sorry mate"); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); } @Test(groups = "unit") @@ -197,134 +194,119 @@ public void should_create_proper_paging_state_exception() { @Test(groups = "unit") public void should_create_proper_invalid_configuration_in_query_exception() { InvalidConfigurationInQueryException e = - new InvalidConfigurationInQueryException(address1, "Bad, really bad"); + new InvalidConfigurationInQueryException(endPoint1, "Bad, really bad"); assertThat(e.getMessage()).isEqualTo("Bad, really bad"); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); InvalidQueryException e1 = (InvalidQueryException) e.copy(); assertThat(e1.getMessage()).isEqualTo("Bad, really bad"); } @Test(groups = "unit") public void should_create_proper_overloaded_exception() { - OverloadedException e = new OverloadedException(address1, "I'm busy"); + OverloadedException e = new OverloadedException(endPoint1, "I'm busy"); assertThat(e.getMessage()) - .isEqualTo("Queried host (" + address1 + ") was overloaded: I'm busy"); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); + .isEqualTo("Queried host (" + endPoint1 + ") was overloaded: I'm busy"); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); e = e.copy(); assertThat(e.getMessage()) - .isEqualTo("Queried host (" + address1 + ") was overloaded: I'm busy"); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); + .isEqualTo("Queried host (" + endPoint1 + ") was overloaded: I'm busy"); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); } @Test(groups = "unit") public void should_create_proper_syntax_error() { - SyntaxError e = new SyntaxError(address1, "Missing ) at EOF"); + SyntaxError e = new SyntaxError(endPoint1, "Missing ) at EOF"); assertThat(e.getMessage()).isEqualTo("Missing ) at EOF"); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); e = (SyntaxError) e.copy(); assertThat(e.getMessage()).isEqualTo("Missing ) at EOF"); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); } @Test(groups = "unit") public void should_create_proper_truncate_exception() { - TruncateException e = new TruncateException(address1, "I'm running headless now"); + TruncateException e = new TruncateException(endPoint1, "I'm running headless now"); assertThat(e.getMessage()).isEqualTo("I'm running headless now"); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); e = (TruncateException) e.copy(); assertThat(e.getMessage()).isEqualTo("I'm running headless now"); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); } @Test(groups = "unit") public void should_create_proper_unauthorized_exception() { - UnauthorizedException e = new UnauthorizedException(address1, "You talking to me?"); + UnauthorizedException e = new UnauthorizedException(endPoint1, "You talking to me?"); assertThat(e.getMessage()).isEqualTo("You talking to me?"); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); e = (UnauthorizedException) e.copy(); assertThat(e.getMessage()).isEqualTo("You talking to me?"); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); } @Test(groups = "unit") public void should_create_proper_unavailable_exception() { - UnavailableException e = new UnavailableException(address1, LOCAL_QUORUM, 3, 2); + UnavailableException e = new UnavailableException(endPoint1, LOCAL_QUORUM, 3, 2); assertThat(e.getMessage()) .isEqualTo( "Not enough replicas available for query at consistency LOCAL_QUORUM (3 required but only 2 alive)"); assertThat(e.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM); assertThat(e.getAliveReplicas()).isEqualTo(2); assertThat(e.getRequiredReplicas()).isEqualTo(3); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); - e = e.copy(address2); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); + e = e.copy(endPoint2); assertThat(e.getMessage()) .isEqualTo( "Not enough replicas available for query at consistency LOCAL_QUORUM (3 required but only 2 alive)"); assertThat(e.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM); assertThat(e.getAliveReplicas()).isEqualTo(2); assertThat(e.getRequiredReplicas()).isEqualTo(3); - assertThat(e.getAddress()).isEqualTo(address2); - assertThat(e.getHost()).isEqualTo(address2.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(endPoint2); } @Test(groups = "unit") public void should_create_proper_unprepared_exception() { - UnpreparedException e = new UnpreparedException(address1, "Caught me unawares"); + UnpreparedException e = new UnpreparedException(endPoint1, "Caught me unawares"); assertThat(e.getMessage()) .isEqualTo( "A prepared query was submitted on " - + address1 + + endPoint1 + " but was not known of that node: Caught me unawares"); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); e = e.copy(); assertThat(e.getMessage()) .isEqualTo( "A prepared query was submitted on " - + address1 + + endPoint1 + " but was not known of that node: Caught me unawares"); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); } @Test(groups = "unit") public void should_create_proper_read_timeout_exception() { - ReadTimeoutException e = new ReadTimeoutException(address1, LOCAL_QUORUM, 2, 3, true); + ReadTimeoutException e = new ReadTimeoutException(endPoint1, LOCAL_QUORUM, 2, 3, true); assertThat(e.getMessage()) - .isEqualTo( + .contains( "Cassandra timeout during read query at consistency LOCAL_QUORUM (3 responses were required but only 2 replica responded)"); assertThat(e.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM); assertThat(e.getReceivedAcknowledgements()).isEqualTo(2); assertThat(e.getRequiredAcknowledgements()).isEqualTo(3); assertThat(e.wasDataRetrieved()).isTrue(); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); - e = e.copy(address2); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); + e = e.copy(endPoint2); assertThat(e.getMessage()) - .isEqualTo( + .contains( "Cassandra timeout during read query at consistency LOCAL_QUORUM (3 responses were required but only 2 replica responded)"); assertThat(e.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM); assertThat(e.getReceivedAcknowledgements()).isEqualTo(2); assertThat(e.getRequiredAcknowledgements()).isEqualTo(3); assertThat(e.wasDataRetrieved()).isTrue(); - assertThat(e.getAddress()).isEqualTo(address2); - assertThat(e.getHost()).isEqualTo(address2.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(endPoint2); } @Test(groups = "unit") public void should_create_proper_write_timeout_exception() { WriteTimeoutException e = - new WriteTimeoutException(address1, LOCAL_QUORUM, WriteType.BATCH, 2, 3); + new WriteTimeoutException(endPoint1, LOCAL_QUORUM, WriteType.BATCH, 2, 3); assertThat(e.getMessage()) .isEqualTo( "Cassandra timeout during BATCH write query at consistency LOCAL_QUORUM (3 replica were required but only 2 acknowledged the write)"); @@ -332,9 +314,8 @@ public void should_create_proper_write_timeout_exception() { assertThat(e.getReceivedAcknowledgements()).isEqualTo(2); assertThat(e.getRequiredAcknowledgements()).isEqualTo(3); assertThat(e.getWriteType()).isEqualTo(WriteType.BATCH); - assertThat(e.getAddress()).isEqualTo(address1); - assertThat(e.getHost()).isEqualTo(address1.getAddress()); - e = e.copy(address2); + assertThat(e.getEndPoint()).isEqualTo(endPoint1); + e = e.copy(endPoint2); assertThat(e.getMessage()) .isEqualTo( "Cassandra timeout during BATCH write query at consistency LOCAL_QUORUM (3 replica were required but only 2 acknowledged the write)"); @@ -342,7 +323,6 @@ public void should_create_proper_write_timeout_exception() { assertThat(e.getReceivedAcknowledgements()).isEqualTo(2); assertThat(e.getRequiredAcknowledgements()).isEqualTo(3); assertThat(e.getWriteType()).isEqualTo(WriteType.BATCH); - assertThat(e.getAddress()).isEqualTo(address2); - assertThat(e.getHost()).isEqualTo(address2.getAddress()); + assertThat(e.getEndPoint()).isEqualTo(endPoint2); } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/exceptions/FunctionExecutionExceptionTest.java b/driver-core/src/test/java/com/datastax/driver/core/exceptions/FunctionExecutionExceptionTest.java index f7d1dd86059..bd217030c11 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/exceptions/FunctionExecutionExceptionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/exceptions/FunctionExecutionExceptionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/exceptions/NoHostAvailableExceptionTest.java b/driver-core/src/test/java/com/datastax/driver/core/exceptions/NoHostAvailableExceptionTest.java index 9e7569fd9d8..1740c17fb6d 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/exceptions/NoHostAvailableExceptionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/exceptions/NoHostAvailableExceptionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,8 +19,9 @@ import static org.assertj.core.api.Assertions.assertThat; +import com.datastax.driver.core.EndPoint; +import com.datastax.driver.core.EndPoints; import java.io.PrintWriter; -import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import org.testng.annotations.Test; @@ -84,10 +87,10 @@ public void should_build_formatted_message_with_stack_traces() { assertThat(message).contains("/127.0.0.2:9042\nmock stack trace 2\n"); } - private static Map buildMockErrors(int count) { - Map errors = new HashMap(); + private static Map buildMockErrors(int count) { + Map errors = new HashMap(); for (int i = 1; i <= count; i++) { - errors.put(new InetSocketAddress("127.0.0." + i, 9042), new MockError(i)); + errors.put(EndPoints.forAddress("127.0.0." + i, 9042), new MockError(i)); } return errors; } diff --git a/driver-core/src/test/java/com/datastax/driver/core/exceptions/ReadWriteFailureExceptionTest.java b/driver-core/src/test/java/com/datastax/driver/core/exceptions/ReadWriteFailureExceptionTest.java index f5dad556ad1..5805ef060ef 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/exceptions/ReadWriteFailureExceptionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/exceptions/ReadWriteFailureExceptionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java index 9c370f4e8aa..2ad6ee1435f 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/CloseableLoadBalancingPolicyTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/CloseableLoadBalancingPolicyTest.java index 475d5b2b153..0e155eb986a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/CloseableLoadBalancingPolicyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/CloseableLoadBalancingPolicyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,9 +42,7 @@ public void should_be_invoked_at_shutdown() { @Override public Cluster.Builder createClusterBuilder() { policy = new CloseMonitoringPolicy(Policies.defaultLoadBalancingPolicy()); - return Cluster.builder() - .addContactPoints(getContactPoints().get(0)) - .withLoadBalancingPolicy(policy); + return super.createClusterBuilder().withLoadBalancingPolicy(policy); } static class CloseMonitoringPolicy extends DelegatingLoadBalancingPolicy { diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/CustomRetryPolicyIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/CustomRetryPolicyIntegrationTest.java index 37b87e91e00..935d97f6e70 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/CustomRetryPolicyIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/CustomRetryPolicyIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -100,7 +102,7 @@ public void should_rethrow_on_client_timeouts() { assertThat(e.getMessage()) .isEqualTo( String.format( - "[%s] Timed out waiting for server response", host1.getSocketAddress())); + "[%s] Timed out waiting for server response", host1.getEndPoint().resolve())); } assertOnRequestErrorWasCalled(1, OperationTimedOutException.class); assertThat(errors.getRetries().getCount()).isEqualTo(0); @@ -144,7 +146,8 @@ public void should_rethrow_on_connection_error(CloseType closeType) { fail("expected a TransportException"); } catch (TransportException e) { assertThat(e.getMessage()) - .isEqualTo(String.format("[%s] Connection has been closed", host1.getSocketAddress())); + .isEqualTo( + String.format("[%s] Connection has been closed", host1.getEndPoint().resolve())); } assertOnRequestErrorWasCalled(1, TransportException.class); assertThat(errors.getRetries().getCount()).isEqualTo(0); diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java index 8c48b04b184..c662339b0ee 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,12 +48,12 @@ public class DCAwareRoundRobinPolicyTest { - Logger policyLogger = Logger.getLogger(DCAwareRoundRobinPolicy.class); - Level originalLevel; - MemoryAppender logs; - QueryTracker queryTracker; + private final Logger policyLogger = Logger.getLogger(DCAwareRoundRobinPolicy.class); + private Level originalLevel; + private MemoryAppender logs; + private QueryTracker queryTracker; - @Captor ArgumentCaptor> initHostsCaptor; + @Captor private ArgumentCaptor> initHostsCaptor; @BeforeMethod(groups = "short") public void setUp() { @@ -121,6 +123,7 @@ public void should_round_robin_within_local_dc() { public void should_not_use_remote_hosts_if_some_nodes_are_up_in_local_dc() { // given: a 10 node 2 DC cluster with DC policy with 2 remote hosts. ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5, 5).build(); + @SuppressWarnings("deprecation") Cluster cluster = builder() .addContactPoints(sCluster.address(1, 1).getAddress()) @@ -169,6 +172,7 @@ public void should_not_use_remote_hosts_if_some_nodes_are_up_in_local_dc() { public void should_round_robin_on_remote_hosts_when_no_up_nodes_in_local_dc() { // given: a 10 node 2 DC cluster with DC policy with 2 remote hosts. ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5, 5).build(); + @SuppressWarnings("deprecation") Cluster cluster = builder() .addContactPoints(sCluster.address(1, 1).getAddress()) @@ -218,6 +222,7 @@ public void should_only_use_remote_hosts_when_using_non_dc_local_cl(ConsistencyL // given: a 4 node 2 DC Cluster with a LB policy that specifies to not allow remote dcs for // a local consistency level. ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build(); + @SuppressWarnings("deprecation") Cluster cluster = builder() .addContactPoints(sCluster.address(1, 1).getAddress()) @@ -257,7 +262,7 @@ public void should_only_use_remote_hosts_when_using_non_dc_local_cl(ConsistencyL /** * Ensures that {@link DCAwareRoundRobinPolicy} will use remote hosts for non DC local Consistency - * Levels if {@link DCAwareRoundRobinPolicy.Builder#allowRemoteDCsForLocalConsistencyLevel} is + * Levels if {@code DCAwareRoundRobinPolicy.Builder#allowRemoteDCsForLocalConsistencyLevel} is * used. In the case that a DC local Consistency Level is provided a {@link * NoHostAvailableException} is raised. * @@ -271,6 +276,7 @@ public void should_use_remote_hosts_for_local_cl_when_allowed(ConsistencyLevel c // given: a 4 node 2 DC Cluster with a LB policy that specifies to allow remote dcs for // a local consistency level. ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build(); + @SuppressWarnings("deprecation") Cluster cluster = builder() .addContactPoints(sCluster.address(1, 1).getAddress()) @@ -317,6 +323,7 @@ public void should_use_remote_hosts_for_local_cl_when_allowed(ConsistencyLevel c public void should_not_send_requests_to_blacklisted_dc_using_host_filter_policy() { // given: a 6 node 3 DC cluster with a DCAwareRoundRobinPolicy that is filtering hosts in DC2. ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2, 2).build(); + @SuppressWarnings("deprecation") LoadBalancingPolicy loadBalancingPolicy = HostFilterPolicy.fromDCBlackList( DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build(), @@ -374,6 +381,7 @@ public void should_send_requests_to_whitelisted_dcs_using_host_filter_policy() { // given: a 6 node 3 DC cluster with a DCAwareRoundRobinPolicy that is whitelisting hosts in DC1 // and DC2. ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2, 2).build(); + @SuppressWarnings("deprecation") LoadBalancingPolicy loadBalancingPolicy = HostFilterPolicy.fromDCWhiteList( DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build(), diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java index 516b8629462..0de1477a186 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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_rethrow_unavailable_in_no_host_available_exception() { LoadBalancingPolicy firstHostOnlyPolicy = new WhiteListPolicy( Policies.defaultLoadBalancingPolicy(), - Collections.singletonList(host1.getSocketAddress())); + Collections.singletonList(host1.getEndPoint().resolve())); Cluster whiteListedCluster = Cluster.builder() @@ -161,7 +163,7 @@ public void should_rethrow_unavailable_in_no_host_available_exception() { fail("expected an NoHostAvailableException"); } catch (NoHostAvailableException e) { // ok - Throwable error = e.getErrors().get(host1.getSocketAddress()); + Throwable error = e.getErrors().get(host1.getEndPoint()); assertThat(error).isNotNull(); assertThat(error).isInstanceOf(UnavailableException.class); } @@ -212,18 +214,14 @@ public void should_try_next_host_on_client_timeouts() { } catch (NoHostAvailableException e) { assertThat(e.getErrors().keySet()) .hasSize(3) - .containsOnly( - host1.getSocketAddress(), host2.getSocketAddress(), host3.getSocketAddress()); + .containsOnly(host1.getEndPoint(), host2.getEndPoint(), host3.getEndPoint()); assertThat(e.getErrors().values()) .hasOnlyElementsOfType(OperationTimedOutException.class) .extractingResultOf("getMessage") .containsOnlyOnce( - String.format( - "[%s] Timed out waiting for server response", host1.getSocketAddress()), - String.format( - "[%s] Timed out waiting for server response", host2.getSocketAddress()), - String.format( - "[%s] Timed out waiting for server response", host3.getSocketAddress())); + String.format("[%s] Timed out waiting for server response", host1.getEndPoint()), + String.format("[%s] Timed out waiting for server response", host2.getEndPoint()), + String.format("[%s] Timed out waiting for server response", host3.getEndPoint())); } assertOnRequestErrorWasCalled(3, OperationTimedOutException.class); assertThat(errors.getRetries().getCount()).isEqualTo(3); @@ -252,8 +250,7 @@ public void should_try_next_host_on_server_side_error( } catch (NoHostAvailableException e) { assertThat(e.getErrors().keySet()) .hasSize(3) - .containsOnly( - host1.getSocketAddress(), host2.getSocketAddress(), host3.getSocketAddress()); + .containsOnly(host1.getEndPoint(), host2.getEndPoint(), host3.getEndPoint()); assertThat(e.getErrors().values()).hasOnlyElementsOfType(exception); } assertOnRequestErrorWasCalled(3, exception); @@ -316,8 +313,7 @@ public void should_try_next_host_on_connection_error(ClosedConnectionConfig.Clos } catch (NoHostAvailableException e) { assertThat(e.getErrors().keySet()) .hasSize(3) - .containsOnly( - host1.getSocketAddress(), host2.getSocketAddress(), host3.getSocketAddress()); + .containsOnly(host1.getEndPoint(), host2.getEndPoint(), host3.getEndPoint()); assertThat(e.getErrors().values()).hasOnlyElementsOfType(TransportException.class); } assertOnRequestErrorWasCalled(3, TransportException.class); diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingLoadBalancingPolicy.java b/driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingLoadBalancingPolicy.java index e2d7a3b3d86..538c55d0ca5 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingLoadBalancingPolicy.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingLoadBalancingPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingSpeculativeExecutionPolicy.java b/driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingSpeculativeExecutionPolicy.java index 341b97d3435..24a43f45b81 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingSpeculativeExecutionPolicy.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingSpeculativeExecutionPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java index 16efd0fe331..7d81152414f 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -409,18 +411,14 @@ public void should_try_next_host_on_client_timeouts() { } catch (NoHostAvailableException e) { assertThat(e.getErrors().keySet()) .hasSize(3) - .containsOnly( - host1.getSocketAddress(), host2.getSocketAddress(), host3.getSocketAddress()); + .containsOnly(host1.getEndPoint(), host2.getEndPoint(), host3.getEndPoint()); assertThat(e.getErrors().values()) .hasOnlyElementsOfType(OperationTimedOutException.class) .extractingResultOf("getMessage") .containsOnlyOnce( - String.format( - "[%s] Timed out waiting for server response", host1.getSocketAddress()), - String.format( - "[%s] Timed out waiting for server response", host2.getSocketAddress()), - String.format( - "[%s] Timed out waiting for server response", host3.getSocketAddress())); + String.format("[%s] Timed out waiting for server response", host1.getEndPoint()), + String.format("[%s] Timed out waiting for server response", host2.getEndPoint()), + String.format("[%s] Timed out waiting for server response", host3.getEndPoint())); } assertOnRequestErrorWasCalled(3, OperationTimedOutException.class); assertThat(errors.getRetries().getCount()).isEqualTo(3); @@ -459,8 +457,7 @@ public void should_try_next_host_on_server_side_error( } catch (NoHostAvailableException e) { assertThat(e.getErrors().keySet()) .hasSize(3) - .containsOnly( - host1.getSocketAddress(), host2.getSocketAddress(), host3.getSocketAddress()); + .containsOnly(host1.getEndPoint(), host2.getEndPoint(), host3.getEndPoint()); assertThat(e.getErrors().values()).hasOnlyElementsOfType(exception); } assertOnRequestErrorWasCalled(3, exception); @@ -489,8 +486,7 @@ public void should_try_next_host_on_connection_error(ClosedConnectionConfig.Clos } catch (NoHostAvailableException e) { assertThat(e.getErrors().keySet()) .hasSize(3) - .containsOnly( - host1.getSocketAddress(), host2.getSocketAddress(), host3.getSocketAddress()); + .containsOnly(host1.getEndPoint(), host2.getEndPoint(), host3.getEndPoint()); assertThat(e.getErrors().values()).hasOnlyElementsOfType(TransportException.class); } assertOnRequestErrorWasCalled(3, TransportException.class); diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslatorTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslatorTest.java index 5d91f205eeb..794bf7fc134 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslatorTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/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/driver-core/src/test/java/com/datastax/driver/core/policies/ErrorAwarePolicyIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/ErrorAwarePolicyIntegrationTest.java index c24c3dd44a9..ddfb57b2b64 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/ErrorAwarePolicyIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/ErrorAwarePolicyIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/FallthroughRetryPolicyIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/FallthroughRetryPolicyIntegrationTest.java index 514fc2f9dd9..45bd0ef8817 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/FallthroughRetryPolicyIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/FallthroughRetryPolicyIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -115,7 +117,7 @@ public void should_rethrow_on_client_timeouts() { assertThat(e.getMessage()) .isEqualTo( String.format( - "[%s] Timed out waiting for server response", host1.getSocketAddress())); + "[%s] Timed out waiting for server response", host1.getEndPoint().resolve())); } assertOnRequestErrorWasCalled(1, OperationTimedOutException.class); assertThat(errors.getRetries().getCount()).isEqualTo(0); @@ -159,7 +161,8 @@ public void should_rethrow_on_connection_error(CloseType closeType) { Fail.fail("expected a TransportException"); } catch (TransportException e) { assertThat(e.getMessage()) - .isEqualTo(String.format("[%s] Connection has been closed", host1.getSocketAddress())); + .isEqualTo( + String.format("[%s] Connection has been closed", host1.getEndPoint().resolve())); } assertOnRequestErrorWasCalled(1, TransportException.class); assertThat(errors.getRetries().getCount()).isEqualTo(0); diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/HostFilterPolicyTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/HostFilterPolicyTest.java index 5203c4b173e..27df4921974 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/HostFilterPolicyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/HostFilterPolicyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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.google.common.base.Predicates; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; -import java.net.InetSocketAddress; import java.util.Collection; import org.mockito.ArgumentCaptor; import org.mockito.Captor; @@ -45,10 +46,6 @@ public class HostFilterPolicyTest { @Mock Host host1, host2, host3; - InetSocketAddress address1 = InetSocketAddress.createUnresolved("192.168.1.1", 2345); - InetSocketAddress address2 = InetSocketAddress.createUnresolved("192.168.1.2", 9876); - InetSocketAddress address3 = InetSocketAddress.createUnresolved("192.168.1.3", 6666); - @Mock LoadBalancingPolicy wrappedPolicy; @Captor ArgumentCaptor> hostsCaptor; @@ -56,11 +53,6 @@ public class HostFilterPolicyTest { @BeforeMethod(groups = "unit") public void setup() { MockitoAnnotations.initMocks(this); - - when(host1.getSocketAddress()).thenReturn(address1); - when(host2.getSocketAddress()).thenReturn(address2); - when(host3.getSocketAddress()).thenReturn(address3); - when(wrappedPolicy.distance(any(Host.class))).thenReturn(HostDistance.LOCAL); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicyIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicyIntegrationTest.java index 101e0fb6d60..dc82c7c11cf 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicyIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicyIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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,7 +107,7 @@ public void should_not_retry_on_client_timeout_if_statement_non_idempotent() { assertThat(e.getMessage()) .isEqualTo( String.format( - "[%s] Timed out waiting for server response", host1.getSocketAddress())); + "[%s] Timed out waiting for server response", host1.getEndPoint().resolve())); } // Should not have even been called as statement was not idempotent. assertOnRequestErrorWasCalled(0, OperationTimedOutException.class); @@ -184,8 +186,7 @@ public void should_retry_on_server_error_if_statement_idempotent( } catch (NoHostAvailableException e) { assertThat(e.getErrors().keySet()) .hasSize(3) - .containsOnly( - host1.getSocketAddress(), host2.getSocketAddress(), host3.getSocketAddress()); + .containsOnly(host1.getEndPoint(), host2.getEndPoint(), host3.getEndPoint()); assertThat(e.getErrors().values()).hasOnlyElementsOfType(exception); } assertOnRequestErrorWasCalled(3, exception); @@ -208,7 +209,8 @@ public void should_not_retry_on_connection_error_if_statement_non_idempotent( Fail.fail("expected a TransportException"); } catch (TransportException e) { assertThat(e.getMessage()) - .isEqualTo(String.format("[%s] Connection has been closed", host1.getSocketAddress())); + .isEqualTo( + String.format("[%s] Connection has been closed", host1.getEndPoint().resolve())); } // Should not have even been called as statement was not idempotent. assertOnRequestErrorWasCalled(0, TransportException.class); @@ -233,8 +235,7 @@ public void should_retry_on_connection_error_if_statement_idempotent( } catch (NoHostAvailableException e) { assertThat(e.getErrors().keySet()) .hasSize(3) - .containsOnly( - host1.getSocketAddress(), host2.getSocketAddress(), host3.getSocketAddress()); + .containsOnly(host1.getEndPoint(), host2.getEndPoint(), host3.getEndPoint()); assertThat(e.getErrors().values()).hasOnlyElementsOfType(TransportException.class); } assertOnRequestErrorWasCalled(3, TransportException.class); diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/LatencyAwarePolicyTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/LatencyAwarePolicyTest.java index 5ec652238ad..4f4d41626e2 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/LatencyAwarePolicyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/LatencyAwarePolicyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -121,7 +123,7 @@ public void should_discard_latency_when_unavailable() throws Exception { fail("Should have thrown NoHostAvailableException"); } catch (NoHostAvailableException e) { // ok - Throwable error = e.getErrors().get(hostAddress); + Throwable error = e.getErrors().get(hostEndPoint); assertThat(error).isNotNull(); assertThat(error).isInstanceOf(UnavailableException.class); } diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/LimitingLoadBalancingPolicy.java b/driver-core/src/test/java/com/datastax/driver/core/policies/LimitingLoadBalancingPolicy.java index a079c7ed43c..ba8ba8188f0 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/LimitingLoadBalancingPolicy.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/LimitingLoadBalancingPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/LoggingRetryPolicyIntegrationTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/LoggingRetryPolicyIntegrationTest.java index 8ab0cb000a8..4a5f4617e4e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/LoggingRetryPolicyIntegrationTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/LoggingRetryPolicyIntegrationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -161,7 +163,7 @@ public void should_log_ignored_request_error() throws InterruptedException { IGNORING_REQUEST_ERROR, defaultCL, 0, - new ServerError(host1.getSocketAddress(), "Server Error").toString())); + new ServerError(host1.getEndPoint(), "Server Error").toString())); } @Test(groups = "short") @@ -178,7 +180,7 @@ public void should_log_retried_request_error() throws InterruptedException { LOCAL_ONE, defaultCL, 0, - new ServerError(host1.getSocketAddress(), "Server Error").toString())); + new ServerError(host1.getEndPoint(), "Server Error").toString())); } @Test(groups = "short") diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/RetryDecisionTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/RetryDecisionTest.java index 7b175ad1b16..221aa9b4f05 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/RetryDecisionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/RetryDecisionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/RollingCountTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/RollingCountTest.java index 4b9171b81ca..a2eb3e0b5cc 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/RollingCountTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/RollingCountTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/RoundRobinPolicyTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/RoundRobinPolicyTest.java index 9b7af208ea3..c1c133396b5 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/RoundRobinPolicyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/RoundRobinPolicyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java index d75f972904b..21f7f50118e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -275,6 +277,7 @@ public void should_choose_host_in_local_dc_when_using_network_topology_strategy_ .withNodes(3, 3) .withNetworkTopologyKeyspace("keyspace", ImmutableMap.of(1, 1, 2, 1)) .build(); + @SuppressWarnings("deprecation") Cluster cluster = Cluster.builder() .addContactPoints(sCluster.address(1).getAddress()) @@ -507,9 +510,7 @@ public void should_properly_generate_and_use_routing_key_for_composite_partition ccm.start(); Cluster cluster = - Cluster.builder() - .addContactPoints(ccm.addressOfNode(1).getAddress()) - .withPort(ccm.getBinaryPort()) + TestUtils.configureClusterBuilder(Cluster.builder(), ccm) .withNettyOptions(nonQuietClusterCloseOptions) .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())) .build(); diff --git a/driver-core/src/test/java/com/datastax/driver/core/policies/WhiteListPolicyTest.java b/driver-core/src/test/java/com/datastax/driver/core/policies/WhiteListPolicyTest.java index 17c558c9efb..ce4efca5c3c 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/policies/WhiteListPolicyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/policies/WhiteListPolicyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/BatchIdempotencyTest.java b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/BatchIdempotencyTest.java index 8c01ddfd195..2d48e143c77 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/BatchIdempotencyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/BatchIdempotencyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilder21ExecutionTest.java b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilder21ExecutionTest.java index 7855a71b3d1..85859dc3056 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilder21ExecutionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilder21ExecutionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java index 26c617945f2..f7b0d2690ec 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 static com.datastax.driver.core.querybuilder.QueryBuilder.token; import static com.datastax.driver.core.querybuilder.QueryBuilder.update; import static com.datastax.driver.core.schemabuilder.SchemaBuilder.createTable; +import static java.util.concurrent.TimeUnit.MINUTES; import static org.assertj.core.data.MapEntry.entry; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; @@ -43,7 +46,9 @@ import static org.testng.Assert.fail; import com.datastax.driver.core.CCMTestsSupport; +import com.datastax.driver.core.ConditionChecker; import com.datastax.driver.core.DataType; +import com.datastax.driver.core.MaterializedViewMetadata; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.RegularStatement; import com.datastax.driver.core.ResultSet; @@ -56,6 +61,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.Callable; import org.assertj.core.api.iterable.Extractor; import org.testng.annotations.Test; @@ -871,7 +877,7 @@ public void should_support_group_by() throws Exception { .groupBy("a", "clustering1")); fail("Expecting IQE"); } catch (InvalidQueryException e) { - assertThat(e.getMessage()).isEqualTo("Undefined column name clustering1"); + assertThat(e.getMessage()).startsWith("Undefined column name clustering1"); } try { @@ -886,7 +892,7 @@ public void should_support_group_by() throws Exception { .groupBy("a", "b", "z")); fail("Expecting IQE"); } catch (InvalidQueryException e) { - assertThat(e.getMessage()).isEqualTo("Undefined column name z"); + assertThat(e.getMessage()).startsWith("Undefined column name z"); } // Test with composite partition key @@ -924,4 +930,48 @@ public void should_support_group_by() throws Exception { .groupBy("b"))) .containsExactly(row(1, 1, 12)); } + + /** + * Validates that {@link QueryBuilder} can construct a SELECT query for a materialized view. + * + * @test_category queries:builder + * @jira_ticket JAVA-2123 + * @since 3.7.0 + */ + @CassandraVersion( + value = "3.0", + description = "Support for materialized views was added to C* 3.0") + @Test(groups = "short") + public void should_select_from_materialized_view() { + + String table = TestUtils.generateIdentifier("table"); + final String mv = TestUtils.generateIdentifier("mv"); + + execute( + String.format("CREATE TABLE %s (pk int, cc int, v int, PRIMARY KEY (pk, cc))", table), + String.format("INSERT INTO %s (pk, cc, v) VALUES (0,0,0)", table), + String.format("INSERT INTO %s (pk, cc, v) VALUES (0,1,1)", table), + String.format("INSERT INTO %s (pk, cc, v) VALUES (0,2,2)", table), + String.format( + "CREATE MATERIALIZED VIEW %s AS SELECT pk, cc FROM %s WHERE cc IS NOT NULL AND pk IS NOT NULL PRIMARY KEY (pk, cc)", + mv, table)); + + // Wait until the MV is fully constructed + ConditionChecker.check() + .that( + new Callable() { + @Override + public Boolean call() { + return session().execute("SELECT * FROM " + mv).all().size() == 3; + } + }) + .before(1, MINUTES) + .becomesTrue(); + + MaterializedViewMetadata materializedView = + session().getCluster().getMetadata().getKeyspace(keyspace).getMaterializedView(mv); + + assertThat(session().execute(select().column("cc").as("mycc").from(materializedView))) + .containsExactly(row(0), row(1), row(2)); + } } diff --git a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java index 5b8ca9704fb..a1f4d8a8bbe 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java index ab058c2d350..bbcc45ca170 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java index 16fbec07ee9..0bfd9493f04 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTupleExecutionTest.java b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTupleExecutionTest.java index 1fe68cc5b6d..40cf4156477 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTupleExecutionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTupleExecutionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderUDTExecutionTest.java b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderUDTExecutionTest.java index cbcc7960d34..66d64b66f7e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderUDTExecutionTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderUDTExecutionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/AlterKeyspaceTest.java b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/AlterKeyspaceTest.java index f2db19af96e..a1c5c50c0bf 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/AlterKeyspaceTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/AlterKeyspaceTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/AlterTest.java b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/AlterTest.java index 57e98221363..be41789af1a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/AlterTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/AlterTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CompactionOptionsTest.java b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CompactionOptionsTest.java index 01de6a8c3cc..001331bb15f 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CompactionOptionsTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CompactionOptionsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CompressionOptionsTest.java b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CompressionOptionsTest.java index 2560e333d05..49e46a2669e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CompressionOptionsTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CompressionOptionsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateIndexTest.java b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateIndexTest.java index 87c8c667edc..1dc8d408c10 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateIndexTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateIndexTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateKeyspaceTest.java b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateKeyspaceTest.java index 51f252c90bb..2a4a5f9a458 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateKeyspaceTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateKeyspaceTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateTest.java b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateTest.java index 3dcb578fae6..ee994ea5416 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateTypeTest.java b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateTypeTest.java index 202e3a6a816..e7936ac177f 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateTypeTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateTypeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/DropKeyspaceTest.java b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/DropKeyspaceTest.java index 3797111ef82..86a4ae6ceb3 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/DropKeyspaceTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/DropKeyspaceTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/DropTest.java b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/DropTest.java index b8f748075e9..46d33c4b00e 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/DropTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/DropTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/SchemaBuilderIT.java b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/SchemaBuilderIT.java index e4717e38185..42b8cc21290 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/SchemaBuilderIT.java +++ b/driver-core/src/test/java/com/datastax/driver/core/schemabuilder/SchemaBuilderIT.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/utils/CassandraVersion.java b/driver-core/src/test/java/com/datastax/driver/core/utils/CassandraVersion.java index 2ab3b89c989..93d3cfe3a2d 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/utils/CassandraVersion.java +++ b/driver-core/src/test/java/com/datastax/driver/core/utils/CassandraVersion.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/utils/DseVersion.java b/driver-core/src/test/java/com/datastax/driver/core/utils/DseVersion.java index e204e55679c..204c9a72215 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/utils/DseVersion.java +++ b/driver-core/src/test/java/com/datastax/driver/core/utils/DseVersion.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java b/driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java index 07977f58d6b..e012dfd516a 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java +++ b/driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDFromPropertyTest.java b/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDFromPropertyTest.java index 188a168aea5..5c36094bbbe 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDFromPropertyTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDFromPropertyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDNativeTest.java b/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDNativeTest.java index 473f96ff348..e8c6f74b244 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDNativeTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDNativeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDPropertyInvalidTest.java b/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDPropertyInvalidTest.java index 49724a2bd3f..64f502ad562 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDPropertyInvalidTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDPropertyInvalidTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsTest.java b/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsTest.java index f1cf7e92adf..e45785cc1e0 100644 --- a/driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsTest.java +++ b/driver-core/src/test/java/com/datastax/driver/core/utils/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, diff --git a/driver-core/src/test/resources/cloud/creds.zip b/driver-core/src/test/resources/cloud/creds.zip new file mode 100644 index 00000000000..3b5d1cb1cbd Binary files /dev/null and b/driver-core/src/test/resources/cloud/creds.zip differ diff --git a/driver-core/src/test/resources/cloud/identity.jks b/driver-core/src/test/resources/cloud/identity.jks new file mode 100644 index 00000000000..8aac969133a Binary files /dev/null and b/driver-core/src/test/resources/cloud/identity.jks differ diff --git a/driver-core/src/test/resources/cloud/metadata.json b/driver-core/src/test/resources/cloud/metadata.json new file mode 100644 index 00000000000..9573731ac3e --- /dev/null +++ b/driver-core/src/test/resources/cloud/metadata.json @@ -0,0 +1 @@ +{"region":"local","contact_info":{"type":"sni_proxy","local_dc":"dc1","contact_points":["4ac06655-f861-49f9-881e-3fee22e69b94","2af7c253-3394-4a0d-bfac-f1ad81b5154d","b17b6e2a-3f48-4d6a-81c1-20a0a1f3192a"],"sni_proxy_address":"localhost:30002"}} \ No newline at end of file diff --git a/driver-core/src/test/resources/cloud/trustStore.jks b/driver-core/src/test/resources/cloud/trustStore.jks new file mode 100644 index 00000000000..8c389a5dd00 Binary files /dev/null and b/driver-core/src/test/resources/cloud/trustStore.jks differ diff --git a/driver-core/src/test/resources/export_as_string_test_2.0.cql b/driver-core/src/test/resources/export_as_string_test_2.0.cql index 9ad5fe1a9a9..a2e180ad8af 100644 --- a/driver-core/src/test/resources/export_as_string_test_2.0.cql +++ b/driver-core/src/test/resources/export_as_string_test_2.0.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. + */ + CREATE KEYSPACE complex_ks WITH REPLICATION = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor': '1' } AND DURABLE_WRITES = true; CREATE TABLE complex_ks.rank_by_year_and_name ( diff --git a/driver-core/src/test/resources/export_as_string_test_2.1.cql b/driver-core/src/test/resources/export_as_string_test_2.1.cql index 89c4b7df256..71257fbdfd8 100644 --- a/driver-core/src/test/resources/export_as_string_test_2.1.cql +++ b/driver-core/src/test/resources/export_as_string_test_2.1.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. + */ + CREATE KEYSPACE complex_ks WITH REPLICATION = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor': '1' } AND DURABLE_WRITES = true; CREATE TYPE complex_ks.btype ( diff --git a/driver-core/src/test/resources/export_as_string_test_2.2.cql b/driver-core/src/test/resources/export_as_string_test_2.2.cql index 3257a4b9275..b86ee43b132 100644 --- a/driver-core/src/test/resources/export_as_string_test_2.2.cql +++ b/driver-core/src/test/resources/export_as_string_test_2.2.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. + */ + CREATE KEYSPACE complex_ks WITH REPLICATION = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor': '1' } AND DURABLE_WRITES = true; CREATE TYPE complex_ks.btype ( diff --git a/driver-core/src/test/resources/export_as_string_test_3.0.cql b/driver-core/src/test/resources/export_as_string_test_3.0.cql index b656ce9e6c7..90a91603e26 100644 --- a/driver-core/src/test/resources/export_as_string_test_3.0.cql +++ b/driver-core/src/test/resources/export_as_string_test_3.0.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. + */ + CREATE KEYSPACE complex_ks WITH REPLICATION = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor': '1' } AND DURABLE_WRITES = true; CREATE TYPE complex_ks.btype ( diff --git a/driver-core/src/test/resources/export_as_string_test_3.11.cql b/driver-core/src/test/resources/export_as_string_test_3.11.cql index 2bb2e726ae9..c7edb57bae0 100644 --- a/driver-core/src/test/resources/export_as_string_test_3.11.cql +++ b/driver-core/src/test/resources/export_as_string_test_3.11.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. + */ + CREATE KEYSPACE complex_ks WITH REPLICATION = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor': '1' } AND DURABLE_WRITES = true; CREATE TYPE complex_ks.btype ( diff --git a/driver-core/src/test/resources/export_as_string_test_4.0.cql b/driver-core/src/test/resources/export_as_string_test_4.0.cql new file mode 100644 index 00000000000..3c02a337113 --- /dev/null +++ b/driver-core/src/test/resources/export_as_string_test_4.0.cql @@ -0,0 +1,204 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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. + */ + +CREATE KEYSPACE complex_ks WITH REPLICATION = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor': '1' } AND DURABLE_WRITES = true; + +CREATE TYPE complex_ks.btype ( + a text +); + +CREATE TYPE complex_ks.xtype ( + d text +); + +CREATE TYPE complex_ks.ztype ( + c text, + a int +); + +CREATE TYPE complex_ks.ctype ( + "Z" frozen, + x frozen +); + +CREATE TYPE complex_ks.atype ( + c frozen +); + +CREATE TABLE complex_ks.cyclist_mv ( + cid uuid, + age int, + birthday date, + country text, + name text, + PRIMARY KEY (cid) +) WITH read_repair = 'BLOCKING' + AND gc_grace_seconds = 864000 + AND additional_write_policy = '99p' + AND bloom_filter_fp_chance = 0.01 + AND caching = { 'keys' : 'ALL', 'rows_per_partition' : 'NONE' } + AND comment = '' + AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold' : 32, 'min_threshold' : 4 } + AND compression = { 'chunk_length_in_kb' : 16, 'class' : 'org.apache.cassandra.io.compress.LZ4Compressor' } + AND default_time_to_live = 0 + AND speculative_retry = '99p' + AND min_index_interval = 128 + AND max_index_interval = 2048 + AND crc_check_chance = 1.0 + AND cdc = false + AND memtable_flush_period_in_ms = 0; + +CREATE INDEX cyclist_by_country ON complex_ks.cyclist_mv (country); + +CREATE MATERIALIZED VIEW complex_ks.cyclist_by_a_age AS + SELECT * + FROM complex_ks.cyclist_mv + WHERE age IS NOT NULL AND cid IS NOT NULL + PRIMARY KEY (age, cid) + WITH CLUSTERING ORDER BY (cid ASC) + AND read_repair = 'BLOCKING' + AND gc_grace_seconds = 864000 + AND additional_write_policy = '99p' + AND bloom_filter_fp_chance = 0.01 + AND caching = { 'keys' : 'ALL', 'rows_per_partition' : 'NONE' } + AND comment = '' + AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold' : 32, 'min_threshold' : 4 } + AND compression = { 'chunk_length_in_kb' : 16, 'class' : 'org.apache.cassandra.io.compress.LZ4Compressor' } + AND default_time_to_live = 0 + AND speculative_retry = '99p' + AND min_index_interval = 128 + AND max_index_interval = 2048 + AND crc_check_chance = 1.0 + AND cdc = false + AND memtable_flush_period_in_ms = 0; + +CREATE MATERIALIZED VIEW complex_ks.cyclist_by_age AS + SELECT age, cid, birthday, country, name + FROM complex_ks.cyclist_mv + WHERE age IS NOT NULL AND cid IS NOT NULL + PRIMARY KEY (age, cid) + WITH CLUSTERING ORDER BY (cid ASC) + AND read_repair = 'BLOCKING' + AND gc_grace_seconds = 864000 + AND additional_write_policy = '99p' + AND bloom_filter_fp_chance = 0.01 + AND caching = { 'keys' : 'ALL', 'rows_per_partition' : 'NONE' } + AND comment = 'simple view' + AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold' : 32, 'min_threshold' : 4 } + AND compression = { 'chunk_length_in_kb' : 16, 'class' : 'org.apache.cassandra.io.compress.LZ4Compressor' } + AND default_time_to_live = 0 + AND speculative_retry = '99p' + AND min_index_interval = 128 + AND max_index_interval = 2048 + AND crc_check_chance = 1.0 + AND cdc = false + AND memtable_flush_period_in_ms = 0; + +CREATE MATERIALIZED VIEW complex_ks.cyclist_by_r_age AS + SELECT age, cid, birthday, country, name + FROM complex_ks.cyclist_mv + WHERE age IS NOT NULL AND cid IS NOT NULL + PRIMARY KEY (age, cid) + WITH CLUSTERING ORDER BY (cid DESC) + AND read_repair = 'BLOCKING' + AND gc_grace_seconds = 864000 + AND additional_write_policy = '99p' + AND bloom_filter_fp_chance = 0.01 + AND caching = { 'keys' : 'ALL', 'rows_per_partition' : 'NONE' } + AND comment = '' + AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold' : 32, 'min_threshold' : 4 } + AND compression = { 'chunk_length_in_kb' : 16, 'class' : 'org.apache.cassandra.io.compress.LZ4Compressor' } + AND default_time_to_live = 0 + AND speculative_retry = '99p' + AND min_index_interval = 128 + AND max_index_interval = 2048 + AND crc_check_chance = 1.0 + AND cdc = false + AND memtable_flush_period_in_ms = 0; + +CREATE TABLE complex_ks.rank_by_year_and_name ( + race_year int, + race_name text, + rank int, + cyclist_name text, + PRIMARY KEY ((race_year, race_name), rank) +) WITH CLUSTERING ORDER BY (rank ASC) + AND read_repair = 'BLOCKING' + AND gc_grace_seconds = 864000 + AND additional_write_policy = '99p' + AND bloom_filter_fp_chance = 0.01 + AND caching = { 'keys' : 'ALL', 'rows_per_partition' : 'NONE' } + AND comment = '' + AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold' : 32, 'min_threshold' : 4 } + AND compression = { 'chunk_length_in_kb' : 16, 'class' : 'org.apache.cassandra.io.compress.LZ4Compressor' } + AND default_time_to_live = 0 + AND speculative_retry = '99p' + AND min_index_interval = 128 + AND max_index_interval = 2048 + AND crc_check_chance = 1.0 + AND cdc = false + AND memtable_flush_period_in_ms = 0; + +CREATE INDEX rrank ON complex_ks.rank_by_year_and_name (rank); + +CREATE INDEX ryear ON complex_ks.rank_by_year_and_name (race_year); + +CREATE TABLE complex_ks.ztable ( + zkey text, + a frozen, + PRIMARY KEY (zkey) +) WITH read_repair = 'BLOCKING' + AND gc_grace_seconds = 864000 + AND additional_write_policy = '99p' + AND bloom_filter_fp_chance = 0.1 + AND caching = { 'keys' : 'ALL', 'rows_per_partition' : 'NONE' } + AND comment = '' + AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'max_threshold' : 32, 'min_threshold' : 4, 'sstable_size_in_mb' : 95 } + AND compression = { 'chunk_length_in_kb' : 16, 'class' : 'org.apache.cassandra.io.compress.LZ4Compressor' } + AND default_time_to_live = 0 + AND speculative_retry = '99p' + AND min_index_interval = 128 + AND max_index_interval = 2048 + AND crc_check_chance = 1.0 + AND cdc = false + AND memtable_flush_period_in_ms = 0; + +CREATE FUNCTION complex_ks.avgfinal(state tuple) + CALLED ON NULL INPUT + RETURNS double + LANGUAGE java + AS 'double r = 0; if (state.getInt(0) == 0) return null; r = state.getLong(1); r /= state.getInt(0); return Double.valueOf(r);'; + +CREATE FUNCTION complex_ks.avgstate(state tuple,val int) + CALLED ON NULL INPUT + RETURNS tuple + LANGUAGE java + AS 'if (val !=null) { state.setInt(0, state.getInt(0)+1); state.setLong(1, state.getLong(1)+val.intValue()); } return state;'; + +CREATE AGGREGATE complex_ks.average(int) + SFUNC avgstate + STYPE tuple + FINALFUNC avgfinal + INITCOND (0,0); + +CREATE AGGREGATE complex_ks.mean(int) + SFUNC avgstate + STYPE tuple + FINALFUNC avgfinal + INITCOND (0,0); diff --git a/driver-core/src/test/resources/log4j.properties b/driver-core/src/test/resources/log4j.properties index 67195750ee6..b74fe275a0b 100644 --- a/driver-core/src/test/resources/log4j.properties +++ b/driver-core/src/test/resources/log4j.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/driver-core/src/test/resources/reference.conf b/driver-core/src/test/resources/reference.conf index 6da0ce3a055..4f5a14da64c 100644 --- a/driver-core/src/test/resources/reference.conf +++ b/driver-core/src/test/resources/reference.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. + # Adjust Scassandra's log level # (it seems some messages are conditioned by log4j.properties and others by reference.conf, so we need both) akka { diff --git a/driver-dist-source/pom.xml b/driver-dist-source/pom.xml new file mode 100644 index 00000000000..27297c8bb66 --- /dev/null +++ b/driver-dist-source/pom.xml @@ -0,0 +1,125 @@ + + + + 4.0.0 + + org.apache.cassandra + cassandra-driver-parent + 3.12.2-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/driver-dist-source/src/assembly/source-tarball.xml b/driver-dist-source/src/assembly/source-tarball.xml new file mode 100644 index 00000000000..b3e2d0f463a --- /dev/null +++ b/driver-dist-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/driver-dist/pom.xml b/driver-dist/pom.xml index 973f004090f..098e8be1a66 100644 --- a/driver-dist/pom.xml +++ b/driver-dist/pom.xml @@ -1,12 +1,14 @@ jar - DataStax Java Driver for Apache Cassandra - Binary distribution + Java Driver for Apache Cassandra - Binary distribution - - com.datastax.cassandra + org.apache.cassandra cassandra-driver-core - - com.datastax.cassandra + org.apache.cassandra cassandra-driver-mapping - - com.datastax.cassandra + org.apache.cassandra cassandra-driver-extras - - - cassandra-java-driver-${project.version} - + apache-cassandra-java-driver-${project.version} - maven-jar-plugin @@ -66,53 +61,38 @@ - maven-source-plugin true - maven-install-plugin true - maven-deploy-plugin true - + + maven-gpg-plugin + + true + + - - release - - maven-javadoc-plugin - - - dependencies-javadoc - package - - jar - - - true - - - - maven-assembly-plugin @@ -139,10 +119,34 @@ true + + net.nicoulaj.maven.plugins + checksum-maven-plugin + 1.7 + + + + artifacts + + + + + true + + sha256 + sha512 + + + + + maven-gpg-plugin + + false + + - diff --git a/driver-dist/src/assembly/binary-tarball.xml b/driver-dist/src/assembly/binary-tarball.xml index 4e9b78b48f4..baf4579ca55 100644 --- a/driver-dist/src/assembly/binary-tarball.xml +++ b/driver-dist/src/assembly/binary-tarball.xml @@ -1,12 +1,14 @@ - com.datastax.cassandra:cassandra-driver-core - com.datastax.cassandra:cassandra-driver-mapping - com.datastax.cassandra:cassandra-driver-extras + org.apache.cassandra:cassandra-driver-core + org.apache.cassandra:cassandra-driver-mapping + org.apache.cassandra:cassandra-driver-extras io.netty:netty-transport-native-epoll:* true + + lib + + + io.netty:netty-common:* + + true + @@ -55,7 +65,7 @@ true - com.datastax.cassandra:cassandra-driver-mapping + org.apache.cassandra:cassandra-driver-mapping false @@ -64,9 +74,9 @@ lib/mapping - com.datastax.cassandra:cassandra-driver-core - com.datastax.cassandra:cassandra-driver-mapping - com.datastax.cassandra:cassandra-driver-extras + org.apache.cassandra:cassandra-driver-core + org.apache.cassandra:cassandra-driver-mapping + org.apache.cassandra:cassandra-driver-extras com.google.guava:guava org.slf4j:slf4j-api @@ -81,7 +91,7 @@ true - com.datastax.cassandra:cassandra-driver-extras + org.apache.cassandra:cassandra-driver-extras false @@ -90,9 +100,9 @@ lib/extras - com.datastax.cassandra:cassandra-driver-core - com.datastax.cassandra:cassandra-driver-mapping - com.datastax.cassandra:cassandra-driver-extras + org.apache.cassandra:cassandra-driver-core + org.apache.cassandra:cassandra-driver-mapping + org.apache.cassandra:cassandra-driver-extras com.google.guava:guava org.slf4j:slf4j-api @@ -107,10 +117,10 @@ true - com.datastax.cassandra:cassandra-driver-core - com.datastax.cassandra:cassandra-driver-mapping - com.datastax.cassandra:cassandra-driver-extras - com.datastax.cassandra:cassandra-driver-examples + org.apache.cassandra:cassandra-driver-core + org.apache.cassandra:cassandra-driver-mapping + org.apache.cassandra:cassandra-driver-extras + org.apache.cassandra:cassandra-driver-examples false @@ -127,17 +137,13 @@ - - target/apidocs - apidocs - - .. . README* - LICENSE* + LICENSE_binary + NOTICE_binary.txt diff --git a/driver-examples/README.md b/driver-examples/README.md index 553cdbc5117..63e8c59726c 100644 --- a/driver-examples/README.md +++ b/driver-examples/README.md @@ -1,6 +1,25 @@ -# DataStax Java Driver for Apache Cassandra - Examples + + +# Java Driver for Apache Cassandra - Examples + +This module contains examples of how to use the Java Driver for Apache Cassandra. ## Usage diff --git a/driver-examples/pom.xml b/driver-examples/pom.xml index f2d18e738af..a5508fa9d9b 100644 --- a/driver-examples/pom.xml +++ b/driver-examples/pom.xml @@ -1,12 +1,14 @@ - com.datastax.cassandra + org.apache.cassandra cassandra-driver-core - com.datastax.cassandra + org.apache.cassandra cassandra-driver-extras true @@ -134,6 +136,22 @@ + + + src/main/resources + + + ${project.basedir}/.. + + LICENSE_binary + LICENSE + NOTICE_binary.txt + NOTICE.txt + + META-INF + + + @@ -152,13 +170,6 @@ - - maven-javadoc-plugin - - true - - - maven-gpg-plugin diff --git a/driver-examples/src/main/java/com/datastax/driver/examples/astra/AstraReadCassandraVersion.java b/driver-examples/src/main/java/com/datastax/driver/examples/astra/AstraReadCassandraVersion.java new file mode 100644 index 00000000000..dea5ec9fde6 --- /dev/null +++ b/driver-examples/src/main/java/com/datastax/driver/examples/astra/AstraReadCassandraVersion.java @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this 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.driver.examples.astra; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import java.io.File; + +/** + * Connects to a DataStax Astra cluster and extracts basic information from it. + * + *

Preconditions: + * + *

    + *
  • A DataStax Astra cluster is running and accessible. + *
  • A DataStax Astra secure connect bundle for the running cluster. + *
+ * + *

Side effects: none. + * + * @see Creating an + * Astra Database + * @see + * Providing access to Astra databases + * @see + * Obtaining Astra secure connect bundle + * @see Java Driver online manual + */ +public class AstraReadCassandraVersion { + + public static void main(String[] args) { + + Cluster cluster = null; + try { + // The Cluster object is the main entry point of the driver. + // It holds the known state of the actual Cassandra cluster (notably the Metadata). + // This class is thread-safe, you should create a single instance (per target Cassandra + // cluster), and share it throughout your application. + // Change the path here to the secure connect bundle location (see javadocs above) + cluster = + Cluster.builder() + // Change the path here to the secure connect bundle location (see javadocs above) + .withCloudSecureConnectBundle(new File("/path/to/secure-connect-database_name.zip")) + // Change the user_name and password here for the Astra instance + .withCredentials("user_name", "password") + // Uncomment the next line to use a specific keyspace + // .withKeyspace("keyspace_name") + .build(); + + // The Session is what you use to execute queries. Likewise, it is thread-safe and should be + // reused. + Session session = cluster.connect(); + + // We use execute to send a query to Cassandra. This returns a ResultSet, which is essentially + // a collection of Row objects. + ResultSet rs = session.execute("select release_version from system.local"); + // Extract the first row (which is the only one in this case). + Row row = rs.one(); + + // Extract the value of the first (and only) column from the row. + String releaseVersion = row.getString("release_version"); + System.out.printf("Cassandra version is: %s%n", releaseVersion); + + } finally { + // Close the cluster after we’re done with it. This will also close any session that was + // created from this cluster. + // This step is important because it frees underlying resources (TCP connections, thread + // pools...). In a real application, you would typically do this at shutdown (for example, + // when undeploying your webapp). + if (cluster != null) cluster.close(); + } + } +} diff --git a/driver-examples/src/main/java/com/datastax/driver/examples/basic/CreateAndPopulateKeyspace.java b/driver-examples/src/main/java/com/datastax/driver/examples/basic/CreateAndPopulateKeyspace.java index bfeb0240573..d4a7c8d97cd 100644 --- a/driver-examples/src/main/java/com/datastax/driver/examples/basic/CreateAndPopulateKeyspace.java +++ b/driver-examples/src/main/java/com/datastax/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, @@ -30,7 +32,7 @@ * already exists, it will be reused; - creates two tables "simplex.songs" and "simplex.playlists". * If they exist already, they will be reused; - inserts a row in each table. * - * @see Java driver online manual + * @see Java Driver online manual */ public class CreateAndPopulateKeyspace { diff --git a/driver-examples/src/main/java/com/datastax/driver/examples/basic/ReadCassandraVersion.java b/driver-examples/src/main/java/com/datastax/driver/examples/basic/ReadCassandraVersion.java index 39b88dee09e..74d9d17cbbf 100644 --- a/driver-examples/src/main/java/com/datastax/driver/examples/basic/ReadCassandraVersion.java +++ b/driver-examples/src/main/java/com/datastax/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, @@ -28,7 +30,7 @@ * *

Side effects: none. * - * @see Java driver online manual + * @see Java Driver online manual */ public class ReadCassandraVersion { diff --git a/driver-examples/src/main/java/com/datastax/driver/examples/basic/ReadTopologyAndSchemaMetadata.java b/driver-examples/src/main/java/com/datastax/driver/examples/basic/ReadTopologyAndSchemaMetadata.java index e151ac02858..aee6d5d737f 100644 --- a/driver-examples/src/main/java/com/datastax/driver/examples/basic/ReadTopologyAndSchemaMetadata.java +++ b/driver-examples/src/main/java/com/datastax/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, @@ -30,7 +32,7 @@ * *

Side effects: none. * - * @see Java driver online manual + * @see Java Driver online manual */ public class ReadTopologyAndSchemaMetadata { @@ -49,7 +51,7 @@ public static void main(String[] args) { for (Host host : metadata.getAllHosts()) { System.out.printf( "Datatacenter: %s; Host: %s; Rack: %s%n", - host.getDatacenter(), host.getAddress(), host.getRack()); + host.getDatacenter(), host.getEndPoint(), host.getRack()); } for (KeyspaceMetadata keyspace : metadata.getKeyspaces()) { diff --git a/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java b/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java index 18b9d0784e3..e28120295aa 100644 --- a/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java +++ b/driver-examples/src/main/java/com/datastax/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, @@ -34,7 +36,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. {@code * - * com.datastax.cassandra + * org.apache.cassandra * cassandra-driver-extras * ${driver.version} * diff --git a/driver-examples/src/main/java/com/datastax/driver/examples/json/JacksonJsonFunction.java b/driver-examples/src/main/java/com/datastax/driver/examples/json/JacksonJsonFunction.java index 94a20ae99ba..bd94e716d1e 100644 --- a/driver-examples/src/main/java/com/datastax/driver/examples/json/JacksonJsonFunction.java +++ b/driver-examples/src/main/java/com/datastax/driver/examples/json/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, @@ -47,7 +49,7 @@ * *

{@code
  * 
- *     com.datastax.cassandra
+ *     org.apache.cassandra
  *     cassandra-driver-extras
  *     ${driver.version}
  * 
diff --git a/driver-examples/src/main/java/com/datastax/driver/examples/json/JacksonJsonRow.java b/driver-examples/src/main/java/com/datastax/driver/examples/json/JacksonJsonRow.java
index f2b6048912b..32d44d28eee 100644
--- a/driver-examples/src/main/java/com/datastax/driver/examples/json/JacksonJsonRow.java
+++ b/driver-examples/src/main/java/com/datastax/driver/examples/json/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,
@@ -43,7 +45,7 @@
  *
  * 
{@code
  * 
- *     com.datastax.cassandra
+ *     org.apache.cassandra
  *     cassandra-driver-extras
  *     ${driver.version}
  * 
diff --git a/driver-examples/src/main/java/com/datastax/driver/examples/json/Jsr353JsonColumn.java b/driver-examples/src/main/java/com/datastax/driver/examples/json/Jsr353JsonColumn.java
index 101e6a51585..5eb58ffabea 100644
--- a/driver-examples/src/main/java/com/datastax/driver/examples/json/Jsr353JsonColumn.java
+++ b/driver-examples/src/main/java/com/datastax/driver/examples/json/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,
@@ -44,7 +46,7 @@
  *
  * 
{@code
  * 
- *     com.datastax.cassandra
+ *     org.apache.cassandra
  *     cassandra-driver-extras
  *     ${driver.version}
  * 
diff --git a/driver-examples/src/main/java/com/datastax/driver/examples/json/Jsr353JsonFunction.java b/driver-examples/src/main/java/com/datastax/driver/examples/json/Jsr353JsonFunction.java
index b78928da63d..377f82764d4 100644
--- a/driver-examples/src/main/java/com/datastax/driver/examples/json/Jsr353JsonFunction.java
+++ b/driver-examples/src/main/java/com/datastax/driver/examples/json/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,
@@ -45,7 +47,7 @@
  *
  * 
{@code
  * 
- *     com.datastax.cassandra
+ *     org.apache.cassandra
  *     cassandra-driver-extras
  *     ${driver.version}
  * 
diff --git a/driver-examples/src/main/java/com/datastax/driver/examples/json/Jsr353JsonRow.java b/driver-examples/src/main/java/com/datastax/driver/examples/json/Jsr353JsonRow.java
index 15a45c53c97..05aa1cea1ab 100644
--- a/driver-examples/src/main/java/com/datastax/driver/examples/json/Jsr353JsonRow.java
+++ b/driver-examples/src/main/java/com/datastax/driver/examples/json/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,
@@ -44,7 +46,7 @@
  *
  * 
{@code
  * 
- *     com.datastax.cassandra
+ *     org.apache.cassandra
  *     cassandra-driver-extras
  *     ${driver.version}
  * 
diff --git a/driver-examples/src/main/java/com/datastax/driver/examples/json/PlainTextJson.java b/driver-examples/src/main/java/com/datastax/driver/examples/json/PlainTextJson.java
index 43a51a85369..4b97380d403 100644
--- a/driver-examples/src/main/java/com/datastax/driver/examples/json/PlainTextJson.java
+++ b/driver-examples/src/main/java/com/datastax/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/driver-examples/src/main/java/com/datastax/driver/examples/paging/ForwardPagingRestUi.java b/driver-examples/src/main/java/com/datastax/driver/examples/paging/ForwardPagingRestUi.java
index cb0ff3de08d..faa938f50f6 100644
--- a/driver-examples/src/main/java/com/datastax/driver/examples/paging/ForwardPagingRestUi.java
+++ b/driver-examples/src/main/java/com/datastax/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/driver-examples/src/main/java/com/datastax/driver/examples/paging/RandomPagingRestUi.java b/driver-examples/src/main/java/com/datastax/driver/examples/paging/RandomPagingRestUi.java
index 6335f8d1483..e65047a0bc0 100644
--- a/driver-examples/src/main/java/com/datastax/driver/examples/paging/RandomPagingRestUi.java
+++ b/driver-examples/src/main/java/com/datastax/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/driver-examples/src/main/java/com/datastax/driver/examples/retry/DowngradingRetry.java b/driver-examples/src/main/java/com/datastax/driver/examples/retry/DowngradingRetry.java
index 7e10bcbe69b..64ad03f9dbe 100644
--- a/driver-examples/src/main/java/com/datastax/driver/examples/retry/DowngradingRetry.java
+++ b/driver-examples/src/main/java/com/datastax/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,
@@ -33,12 +35,12 @@
 import com.datastax.driver.core.exceptions.ReadTimeoutException;
 import com.datastax.driver.core.exceptions.UnavailableException;
 import com.datastax.driver.core.exceptions.WriteTimeoutException;
-import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
 import java.text.SimpleDateFormat;
 
 /**
- * This example illustrates how to replace the deprecated {@link DowngradingConsistencyRetryPolicy}
- * with equivalent application logic.
+ * This example illustrates how to replace the deprecated {@link
+ * com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy} with equivalent application
+ * logic.
  *
  * 

Preconditions: * @@ -68,7 +70,7 @@ * idempotence for more information. * * - * @see Java driver online manual + * @see Java Driver online manual */ @SuppressWarnings("deprecation") public class DowngradingRetry { diff --git a/driver-examples/src/main/resources/logback.xml b/driver-examples/src/main/resources/logback.xml index 3104bdb4091..6e477b80910 100644 --- a/driver-examples/src/main/resources/logback.xml +++ b/driver-examples/src/main/resources/logback.xml @@ -1,12 +1,14 @@ + # OSGi Tests A collection of simple tests for the Java Driver in an OSGi environment. @@ -9,7 +28,7 @@ It is _not_ meant as an example application. If you are looking for examples demonstrating usage of the driver in an OSGi environment, please refer to our [OSGi examples repository]. -[OSGi examples repository]:https://github.com/datastax/java-driver-examples-osgi +[OSGi examples repository]:https://github.com/apache/cassandra-java-driver-examples-osgi ## Usage @@ -40,7 +59,7 @@ Once `mvn verify` completes, the bundle jar will be present in the `target/` dir The project includes integration tests that verify that the service can be activated and used in an OSGi container. It also verifies that -the Java driver can be used in an OSGi container in the following +the Java Driver can be used in an OSGi container in the following configurations: 1. Default (default classifier with all dependencies) diff --git a/driver-tests/osgi/common/pom.xml b/driver-tests/osgi/common/pom.xml new file mode 100644 index 00000000000..71e616ad2a5 --- /dev/null +++ b/driver-tests/osgi/common/pom.xml @@ -0,0 +1,46 @@ + + + + 4.0.0 + + + org.apache.cassandra + cassandra-driver-tests-osgi + 3.12.2-SNAPSHOT + + + jar + cassandra-driver-tests-osgi-common + Java Driver for Apache Cassandra Tests - OSGi - Shaded + Common classes for testing Java Driver in an OSGi container. + + + + diff --git a/driver-tests/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxException.java b/driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/api/MailboxException.java similarity index 52% rename from driver-tests/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxException.java rename to driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/api/MailboxException.java index 98c92c58105..4a09fde9936 100644 --- a/driver-tests/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxException.java +++ b/driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/api/MailboxException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-tests/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxMessage.java b/driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/api/MailboxMessage.java similarity index 83% rename from driver-tests/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxMessage.java rename to driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/api/MailboxMessage.java index 54678af7038..441119612e8 100644 --- a/driver-tests/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxMessage.java +++ b/driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/api/MailboxMessage.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-tests/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxService.java b/driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/api/MailboxService.java similarity index 70% rename from driver-tests/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxService.java rename to driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/api/MailboxService.java index 332524dbe2c..b720417b05c 100644 --- a/driver-tests/osgi/src/main/java/com/datastax/driver/osgi/api/MailboxService.java +++ b/driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/api/MailboxService.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-tests/osgi/src/main/java/com/datastax/driver/osgi/impl/Activator.java b/driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/impl/Activator.java similarity index 85% rename from driver-tests/osgi/src/main/java/com/datastax/driver/osgi/impl/Activator.java rename to driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/impl/Activator.java index 46f675170b2..d3c8fb98981 100644 --- a/driver-tests/osgi/src/main/java/com/datastax/driver/osgi/impl/Activator.java +++ b/driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/impl/Activator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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.driver.osgi.impl; import static com.datastax.driver.core.ProtocolOptions.Compression.LZ4; +import static com.datastax.driver.core.ProtocolOptions.Compression.SNAPPY; import static com.datastax.driver.osgi.api.MailboxMessage.TABLE; import com.datastax.driver.core.Cluster; @@ -69,7 +72,10 @@ public void start(BundleContext context) throws Exception { String compression = context.getProperty("cassandra.compression"); if (compression != null) { if (ver.getMajor() < 2 && compression.equals(LZ4.name())) { - LOGGER.warn("Requested LZ4 compression but C* version is not compatible, disabling"); + LOGGER.warn("Requested LZ4 compression but C* version < 2.0 is not compatible, disabling"); + } else if (ver.getMajor() >= 4 && compression.equals(SNAPPY.name())) { + LOGGER.warn( + "Requested snappy compression but C* version >= 4.0 is not compatible, disabling"); } else { LOGGER.info("Compression: {}", compression); builder.withCompression(ProtocolOptions.Compression.valueOf(compression)); diff --git a/driver-tests/osgi/src/main/java/com/datastax/driver/osgi/impl/MailboxImpl.java b/driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/impl/MailboxImpl.java similarity index 87% rename from driver-tests/osgi/src/main/java/com/datastax/driver/osgi/impl/MailboxImpl.java rename to driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/impl/MailboxImpl.java index a1ab71cea17..2781b1e3ce0 100644 --- a/driver-tests/osgi/src/main/java/com/datastax/driver/osgi/impl/MailboxImpl.java +++ b/driver-tests/osgi/common/src/main/java/com/datastax/driver/osgi/impl/MailboxImpl.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/BundleOptions.java b/driver-tests/osgi/common/src/test/java/com/datastax/driver/osgi/BundleOptions.java similarity index 79% rename from driver-tests/osgi/src/test/java/com/datastax/driver/osgi/BundleOptions.java rename to driver-tests/osgi/common/src/test/java/com/datastax/driver/osgi/BundleOptions.java index a60944b7e61..e4d9ef9aaa0 100644 --- a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/BundleOptions.java +++ b/driver-tests/osgi/common/src/test/java/com/datastax/driver/osgi/BundleOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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.driver.osgi; -import static org.ops4j.pax.exam.CoreOptions.bootDelegationPackage; +import static org.ops4j.pax.exam.CoreOptions.bootDelegationPackages; import static org.ops4j.pax.exam.CoreOptions.bundle; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.options; @@ -60,7 +62,7 @@ public static UrlProvisionOption driverBundle(boolean useShaded) { return bundle( "reference:file:" + PathUtils.getBaseDir() - + "/../../driver-core/target/cassandra-driver-core-" + + "/../../../driver-core/target/cassandra-driver-core-" + Cluster.getDriverVersion() + classifier + ".jar"); @@ -70,7 +72,7 @@ public static UrlProvisionOption mappingBundle() { return bundle( "reference:file:" + PathUtils.getBaseDir() - + "/../../driver-mapping/target/cassandra-driver-mapping-" + + "/../../../driver-mapping/target/cassandra-driver-mapping-" + Cluster.getDriverVersion() + ".jar"); } @@ -79,7 +81,7 @@ public static UrlProvisionOption extrasBundle() { return bundle( "reference:file:" + PathUtils.getBaseDir() - + "/../../driver-extras/target/cassandra-driver-extras-" + + "/../../../driver-extras/target/cassandra-driver-extras-" + Cluster.getDriverVersion() + ".jar"); } @@ -136,7 +138,20 @@ public Option[] getOptions() { mavenBundle("io.netty", "netty-codec", nettyVersion), mavenBundle("io.netty", "netty-common", nettyVersion), mavenBundle("io.netty", "netty-handler", nettyVersion), - mavenBundle("io.netty", "netty-transport", nettyVersion)); + mavenBundle("io.netty", "netty-transport", nettyVersion), + mavenBundle("io.netty", "netty-transport-native-unix-common", nettyVersion), + mavenBundle("io.netty", "netty-resolver", nettyVersion)); + } + }; + } + + public static CompositeOption dropwizardMetricsBundle() { + return new CompositeOption() { + + @Override + public Option[] getOptions() { + return options( + mavenBundle("io.dropwizard.metrics", "metrics-core", getVersion("metrics.version"))); } }; } @@ -155,7 +170,7 @@ public Option[] getOptions() { // Delegate javax.security.cert to the parent classloader. // javax.security.cert.X509Certificate is used in // io.netty.util.internal.EmptyArrays, but not directly by the driver. - bootDelegationPackage("javax.security.cert"), + bootDelegationPackages("javax.security.cert", "javax.management"), systemProperty("cassandra.version") .value(CCMBridge.getGlobalCassandraVersion().toString()), systemProperty("cassandra.contactpoints").value(TestUtils.IP_PREFIX + 1), @@ -164,7 +179,16 @@ public Option[] getOptions() { mavenBundle("org.slf4j", "slf4j-api", getVersion("slf4j.version")), mavenBundle("ch.qos.logback", "logback-classic", getVersion("logback.version")), mavenBundle("ch.qos.logback", "logback-core", getVersion("logback.version")), - mavenBundle("io.dropwizard.metrics", "metrics-core", getVersion("metrics.version")), + mavenBundle( + "com.fasterxml.jackson.core", + "jackson-databind", + getVersion("jackson-databind.version")), + mavenBundle( + "com.fasterxml.jackson.core", "jackson-core", getVersion("jackson.version")), + mavenBundle( + "com.fasterxml.jackson.core", + "jackson-annotations", + getVersion("jackson.version")), mavenBundle("org.testng", "testng", getVersion("testng.version")), systemPackages( "org.testng", diff --git a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/CCMBridgeListener.java b/driver-tests/osgi/common/src/test/java/com/datastax/driver/osgi/CCMBridgeListener.java similarity index 75% rename from driver-tests/osgi/src/test/java/com/datastax/driver/osgi/CCMBridgeListener.java rename to driver-tests/osgi/common/src/test/java/com/datastax/driver/osgi/CCMBridgeListener.java index 3447ebe8757..de69805c824 100644 --- a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/CCMBridgeListener.java +++ b/driver-tests/osgi/common/src/test/java/com/datastax/driver/osgi/CCMBridgeListener.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceTests.java b/driver-tests/osgi/common/src/test/java/com/datastax/driver/osgi/MailboxServiceTests.java similarity index 84% rename from driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceTests.java rename to driver-tests/osgi/common/src/test/java/com/datastax/driver/osgi/MailboxServiceTests.java index 18fa9a55e89..fa92ea4dc4f 100644 --- a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceTests.java +++ b/driver-tests/osgi/common/src/test/java/com/datastax/driver/osgi/MailboxServiceTests.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-tests/osgi/pom.xml b/driver-tests/osgi/pom.xml index 7cd3dc04055..8609753a8c9 100644 --- a/driver-tests/osgi/pom.xml +++ b/driver-tests/osgi/pom.xml @@ -1,12 +1,14 @@ @@ -177,31 +165,22 @@ ${metrics.version} ${testng.version} ${jsr353-api.version} + ${jackson.version} + ${jackson-databind.version} ${ipprefix} + false + + https://repo1.maven.org/maven2@id=central - org.apache.felix - maven-bundle-plugin + org.codehaus.mojo + animal-sniffer-maven-plugin - - com.datastax.driver.osgi - com.datastax.driver.osgi.api,!com.datastax.driver.osgi.impl - com.datastax.driver.osgi.impl.Activator - <_include>-osgi.bnd - + true - - - bundle-manifest - process-classes - - manifest - - - diff --git a/driver-tests/osgi/shaded/pom.xml b/driver-tests/osgi/shaded/pom.xml new file mode 100644 index 00000000000..26d30bc88bd --- /dev/null +++ b/driver-tests/osgi/shaded/pom.xml @@ -0,0 +1,163 @@ + + + + 4.0.0 + + + org.apache.cassandra + cassandra-driver-tests-osgi + 3.12.2-SNAPSHOT + + + cassandra-driver-tests-osgi-shaded + Java Driver for Apache Cassandra Tests - OSGi - Shaded + A test for the shaded Java Driver in an OSGi container. + + + + org.apache.cassandra + cassandra-driver-core + + shaded + + + com.github.jnr + jnr-ffi + + + com.github.jnr + jnr-posix + + + + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + + copy-common-sources + process-sources + + copy-resources + + + ${project.build.directory}/dependency-sources/cassandra-driver-tests-osgi-common + true + + + ../common/src/main/java/ + + **/*.* + + + + + + + copy-common-test-sources + process-test-sources + + copy-resources + + + ${project.build.directory}/dependency-test-sources/cassandra-driver-tests-osgi-common + true + + + ../common/src/test/java/ + + **/*.* + + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-source + generate-sources + + add-source + + + + ${project.build.directory}/dependency-sources/cassandra-driver-tests-osgi-common + + + + + add-test-source + generate-test-sources + + add-test-source + + + + ${project.build.directory}/dependency-test-sources/cassandra-driver-tests-osgi-common + + + + + + + + maven-failsafe-plugin + + ${test.osgi.skip} + + + + + org.apache.felix + maven-bundle-plugin + + + bundle-manifest + process-classes + + manifest + + + ${project.build.outputDirectory}/META-INF + + com.datastax.driver.osgi + com.datastax.driver.osgi.api,!com.datastax.driver.osgi.impl + com.datastax.driver.osgi.impl.Activator + <_include>-osgi.bnd + + + + + + + + diff --git a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceShadedIT.java b/driver-tests/osgi/shaded/src/test/java/com/datastax/driver/osgi/MailboxServiceShadedIT.java similarity index 79% rename from driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceShadedIT.java rename to driver-tests/osgi/shaded/src/test/java/com/datastax/driver/osgi/MailboxServiceShadedIT.java index 0fccf6ad590..1f8cf26e679 100644 --- a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceShadedIT.java +++ b/driver-tests/osgi/shaded/src/test/java/com/datastax/driver/osgi/MailboxServiceShadedIT.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/driver-tests/osgi/shaded/src/test/resources/exam.properties b/driver-tests/osgi/shaded/src/test/resources/exam.properties new file mode 100644 index 00000000000..16d353c88cb --- /dev/null +++ b/driver-tests/osgi/shaded/src/test/resources/exam.properties @@ -0,0 +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. +# + +pax.exam.system=test +pax.exam.logging=none diff --git a/driver-tests/osgi/src/test/resources/logback.xml b/driver-tests/osgi/shaded/src/test/resources/logback.xml similarity index 74% rename from driver-tests/osgi/src/test/resources/logback.xml rename to driver-tests/osgi/shaded/src/test/resources/logback.xml index cd3ec75c4e8..0821c6dd2c0 100644 --- a/driver-tests/osgi/src/test/resources/logback.xml +++ b/driver-tests/osgi/shaded/src/test/resources/logback.xml @@ -1,12 +1,14 @@ + + + 4.0.0 + + + org.apache.cassandra + cassandra-driver-tests-osgi + 3.12.2-SNAPSHOT + + + cassandra-driver-tests-osgi-unshaded + Java Driver for Apache Cassandra Tests - OSGi - Unshaded + A test for the unshaded Java Driver in an OSGi container. + + + + org.apache.cassandra + cassandra-driver-core + + + + com.github.jnr + jnr-ffi + + + com.github.jnr + jnr-posix + + + + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + + copy-common-sources + process-sources + + copy-resources + + + ${project.build.directory}/dependency-sources/cassandra-driver-tests-osgi-common + true + + + ../common/src/main/java/ + + **/*.* + + + + + + + copy-common-test-sources + process-test-sources + + copy-resources + + + ${project.build.directory}/dependency-test-sources/cassandra-driver-tests-osgi-common + true + + + ../common/src/test/java/ + + **/*.* + + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-source + generate-sources + + add-source + + + + ${project.build.directory}/dependency-sources/cassandra-driver-tests-osgi-common + + + + + add-test-source + generate-test-sources + + add-test-source + + + + ${project.build.directory}/dependency-test-sources/cassandra-driver-tests-osgi-common + + + + + + + + maven-failsafe-plugin + + ${test.osgi.skip} + + + + + org.apache.felix + maven-bundle-plugin + + + bundle-manifest + process-classes + + manifest + + + ${project.build.outputDirectory}/META-INF + + com.datastax.driver.osgi + com.datastax.driver.osgi.api,!com.datastax.driver.osgi.impl + com.datastax.driver.osgi.impl.Activator + <_include>-osgi.bnd + + + + + + + + diff --git a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceDefaultIT.java b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceDefaultIT.java similarity index 77% rename from driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceDefaultIT.java rename to driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceDefaultIT.java index cd75f3afad4..abdc10bbbec 100644 --- a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceDefaultIT.java +++ b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceDefaultIT.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 static com.datastax.driver.osgi.BundleOptions.defaultOptions; import static com.datastax.driver.osgi.BundleOptions.driverBundle; +import static com.datastax.driver.osgi.BundleOptions.dropwizardMetricsBundle; import static com.datastax.driver.osgi.BundleOptions.extrasBundle; import static com.datastax.driver.osgi.BundleOptions.guavaBundle; import static com.datastax.driver.osgi.BundleOptions.mailboxBundle; @@ -39,6 +42,7 @@ public Option[] defaultConfig() { return options( defaultOptions(), nettyBundles(), + dropwizardMetricsBundle(), guavaBundle(), driverBundle(), extrasBundle(), diff --git a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava17IT.java b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava17IT.java similarity index 77% rename from driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava17IT.java rename to driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava17IT.java index 1830df37679..3b6b90141e4 100644 --- a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava17IT.java +++ b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava17IT.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 static com.datastax.driver.osgi.BundleOptions.defaultOptions; import static com.datastax.driver.osgi.BundleOptions.driverBundle; +import static com.datastax.driver.osgi.BundleOptions.dropwizardMetricsBundle; import static com.datastax.driver.osgi.BundleOptions.extrasBundle; import static com.datastax.driver.osgi.BundleOptions.guavaBundle; import static com.datastax.driver.osgi.BundleOptions.mailboxBundle; @@ -39,6 +42,7 @@ public Option[] guava17Config() { return options( defaultOptions(), nettyBundles(), + dropwizardMetricsBundle(), guavaBundle().version("17.0"), driverBundle(), mappingBundle(), diff --git a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava18IT.java b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava18IT.java similarity index 77% rename from driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava18IT.java rename to driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava18IT.java index c31cd576df0..2bc27869075 100644 --- a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava18IT.java +++ b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava18IT.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 static com.datastax.driver.osgi.BundleOptions.defaultOptions; import static com.datastax.driver.osgi.BundleOptions.driverBundle; +import static com.datastax.driver.osgi.BundleOptions.dropwizardMetricsBundle; import static com.datastax.driver.osgi.BundleOptions.extrasBundle; import static com.datastax.driver.osgi.BundleOptions.guavaBundle; import static com.datastax.driver.osgi.BundleOptions.mailboxBundle; @@ -39,6 +42,7 @@ public Option[] guava18Config() { return options( defaultOptions(), nettyBundles(), + dropwizardMetricsBundle(), guavaBundle().version("18.0"), driverBundle(), extrasBundle(), diff --git a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava19IT.java b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava19IT.java similarity index 77% rename from driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava19IT.java rename to driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava19IT.java index f6fa756a643..7fe217fc74f 100644 --- a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava19IT.java +++ b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava19IT.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 static com.datastax.driver.osgi.BundleOptions.defaultOptions; import static com.datastax.driver.osgi.BundleOptions.driverBundle; +import static com.datastax.driver.osgi.BundleOptions.dropwizardMetricsBundle; import static com.datastax.driver.osgi.BundleOptions.extrasBundle; import static com.datastax.driver.osgi.BundleOptions.guavaBundle; import static com.datastax.driver.osgi.BundleOptions.mailboxBundle; @@ -39,6 +42,7 @@ public Option[] guava19Config() { return options( defaultOptions(), nettyBundles(), + dropwizardMetricsBundle(), guavaBundle().version("19.0"), driverBundle(), extrasBundle(), diff --git a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava20IT.java b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava20IT.java similarity index 77% rename from driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava20IT.java rename to driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava20IT.java index 807e7bfc40e..6917d1d7cd8 100644 --- a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava20IT.java +++ b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava20IT.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 static com.datastax.driver.osgi.BundleOptions.defaultOptions; import static com.datastax.driver.osgi.BundleOptions.driverBundle; +import static com.datastax.driver.osgi.BundleOptions.dropwizardMetricsBundle; import static com.datastax.driver.osgi.BundleOptions.extrasBundle; import static com.datastax.driver.osgi.BundleOptions.guavaBundle; import static com.datastax.driver.osgi.BundleOptions.mailboxBundle; @@ -39,6 +42,7 @@ public Option[] guava20Config() { return options( defaultOptions(), nettyBundles(), + dropwizardMetricsBundle(), guavaBundle().version("20.0"), driverBundle(), extrasBundle(), diff --git a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava21IT.java b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava21IT.java similarity index 81% rename from driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava21IT.java rename to driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava21IT.java index bfacb06a058..bb9d10c9968 100644 --- a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava21IT.java +++ b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceGuava21IT.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 static com.datastax.driver.osgi.BundleOptions.defaultOptions; import static com.datastax.driver.osgi.BundleOptions.driverBundle; +import static com.datastax.driver.osgi.BundleOptions.dropwizardMetricsBundle; import static com.datastax.driver.osgi.BundleOptions.extrasBundle; import static com.datastax.driver.osgi.BundleOptions.guavaBundle; import static com.datastax.driver.osgi.BundleOptions.mailboxBundle; @@ -49,6 +52,7 @@ public Option[] guava21Config() { return options( defaultOptions(), nettyBundles(), + dropwizardMetricsBundle(), guavaBundle, driverBundle(), extrasBundle(), diff --git a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceHdrHistogramIT.java b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceHdrHistogramIT.java similarity index 77% rename from driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceHdrHistogramIT.java rename to driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceHdrHistogramIT.java index 3f25f426c65..019d3616087 100644 --- a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceHdrHistogramIT.java +++ b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceHdrHistogramIT.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 static com.datastax.driver.osgi.BundleOptions.defaultOptions; import static com.datastax.driver.osgi.BundleOptions.driverBundle; +import static com.datastax.driver.osgi.BundleOptions.dropwizardMetricsBundle; import static com.datastax.driver.osgi.BundleOptions.extrasBundle; import static com.datastax.driver.osgi.BundleOptions.guavaBundle; import static com.datastax.driver.osgi.BundleOptions.hdrHistogramBundle; @@ -41,6 +44,7 @@ public Option[] hdrHistogramConfig() { defaultOptions(), hdrHistogramBundle(), nettyBundles(), + dropwizardMetricsBundle(), guavaBundle(), extrasBundle(), mappingBundle(), diff --git a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceLZ4IT.java b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceLZ4IT.java similarity index 77% rename from driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceLZ4IT.java rename to driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceLZ4IT.java index 548a03f8ea6..430a5d0b98c 100644 --- a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceLZ4IT.java +++ b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceLZ4IT.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 static com.datastax.driver.osgi.BundleOptions.defaultOptions; import static com.datastax.driver.osgi.BundleOptions.driverBundle; +import static com.datastax.driver.osgi.BundleOptions.dropwizardMetricsBundle; import static com.datastax.driver.osgi.BundleOptions.extrasBundle; import static com.datastax.driver.osgi.BundleOptions.guavaBundle; import static com.datastax.driver.osgi.BundleOptions.lz4Bundle; @@ -41,6 +44,7 @@ public Option[] lz4Config() { defaultOptions(), lz4Bundle(), nettyBundles(), + dropwizardMetricsBundle(), guavaBundle(), extrasBundle(), mappingBundle(), diff --git a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceSnappyIT.java b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceSnappyIT.java similarity index 69% rename from driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceSnappyIT.java rename to driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceSnappyIT.java index 8d8ae4afa72..0cb87523076 100644 --- a/driver-tests/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceSnappyIT.java +++ b/driver-tests/osgi/unshaded/src/test/java/com/datastax/driver/osgi/MailboxServiceSnappyIT.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-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 static com.datastax.driver.osgi.BundleOptions.defaultOptions; import static com.datastax.driver.osgi.BundleOptions.driverBundle; +import static com.datastax.driver.osgi.BundleOptions.dropwizardMetricsBundle; import static com.datastax.driver.osgi.BundleOptions.extrasBundle; import static com.datastax.driver.osgi.BundleOptions.guavaBundle; import static com.datastax.driver.osgi.BundleOptions.mailboxBundle; @@ -25,10 +28,12 @@ import static com.datastax.driver.osgi.BundleOptions.snappyBundle; import static org.ops4j.pax.exam.CoreOptions.options; +import com.datastax.driver.core.VersionNumber; import com.datastax.driver.osgi.api.MailboxException; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.testng.listener.PaxExam; +import org.testng.SkipException; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @@ -41,6 +46,7 @@ public Option[] snappyConfig() { defaultOptions(), snappyBundle(), nettyBundles(), + dropwizardMetricsBundle(), guavaBundle(), extrasBundle(), mappingBundle(), @@ -59,6 +65,10 @@ public Option[] snappyConfig() { */ @Test(groups = "short") public void test_snappy() throws MailboxException { + VersionNumber ver = VersionNumber.parse(bundleContext.getProperty("cassandra.version")); + if (ver.getMajor() >= 4) { + throw new SkipException("Snappy not supported with cassandra 4.0+"); + } checkService(); } } diff --git a/driver-tests/osgi/unshaded/src/test/resources/exam.properties b/driver-tests/osgi/unshaded/src/test/resources/exam.properties new file mode 100644 index 00000000000..16d353c88cb --- /dev/null +++ b/driver-tests/osgi/unshaded/src/test/resources/exam.properties @@ -0,0 +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. +# + +pax.exam.system=test +pax.exam.logging=none diff --git a/driver-tests/osgi/unshaded/src/test/resources/logback.xml b/driver-tests/osgi/unshaded/src/test/resources/logback.xml new file mode 100644 index 00000000000..0821c6dd2c0 --- /dev/null +++ b/driver-tests/osgi/unshaded/src/test/resources/logback.xml @@ -0,0 +1,52 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/driver-tests/pom.xml b/driver-tests/pom.xml index 4853bd08bac..fee1fba96c1 100644 --- a/driver-tests/pom.xml +++ b/driver-tests/pom.xml @@ -1,12 +1,14 @@ + # Stress application -A simple example application that uses the Java driver to stress test -Cassandra. This also somewhat stress tests the Java driver as a result. +A simple example application that uses the Java Driver to stress test +Cassandra. This also somewhat stress tests the Java Driver as a result. Please note that this simple example is far from being a complete stress application. In particular it currently supports a very limited number of diff --git a/driver-tests/stress/bin/stress b/driver-tests/stress/bin/stress old mode 100755 new mode 100644 index e47ec0d7955..7aa9b52405d --- a/driver-tests/stress/bin/stress +++ b/driver-tests/stress/bin/stress @@ -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. SCRIPT_DIR=$( cd "$( dirname "$0" )" && pwd ) CURRENT_DIR=$( pwd ) diff --git a/driver-tests/stress/pom.xml b/driver-tests/stress/pom.xml index d291201009a..669a03344c4 100644 --- a/driver-tests/stress/pom.xml +++ b/driver-tests/stress/pom.xml @@ -1,12 +1,14 @@ + ## Frequently Asked Questions ### How do I implement paging? @@ -35,7 +54,7 @@ row.getBool(0); // this is equivalent row.getBool("applied") Note that, unlike manual inspection, `wasApplied` does not consume the first row. -[wasApplied]: http://docs.datastax.com/en/drivers/java/3.5/com/datastax/driver/core/ResultSet.html#wasApplied-- +[wasApplied]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ResultSet.html#wasApplied-- ### What is a parameterized statement and how can I use it? @@ -157,7 +176,7 @@ and we've had many reports where the problem turned out to be in user code. See [Blobs.java] in the `driver-examples` module for some examples and explanations. -[Blobs.java]: https://github.com/datastax/java-driver/tree/3.x/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java +[Blobs.java]: https://github.com/apache/cassandra-java-driver/tree/3.x/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java ### How do I use the driver in an OSGi application? @@ -289,7 +308,7 @@ version is available, you may want to reach out to the maintainer of that tool t an update with compatibility to this driver version. -[Blobs.java]: https://github.com/datastax/java-driver/tree/3.6.0/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java +[Blobs.java]: https://github.com/apache/cassandra-java-driver/tree/3.12.1/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java [CASSANDRA-7304]: https://issues.apache.org/jira/browse/CASSANDRA-7304 [Parameters and Binding]: ../manual/statements/prepared/#parameters-and-binding [Mapper options]: ../manual/object_mapper/using/#mapper-options diff --git a/faq/osgi/README.md b/faq/osgi/README.md index dd01a6bce4c..82b4b788947 100644 --- a/faq/osgi/README.md +++ b/faq/osgi/README.md @@ -1,6 +1,25 @@ + + ## Frequently Asked Questions - OSGi -### How to use the Java driver in an OSGi environment? +### How to use the Java Driver in an OSGi environment? We have complete examples demonstrating usage of the driver in an [OSGi] environment; please refer to our [OSGi examples repository]. @@ -29,7 +48,7 @@ of Guava's packages, e.g. for 19.0: ### How to enable compression? First, read our [manual page on compression](../../manual/compression/) -to understand how to enable compression for the Java driver. +to understand how to enable compression for the Java Driver. OSGi projects can use both Snappy or LZ4 compression algorithms. @@ -156,8 +175,8 @@ it is also normal to see the following log lines when starting the driver: [JAVA-1127]:https://datastax-oss.atlassian.net/browse/JAVA-1127 [BND]:http://bnd.bndtools.org/ [Maven bundle plugin]:https://cwiki.apache.org/confluence/display/FELIX/Apache+Felix+Maven+Bundle+Plugin+%28BND%29 -[OSGi examples repository]:https://github.com/datastax/java-driver-examples-osgi -[without metrics]:http://docs.datastax.com/en/drivers/java/3.5/com/datastax/driver/core/Cluster.Builder.html#withoutMetrics-- +[OSGi examples repository]:https://github.com/apache/cassandra-java-driver-examples-osgi +[without metrics]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.Builder.html#withoutMetrics-- [SLF4J]:http://www.slf4j.org/ [Logback]:http://logback.qos.ch/ [Tycho]:https://eclipse.org/tycho/ 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/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 735259da078..e2498c402a2 100644 --- a/manual/README.md +++ b/manual/README.md @@ -1,3 +1,22 @@ + + ## Manual ### Quick start @@ -209,7 +228,7 @@ String firstName = row.getString("first_name"); blob getBytes java.nio.ByteBuffer boolean getBool boolean counter getLong long - date getDate LocalDate + date getDate LocalDate decimal getDecimal java.math.BigDecimal double getDouble double float getFloat float @@ -288,20 +307,20 @@ Besides explicit work with queries and rows, you can also use If you're reading this from the [generated HTML documentation on github.io](http://datastax.github.io/java-driver/), use the "Contents" menu on the left hand side to navigate sub-sections. If you're [browsing the source files on -github.com](https://github.com/datastax/java-driver/tree/3.x/manual), +github.com](https://github.com/apache/cassandra-java-driver/tree/3.x/manual), simply navigate to each sub-directory. -[Cluster]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Cluster.html -[Cluster.Builder]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Cluster.Builder.html -[Initializer]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Cluster.Initializer.html -[Session]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Session.html -[ResultSet]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/ResultSet.html -[Row]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Row.html -[NettyOptions]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/NettyOptions.html -[QueryOptions]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/QueryOptions.html -[SocketOptions]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SocketOptions.html -[Host.StateListener]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Host.StateListener.html -[LatencyTracker]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/LatencyTracker.html -[SchemaChangeListener]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SchemaChangeListener.html -[NoHostAvailableException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/NoHostAvailableException.html -[LocalDate]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/LocalDate.html \ No newline at end of file +[Cluster]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.html +[Cluster.Builder]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.Builder.html +[Initializer]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.Initializer.html +[Session]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Session.html +[ResultSet]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ResultSet.html +[Row]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Row.html +[NettyOptions]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/NettyOptions.html +[QueryOptions]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/QueryOptions.html +[SocketOptions]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SocketOptions.html +[Host.StateListener]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Host.StateListener.html +[LatencyTracker]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/LatencyTracker.html +[SchemaChangeListener]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SchemaChangeListener.html +[NoHostAvailableException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/NoHostAvailableException.html +[LocalDate]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/LocalDate.html diff --git a/manual/address_resolution/README.md b/manual/address_resolution/README.md index 2f55461bd96..412b3866c71 100644 --- a/manual/address_resolution/README.md +++ b/manual/address_resolution/README.md @@ -1,3 +1,22 @@ + + ## Address resolution Each node in the Cassandra cluster is uniquely identified by an IP address that the driver will use to establish @@ -102,8 +121,8 @@ private/public switch automatically based on location). -[AddressTranslator]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/AddressTranslator.html -[EC2MultiRegionAddressTranslator]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslator.html +[AddressTranslator]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/AddressTranslator.html +[EC2MultiRegionAddressTranslator]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslator.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/async/README.md b/manual/async/README.md index 124b25e8c07..da7df365331 100644 --- a/manual/async/README.md +++ b/manual/async/README.md @@ -1,3 +1,22 @@ + + ## Asynchronous programming The driver exposes an asynchronous API that allows you to write programs @@ -51,8 +70,8 @@ to the current page, and [fetchMoreResults] to get a future to the next page (see also the section on [paging](../paging/)). Here is a full example: -[getAvailableWithoutFetching]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/ResultSet.html#getAvailableWithoutFetching-- -[fetchMoreResults]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/ResultSet.html#fetchMoreResults-- +[getAvailableWithoutFetching]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ResultSet.html#getAvailableWithoutFetching-- +[fetchMoreResults]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ResultSet.html#fetchMoreResults-- ```java Statement statement = new SimpleStatement("select * from foo").setFetchSize(20); @@ -134,5 +153,5 @@ There are still a few places where the driver will block internally hasn't been fetched already. [ListenableFuture]: https://github.com/google/guava/wiki/ListenableFutureExplained -[init]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Cluster.html#init-- -[query trace]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/QueryTrace.html +[init]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.html#init-- +[query trace]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/QueryTrace.html diff --git a/manual/auth/README.md b/manual/auth/README.md index 502973702cc..7b315fa3642 100644 --- a/manual/auth/README.md +++ b/manual/auth/README.md @@ -1,5 +1,53 @@ + + ## Authentication -*Coming soon... In the meantime, see the javadoc for [AuthProvider].* +Cassandra’s binary protocol supports [SASL]-based authentication. To enable it, use +[Cluster.Builder.withCredentials] when building your `Cluster` instance to provide the credentials +you wish to authenticate with: + +```java +Cluster.builder() + .withCredentials("bob", "mypassword") + .build(); +``` + +This is a shortcut for using [PlainTextAuthProvider] for simple username/password authentication +(intended to work with the server-side `PasswordAuthenticator`). This may alternatively be +provided using the [Cluster.Builder.withAuthProvider] method: + + +```java +Cluster.builder() + .withAuthProvider(new PlainTextAuthProvider("bob", "mypassword")) + .build(); +``` + +Authentication must be configured before opening a session, it cannot be changed at runtime. + +You can also write your own provider; it must implement [AuthProvider]. + + +[SASL]: https://en.wikipedia.org/wiki/Simple_Authentication_and_Security_Layer -[AuthProvider]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/AuthProvider.html \ No newline at end of file +[Cluster.Builder.withCredentials]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.Builder.html#withCredentials-java.lang.String-java.lang.String- +[AuthProvider]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/AuthProvider.html +[Cluster.Builder.withAuthProvider]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.Builder.html#withAuthProvider-com.datastax.driver.core.AuthProvider- +[PlainTextAuthProvider]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/PlainTextAuthProvider.html diff --git a/manual/cloud/README.md b/manual/cloud/README.md new file mode 100644 index 00000000000..3ff7e63558c --- /dev/null +++ b/manual/cloud/README.md @@ -0,0 +1,120 @@ + + +## Connecting to Astra (Cloud) + +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`. + +The following is a Quick Start guide to writing a simple application that can connect to an Astra +database. + +### Prerequisites + +1. [Download][Download Maven] and [install][Install Maven] Maven. +1. Create an Astra database on [GCP/AWS/Azure][Create an Astra database - GCP/AWS/Azure]; alternatively, + have a team member provide access to their Astra database (instructions for + [GCP/AWS/Azure][Access an Astra database - GCP/AWS/Azure]) to obtain database connection details. +1. Download the secure connect bundle (instructions for + [GCP/AWS/Azure][Download the secure connect bundle - GCP/AWS/Azure]) to obtain connection credentials for your + database. +1. Ensure you are using Java 8 or higher. The cloud connect api does not support java 6 or 7. + +### Procedure + +1. Include the driver artifacts in your `pom.xml` file according to this [pom.xml dependency]. + +1. Initialize the Java Driver. + + a. Create a `ConnectDatabase.java` file in the `/src/main/java` directory for your Java project. + + ```sh + $ cd javaProject/src/main/java + ``` + ```sh + $ touch ConnectDatabase.java + ``` + + b. Copy the following code for your DataStax Driver into the `ConnectDatabase.java` file. + The following example implements a `ConnectDatabase` class to connect to your Astra database, + runs a CQL query, and prints the output to the console. + + **Note:** With the `Cluster.builder()` object, make sure to set the path to the secure + connect bundle for your Astra database (**"/path/to/secure-connect-database_name.zip"**) in + the `withCloudSecureConnectBundle()` method as shown in the following example. + * Java Driver for Apache Cassandra 3.x + + ```java + import com.datastax.driver.core.Cluster; + import com.datastax.driver.core.ResultSet; + import com.datastax.driver.core.Row; + import com.datastax.driver.core.Session; + import java.io.File; + + public class ConnectDatabase { + + public static void main(String[] args) { + // Create the Cluster object: + Cluster cluster = null; + try { + cluster = Cluster.builder() + // make sure you change the path to the secure connect bundle below + .withCloudSecureConnectBundle(new File("/path/to/secure-connect-database_name.zip")) + .withCredentials("user_name", "password") + .build(); + Session session = cluster.connect(); + // Select the release_version from the system.local table: + ResultSet rs = session.execute("select release_version from system.local"); + Row row = rs.one(); + //Print the results of the CQL query to the console: + if (row != null) { + System.out.println(row.getString("release_version")); + } else { + System.out.println("An error occurred."); + } + } finally { + if (cluster != null) cluster.close(); + } + } + } + ``` + + c. Save and close the ConnectDatabase.java file. + +### Astra Differences + +In most circumstances, the client code for interacting with an Astra cluster will be the same as +interacting with any other Cassandra cluster. The exceptions being: + + * An SSL connection will be established automatically. Manual SSL configuration is not necessary. + + * A Cluster’s contact points attribute should not be used. The cloud config contains all of the + necessary contact information (i.e. don't use any of the `addContactPoint()` or + `addContactPoints()` methods on the Builder) + + * If a consistency level is not specified for an execution profile or query, then + `ConsistencyLevel.LOCAL_QUORUM` will be used as the default. + +[Download Maven]: https://maven.apache.org/download.cgi +[Install Maven]: https://maven.apache.org/install.html +[Create an Astra database - GCP/AWS/Azure]: https://docs.astra.datastax.com/docs/creating-your-astra-database#dscloudCreateCluster +[Access an Astra database - GCP/AWS/Azure]: https://docs.astra.datastax.com/docs/obtaining-database-credentials#sharing-your-secure-connect-bundle +[Download the secure connect bundle - GCP/AWS/Azure]: https://docs.astra.datastax.com/docs/obtaining-database-credentials +[pom.xml dependency]: ../../#getting-the-driver diff --git a/manual/compression/README.md b/manual/compression/README.md index 9d149e7ea09..6b25b5e5c69 100644 --- a/manual/compression/README.md +++ b/manual/compression/README.md @@ -1,3 +1,22 @@ + + ## Compression Cassandra's binary protocol supports optional compression of @@ -12,12 +31,15 @@ will likely be beneficial when you have larger payloads. Two algorithms are available: [LZ4](https://github.com/jpountz/lz4-java) and -[Snappy](https://code.google.com/p/snappy/). +[Snappy](https://code.google.com/p/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 better performance and compression ratios over Snappy. Both rely on third-party libraries, declared by the driver as *optional* -dependencies. So If you use a build tool like Maven, you'll need to -declare an explicit dependency to pull the appropriate library in your -application's classpath. Then you configure compression at driver -startup. +dependencies. So if you use a build tool like Maven, you'll need to declare an +explicit dependency to pull the appropriate library in your application's +classpath. Then you configure compression at driver startup. ### LZ4 @@ -53,11 +75,11 @@ LZ4-java has three internal implementations (from fastest to slowest): It will pick the best implementation depending on what's possible on your platform. To find out which one was chosen, [enable INFO logs](../logging/) on the category -`com.datastax.driver.core.FrameCompressor` and look for a log similar to +`com.datastax.driver.core.LZ4Compressor` and look for a log similar to this: ``` -INFO com.datastax.driver.core.FrameCompressor - Using LZ4Factory:JNI +INFO com.datastax.driver.core.LZ4Compressor - Using LZ4Factory:JNI ``` ### Snappy @@ -85,4 +107,4 @@ cluster = Cluster.builder() .build(); ``` -[pom]: https://repo1.maven.org/maven2/com/datastax/cassandra/cassandra-driver-parent/3.6.0/cassandra-driver-parent-3.6.0.pom +[pom]: https://repo1.maven.org/maven2/com/datastax/cassandra/cassandra-driver-parent/3.12.1/cassandra-driver-parent-3.12.1.pom diff --git a/manual/control_connection/README.md b/manual/control_connection/README.md index eccef57e029..d2cde319bbf 100644 --- a/manual/control_connection/README.md +++ b/manual/control_connection/README.md @@ -1,10 +1,40 @@ + + ## Control connection -*Coming soon...* +The control connection is a dedicated connection used for administrative tasks: - \ No newline at end of file +* querying system tables to learn about the cluster's topology and + [schema](../metadata/#schema-metadata); +* checking [schema agreement](../metadata/#schema-agreement); +* reacting to server events, which are used to notify the driver of external topology or schema + changes. + +When the driver starts, the control connection is established to the first contacted node. If that +node goes down, a [reconnection](../reconnection/) is started to find another node; it is governed +by the same policy as regular connections and tries the nodes according to a query plan from the +[load balancing policy](../load_balancing/). + +The control connection is managed independently from [regular pooled connections](../pooling/), and +used exclusively for administrative requests. It is included in [Session.State.getOpenConnections], +as well as the `open-connections` [metric](../metrics); for example, if you've configured a pool +size of 2, the control node will have 3 connections. + +[Session.State.getOpenConnections]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Session.State.html#getOpenConnections-com.datastax.driver.core.Host- diff --git a/manual/custom_codecs/README.md b/manual/custom_codecs/README.md index 1bd34b8f19e..6737d923dbd 100644 --- a/manual/custom_codecs/README.md +++ b/manual/custom_codecs/README.md @@ -1,3 +1,22 @@ + + ## Custom Codecs Custom codecs support transparent, user-configurable mapping of CQL types to arbitrary Java objects. @@ -447,26 +466,26 @@ Beware that in these cases, the lookup performs in average 10x worse. If perform consider using prepared statements all the time. [JAVA-721]: https://datastax-oss.atlassian.net/browse/JAVA-721 -[TypeCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TypeCodec.html -[LocalDate]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/LocalDate.html +[TypeCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TypeCodec.html +[LocalDate]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/LocalDate.html [ByteBuffer]: http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html -[serialize]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TypeCodec.html#serialize-T-com.datastax.driver.core.ProtocolVersion- -[deserialize]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TypeCodec.html#deserialize-java.nio.ByteBuffer-com.datastax.driver.core.ProtocolVersion- -[TypeCodec.format]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TypeCodec.html#format-T- -[TypeCodec.parse]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TypeCodec.html#parse-java.lang.String- -[accepts]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TypeCodec.html#accepts-com.datastax.driver.core.DataType- -[CodecRegistry]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/CodecRegistry.html -[CodecNotFoundException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/CodecNotFoundException.html +[serialize]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TypeCodec.html#serialize-T-com.datastax.driver.core.ProtocolVersion- +[deserialize]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TypeCodec.html#deserialize-java.nio.ByteBuffer-com.datastax.driver.core.ProtocolVersion- +[TypeCodec.format]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TypeCodec.html#format-T- +[TypeCodec.parse]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TypeCodec.html#parse-java.lang.String- +[accepts]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TypeCodec.html#accepts-com.datastax.driver.core.DataType- +[CodecRegistry]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/CodecRegistry.html +[CodecNotFoundException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/CodecNotFoundException.html [Jackson]: https://github.com/FasterXML/jackson [AbstractType]: https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java -[UserType]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/UserType.html -[UDTValue]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/UDTValue.html -[TupleType]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TupleType.html -[TupleValue]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TupleValue.html -[CustomType]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/DataType.CustomType.html +[UserType]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/UserType.html +[UDTValue]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/UDTValue.html +[TupleType]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TupleType.html +[TupleValue]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TupleValue.html +[CustomType]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/DataType.CustomType.html [TypeToken]: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/reflect/TypeToken.html -[SimpleStatement]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SimpleStatement.html -[BuiltStatement]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/querybuilder/BuiltStatement.html -[setList]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SettableByIndexData.html#setList-int-java.util.List- -[setSet]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SettableByIndexData.html#setSet-int-java.util.Set- -[setMap]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SettableByIndexData.html#setMap-int-java.util.Map- +[SimpleStatement]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SimpleStatement.html +[BuiltStatement]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/querybuilder/BuiltStatement.html +[setList]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SettableByIndexData.html#setList-int-java.util.List- +[setSet]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SettableByIndexData.html#setSet-int-java.util.Set- +[setMap]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SettableByIndexData.html#setMap-int-java.util.Map- diff --git a/manual/custom_codecs/extras/README.md b/manual/custom_codecs/extras/README.md index 0571cf70b72..3198135878a 100644 --- a/manual/custom_codecs/extras/README.md +++ b/manual/custom_codecs/extras/README.md @@ -1,3 +1,22 @@ + + ## Optional codecs The driver's "extras" module provides additional [codec](../) implementations: these codecs are not required by core @@ -8,9 +27,9 @@ The module is published as a separate Maven artifact: ```xml - com.datastax.cassandra + org.apache.cassandra cassandra-driver-extras - 3.6.0 + 3.12.1 ``` @@ -73,12 +92,15 @@ session.execute("INSERT INTO example (id, t) VALUES (1, ?)", ZoneId.of("GMT+07:00")); ``` -[InstantCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/jdk8/InstantCodec.html -[LocalDateCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/jdk8/LocalDateCodec.html -[LocalTimeCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/jdk8/LocalTimeCodec.html -[ZonedDateTimeCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/jdk8/ZonedDateTimeCodec.html +[InstantCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/jdk8/InstantCodec.html +[LocalDateCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/jdk8/LocalDateCodec.html +[LocalDateTimeCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/jdk8/LocalDateTimeCodec.html +[LocalTimeCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/jdk8/LocalTimeCodec.html +[ZonedDateTimeCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/jdk8/ZonedDateTimeCodec.html +[ZoneIdCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/jdk8/ZoneIdCodec.html [Instant]: https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html [LocalDate]: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html +[LocalDateTime]: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html [LocalTime]: https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html [ZonedDateTime]: https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html [ZoneId]: https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html @@ -127,10 +149,10 @@ session.execute("INSERT INTO example (id, t) VALUES (1, ?)", DateTime.parse("2010-06-30T01:20:47.999+01:00")); ``` -[InstantCodec_joda]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/joda/InstantCodec.html -[LocalDateCodec_joda]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/joda/LocalDateCodec.html -[LocalTimeCodec_joda]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/joda/LocalTimeCodec.html -[DateTimeCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/joda/DateTimeCodec.html +[InstantCodec_joda]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/joda/InstantCodec.html +[LocalDateCodec_joda]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/joda/LocalDateCodec.html +[LocalTimeCodec_joda]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/joda/LocalTimeCodec.html +[DateTimeCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/joda/DateTimeCodec.html [DateTime]: http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html [Instant_joda]: http://www.joda.org/joda-time/apidocs/org/joda/time/Instant.html [LocalDate_joda]: http://www.joda.org/joda-time/apidocs/org/joda/time/LocalDate.html @@ -148,8 +170,8 @@ Time can also be expressed as simple durations: There is no extra codec for `time`, because by default the driver already maps that type to a `long` representing the number of nanoseconds since midnight. -[SimpleTimestampCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/date/SimpleTimestampCodec.html -[SimpleDateCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/date/SimpleDateCodec.html +[SimpleTimestampCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/date/SimpleTimestampCodec.html +[SimpleDateCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/date/SimpleDateCodec.html ### Enums @@ -187,8 +209,8 @@ Note that if you registered an `EnumNameCodec` and an `EnumOrdinalCodec` _for th In practice, this is unlikely to happen, because you'll probably stick to a single CQL type for a given enum type; however, if you ever run into that issue, the workaround is to use [prepared statements](../../statements/prepared/), for which the driver knows the CQL type and can pick the exact codec. -[EnumNameCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/enums/EnumNameCodec.html -[EnumOrdinalCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/enums/EnumOrdinalCodec.html +[EnumNameCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/enums/EnumNameCodec.html +[EnumOrdinalCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/enums/EnumOrdinalCodec.html [name]: https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#name-- [ordinal]: https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#ordinal-- @@ -233,7 +255,7 @@ session.execute("insert into example (id, owner) values (1, ?)", // owner saved as '{"id":1,"name":"root"}' ``` -[JacksonJsonCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/json/JacksonJsonCodec.html +[JacksonJsonCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/json/JacksonJsonCodec.html [Jackson]: https://github.com/FasterXML/jackson @@ -272,7 +294,7 @@ session.execute("insert into example (id, owner) values (1, ?)", ``` -[Jsr353JsonCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/json/Jsr353JsonCodec.html +[Jsr353JsonCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/json/Jsr353JsonCodec.html [JsonStructure]: https://docs.oracle.com/javaee/7/tutorial/jsonp002.htm @@ -325,7 +347,7 @@ For the same reason, we need to give a type hint when setting "v", in the form o anonymous inner class; we recommend storing these tokens as constants in a utility class, to avoid creating them too often. -[OptionalCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/jdk8/OptionalCodec.html +[OptionalCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/jdk8/OptionalCodec.html [Optional]: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html [TypeToken]: http://google.github.io/guava/releases/19.0/api/docs/com/google/common/reflect/TypeToken.html @@ -369,7 +391,7 @@ session.execute(pst.bind() See the JDK8 Optional section above for explanations about [TypeToken]. -[OptionalCodec_guava]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/guava/OptionalCodec.html +[OptionalCodec_guava]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/guava/OptionalCodec.html [Optional_guava]: http://google.github.io/guava/releases/19.0/api/docs/com/google/common/base/Optional.html @@ -394,9 +416,9 @@ session.execute("insert into example (i, l) values (1, ?)", Package [com.datastax.driver.extras.codecs.arrays][arrays] contains similar codecs for all primitive types, and [ObjectArrayCodec] to map arrays of objects. -[IntArrayCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/arrays/IntArrayCodec.html -[ObjectArrayCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/arrays/ObjectArrayCodec.html -[arrays]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/arrays/package-summary.html +[IntArrayCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/arrays/IntArrayCodec.html +[ObjectArrayCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/arrays/ObjectArrayCodec.html +[arrays]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/arrays/package-summary.html ### Abstract utilities @@ -426,5 +448,5 @@ These two classes are convenient, but since they perform conversions in two step optimal approach. If performance is paramount, it's better to start from scratch and convert your objects to `ByteBuffer` directly. -[MappingCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/MappingCodec.html -[ParsingCodec]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/extras/codecs/ParsingCodec.html +[MappingCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/MappingCodec.html +[ParsingCodec]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/extras/codecs/ParsingCodec.html diff --git a/manual/custom_payloads/README.md b/manual/custom_payloads/README.md index 924c97ee188..778dbd72ea3 100644 --- a/manual/custom_payloads/README.md +++ b/manual/custom_payloads/README.md @@ -1,3 +1,22 @@ + + ## Custom Payloads The [native protocol](../native_protocol/) version 4 introduces a new feature called [Custom Payloads][CASSANDRA-8553]. @@ -42,7 +61,7 @@ payloads sent by the driver could get lost. ### Implementation Notes -Payloads in the Java driver are represented as `Map` instances. +Payloads in the Java Driver are represented as `Map` instances. It is safe to use any `Map` implementation, including unsynchronized implementations such as `java.util.HashMap`; the driver will create defensive, thread-safe copies of user-supplied maps. However, `ByteBuffer` instances are inherently mutable, @@ -51,11 +70,11 @@ to the driver as it could lead to unexpected results. #### Null values -Note that, for thread safety reasons, the Java driver does not permit `null` keys nor `null` values in a payload map; +Note that, for thread safety reasons, the Java Driver does not permit `null` keys nor `null` values in a payload map; including a `null` in your payload will result in a `NullPointerException` being immediately thrown. However, the protocol specification *does* allow `null` values. If you need to include -a `null` value in your payload map, this can be achieved with the Java driver +a `null` value in your payload map, this can be achieved with the Java Driver by using the special value `Statement.NULL_PAYLOAD_VALUE`. ##### Payload length limitations @@ -241,8 +260,8 @@ The log message contains a pretty-printed version of the payload itself, and its [CASSANDRA-8553]: https://issues.apache.org/jira/browse/CASSANDRA-8553 [v4spec]: https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec [qh]: https://issues.apache.org/jira/browse/CASSANDRA-6659 -[nhae]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/NoHostAvailableException.html +[nhae]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/NoHostAvailableException.html [chm]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html [immutablemap]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableMap.html -[ufe]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/UnsupportedFeatureException.html +[ufe]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/UnsupportedFeatureException.html diff --git a/manual/idempotence/README.md b/manual/idempotence/README.md index 8c833a18805..24c4ac95c40 100644 --- a/manual/idempotence/README.md +++ b/manual/idempotence/README.md @@ -1,3 +1,22 @@ + + ## Query idempotence A query is *idempotent* if it can be applied multiple times without changing the result of the initial application. For @@ -125,8 +144,8 @@ broke linearizability by doing a transparent retry at step 6. If linearizability is important for you, you should ensure that lightweight transactions are appropriately flagged as not idempotent. -[isIdempotent]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Statement.html#isIdempotent-- -[setDefaultIdempotence]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/QueryOptions.html#setDefaultIdempotence-boolean- -[QueryBuilder]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/querybuilder/QueryBuilder.html +[isIdempotent]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Statement.html#isIdempotent-- +[setDefaultIdempotence]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/QueryOptions.html#setDefaultIdempotence-boolean- +[QueryBuilder]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/querybuilder/QueryBuilder.html -[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/load_balancing/README.md b/manual/load_balancing/README.md index 5177d769428..8fd3fb06f2d 100644 --- a/manual/load_balancing/README.md +++ b/manual/load_balancing/README.md @@ -1,3 +1,22 @@ + + ## Load balancing A Cassandra cluster is typically composed of multiple hosts; the [LoadBalancingPolicy] \(sometimes abbreviated LBP) is a @@ -101,14 +120,11 @@ Cluster cluster = Cluster.builder() .withLoadBalancingPolicy( DCAwareRoundRobinPolicy.builder() .withLocalDc("myLocalDC") - .withUsedHostsPerRemoteDc(2) - .allowRemoteDCsForLocalConsistencyLevel() .build() ).build(); ``` -This policy queries nodes of the local data-center in a round-robin fashion; optionally, it can also try a configurable -number of hosts in remote data centers if all local hosts failed. +This policy queries nodes of the local data-center in a round-robin fashion. Call `withLocalDc` to specify the name of your local datacenter. You can also leave it out, and the driver will use the datacenter of the first contact point that was reached [at initialization](../#cluster-initialization). However, @@ -118,21 +134,6 @@ local datacenter. In general, providing the datacenter name explicitly is a safe Hosts belonging to the local datacenter are at distance `LOCAL`, and appear first in query plans (in a round-robin fashion). -If you call `withUsedHostsPerRemoteDc`, the policy will pick that number of hosts for each remote DC, and add them at -the end of query plans. To illustrate this, let's assume that the value is 2, there are 3 datacenters and 3 hosts in the -local datacenter. Query plans would look like this: - -* query 1: localHost1, localHost2, localHost3, host1InRemoteDc1, host2InRemoteDc1, host1InRemoteDc2, host2InRemoteDc2 -* query 2: localHost2, localHost3, localHost1, host1InRemoteDc1, host2InRemoteDc1, host1InRemoteDc2, host2InRemoteDc2 -* query 3: localHost3, localHost1, localHost2, host1InRemoteDc1, host2InRemoteDc1, host1InRemoteDc2, host2InRemoteDc2 - -Hosts selected by this option are at distance `REMOTE`. Note that they always appear in the same order. - -Finally, `allowRemoteDCsForLocalConsistencyLevel` controls whether remote hosts included by the previous option are -included when the consistency level of the query is `LOCAL_ONE` or `LOCAL_QUORUM`. By default, it is off (remote hosts -are not included for local CLs). - - ### [TokenAwarePolicy] ```java @@ -295,11 +296,11 @@ For any host, the distance returned by the policy is always the same as its chil Query plans are based on the child policy's, except that hosts that are currently excluded for being too slow are moved to the end of the plan. -[withExclusionThreshold]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withExclusionThreshold-double- -[withMininumMeasurements]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withMininumMeasurements-int- -[withRetryPeriod]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withRetryPeriod-long-java.util.concurrent.TimeUnit- -[withScale]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withScale-long-java.util.concurrent.TimeUnit- -[withUpdateRate]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withUpdateRate-long-java.util.concurrent.TimeUnit- +[withExclusionThreshold]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withExclusionThreshold-double- +[withMininumMeasurements]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withMininumMeasurements-int- +[withRetryPeriod]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withRetryPeriod-long-java.util.concurrent.TimeUnit- +[withScale]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withScale-long-java.util.concurrent.TimeUnit- +[withUpdateRate]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/LatencyAwarePolicy.Builder.html#withUpdateRate-long-java.util.concurrent.TimeUnit- ### Filtering policies @@ -317,15 +318,15 @@ studying the existing implementations first: `RoundRobinPolicy` is a good place complex ones like `DCAwareRoundRobinPolicy`. -[LoadBalancingPolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/LoadBalancingPolicy.html -[RoundRobinPolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/RoundRobinPolicy.html -[DCAwareRoundRobinPolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.html -[TokenAwarePolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/TokenAwarePolicy.html -[LatencyAwarePolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/LatencyAwarePolicy.html -[HostFilterPolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/HostFilterPolicy.html -[WhiteListPolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/WhiteListPolicy.html -[HostDistance]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/HostDistance.html -[refreshConnectedHosts]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/PoolingOptions.html#refreshConnectedHosts-- -[setMetadataEnabled]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/QueryOptions.html#setMetadataEnabled-boolean- -[Statement#getKeyspace]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Statement.html#getKeyspace-- -[Statement#getRoutingKey]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Statement.html#getRoutingKey-- +[LoadBalancingPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/LoadBalancingPolicy.html +[RoundRobinPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/RoundRobinPolicy.html +[DCAwareRoundRobinPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.html +[TokenAwarePolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/TokenAwarePolicy.html +[LatencyAwarePolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/LatencyAwarePolicy.html +[HostFilterPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/HostFilterPolicy.html +[WhiteListPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/WhiteListPolicy.html +[HostDistance]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/HostDistance.html +[refreshConnectedHosts]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/PoolingOptions.html#refreshConnectedHosts-- +[setMetadataEnabled]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/QueryOptions.html#setMetadataEnabled-boolean- +[Statement#getKeyspace]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Statement.html#getKeyspace-- +[Statement#getRoutingKey]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Statement.html#getRoutingKey-- diff --git a/manual/logging/README.md b/manual/logging/README.md index 08cbda9c6b1..109a4d0bb83 100644 --- a/manual/logging/README.md +++ b/manual/logging/README.md @@ -1,8 +1,27 @@ + + ## Logging ### Setup -DataStax Java driver uses the popular [SLF4J](http://www.slf4j.org) library to emit log messages; +Java Driver uses the popular [SLF4J](http://www.slf4j.org) library to emit log messages; SLF4J has the advantage of providing a logging API that is entirely decoupled from concrete implementations, letting client applications free to seamlessly connect SLF4J to their preferred logging backend. @@ -49,7 +68,7 @@ You can also find some configuration examples below. ### Useful loggers -When debugging the Java driver, the following loggers could be particularly useful +When debugging the Java Driver, the following loggers could be particularly useful and provide hints about what's going wrong. * `com.datastax.driver.core.Cluster` @@ -192,6 +211,47 @@ that can significantly boost latencies when writing log messages. without stopping the application. This usually involves JMX and is available for [Logback](http://logback.qos.ch/manual/jmxConfig.html); Log4J provides a `configureAndWatch()` method but it is not recommended to use it inside J2EE containers (see [FAQ](https://logging.apache.org/log4j/1.2/faq.html#a3.6)). +### Server Side Warnings + +When using the driver to execute queries, it is possible that the server will generate warnings and +return them along with the results. Consider the following query: + +```sql +SELECT count(*) FROM cycling.cyclist_name; +``` + +Executing this query would generate a warning in Cassandra: + +``` +Aggregation query used without partition key +``` + +These +[query warnings](https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ExecutionInfo.html#getWarnings--) +are available programmatically from the +[ExecutionInfo](https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ExecutionInfo.html) +via +[ResultSet](https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ResultSet.html)'s +[getExecutionInfo()](https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/PagingIterable.html#getExecutionInfo--) +method. They are also logged by the driver: + +``` +WARN com.datastax.driver.core.RequestHandler - Query 'SELECT count(*) FROM cycling.cyclist_name' generated server side warning(s): Aggregation query used without partition key +``` + +Sometimes, it is not desirable for the driver to log server-side warnings. In such cases, logging +these warnings can be disabled in the driver by setting the system property `com.datastax.driver.DISABLE_QUERY_WARNING_LOGS` +to "true". This can be done at application startup (`-Dcom.datastax.driver.DISABLE_QUERY_WARNING_LOGS=true`) +or it can be toggled programmatically in application code: + +```java +// disable driver logging of server-side warnings +System.setProperty("com.datastax.driver.DISABLE_QUERY_WARNING_LOGS", "true"); +.... +// enable driver logging of server-side warnings +System.setProperty("com.datastax.driver.DISABLE_QUERY_WARNING_LOGS", "false"); +``` + ### Logback Example Here is a typical example configuration for Logback. *Please adapt it to your specific needs before using it!* @@ -299,4 +359,4 @@ It also turns on slow query tracing as described above. ``` -[query_logger]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/QueryLogger.html +[query_logger]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/QueryLogger.html diff --git a/manual/metadata/README.md b/manual/metadata/README.md index 51f28296283..817587f947d 100644 --- a/manual/metadata/README.md +++ b/manual/metadata/README.md @@ -1,10 +1,29 @@ + + ## Metadata The driver maintains global information about the Cassandra cluster it is connected to. It is available via [Cluster#getMetadata()][getMetadata]. -[getMetadata]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Cluster.html#getMetadata-- +[getMetadata]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.html#getMetadata-- ### Schema metadata @@ -12,8 +31,8 @@ Use [getKeyspace(String)][getKeyspace] or [getKeyspaces()][getKeyspaces] to get keyspace-level metadata. From there you can access the keyspace's objects (tables, and UDTs and UDFs if relevant). -[getKeyspace]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Metadata.html#getKeyspace-java.lang.String- -[getKeyspaces]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Metadata.html#getKeyspaces-- +[getKeyspace]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Metadata.html#getKeyspace-java.lang.String- +[getKeyspaces]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Metadata.html#getKeyspaces-- #### Refreshes @@ -47,8 +66,8 @@ Note that it is preferable to register a listener only *after* the cluster is fu otherwise the listener could be notified with a great deal of "Added" events as the driver builds the schema metadata from scratch for the first time. -[SchemaChangeListener]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SchemaChangeListener.html -[registerListener]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Cluster.html#register-com.datastax.driver.core.SchemaChangeListener- +[SchemaChangeListener]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SchemaChangeListener.html +[registerListener]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.html#register-com.datastax.driver.core.SchemaChangeListener- #### Schema agreement @@ -135,9 +154,9 @@ custom executor). Check out the API docs for the features in this section: -* [withMaxSchemaAgreementWaitSeconds(int)](http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Cluster.Builder.html#withMaxSchemaAgreementWaitSeconds-int-) -* [isSchemaInAgreement()](http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/ExecutionInfo.html#isSchemaInAgreement--) -* [checkSchemaAgreement()](http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Metadata.html#checkSchemaAgreement--) +* [withMaxSchemaAgreementWaitSeconds(int)](https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.Builder.html#withMaxSchemaAgreementWaitSeconds-int-) +* [isSchemaInAgreement()](https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ExecutionInfo.html#isSchemaInAgreement--) +* [checkSchemaAgreement()](https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Metadata.html#checkSchemaAgreement--) ### Token metadata @@ -181,14 +200,14 @@ Starting with Cassandra 2.1.5, this information is available in a system table (see [CASSANDRA-7688](https://issues.apache.org/jira/browse/CASSANDRA-7688)). -[metadata]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Metadata.html -[getTokenRanges]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Metadata.html#getTokenRanges-- -[getTokenRanges2]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Metadata.html#getTokenRanges-java.lang.String-com.datastax.driver.core.Host- -[getReplicas]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Metadata.html#getReplicas-java.lang.String-com.datastax.driver.core.TokenRange- -[newToken]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Metadata.html#newToken-java.lang.String- -[newTokenRange]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Metadata.html#newTokenRange-com.datastax.driver.core.Token-com.datastax.driver.core.Token- -[TokenRange]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TokenRange.html -[getTokens]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Host.html#getTokens-- -[setToken]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/BoundStatement.html#setToken-int-com.datastax.driver.core.Token- -[getToken]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Row.html#getToken-int- -[getPKToken]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Row.html#getPartitionKeyToken-- +[metadata]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Metadata.html +[getTokenRanges]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Metadata.html#getTokenRanges-- +[getTokenRanges2]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Metadata.html#getTokenRanges-java.lang.String-com.datastax.driver.core.Host- +[getReplicas]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Metadata.html#getReplicas-java.lang.String-com.datastax.driver.core.TokenRange- +[newToken]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Metadata.html#newToken-java.lang.String- +[newTokenRange]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Metadata.html#newTokenRange-com.datastax.driver.core.Token-com.datastax.driver.core.Token- +[TokenRange]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TokenRange.html +[getTokens]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Host.html#getTokens-- +[setToken]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/BoundStatement.html#setToken-int-com.datastax.driver.core.Token- +[getToken]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Row.html#getToken-int- +[getPKToken]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Row.html#getPartitionKeyToken-- diff --git a/manual/metrics/README.md b/manual/metrics/README.md index fe9c560e70c..7af7a050232 100644 --- a/manual/metrics/README.md +++ b/manual/metrics/README.md @@ -1,3 +1,22 @@ + + ## Metrics The driver exposes measurements of its internal behavior through the popular [Dropwizard Metrics] @@ -36,9 +55,9 @@ To do this in a maven project: ```xml - com.datastax.cassandra + org.apache.cassandra cassandra-driver-core - 3.6.0 + 3.12.1 io.dropwizard.metrics @@ -146,8 +165,8 @@ reporter.start(); [Reporters]: http://metrics.dropwizard.io/3.2.2/manual/core.html#reporters [MetricRegistry]: http://metrics.dropwizard.io/3.2.2/apidocs/com/codahale/metrics/MetricRegistry.html [MXBeans]: https://docs.oracle.com/javase/tutorial/jmx/mbeans/mxbeans.html -[withClusterName]: https://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Cluster.Builder.html#withClusterName-java.lang.String- -[withoutMetrics]: https://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Cluster.Builder.html#withoutMetrics-- -[withoutJMXReporting]: https://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Cluster.Builder.html#withoutJMXReporting-- -[getMetrics]: https://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Cluster.html#getMetrics-- -[Metrics]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Metrics.html +[withClusterName]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.Builder.html#withClusterName-java.lang.String- +[withoutMetrics]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.Builder.html#withoutMetrics-- +[withoutJMXReporting]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.Builder.html#withoutJMXReporting-- +[getMetrics]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.html#getMetrics-- +[Metrics]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Metrics.html diff --git a/manual/native_protocol/README.md b/manual/native_protocol/README.md index 363e10f3c90..7aab925ea9f 100644 --- a/manual/native_protocol/README.md +++ b/manual/native_protocol/README.md @@ -1,3 +1,22 @@ + + ## Native protocol The native protocol defines the format of the binary messages exchanged @@ -16,16 +35,23 @@ Cassandra when the first connection is established. Both sides are backward-compatible with older versions: - - - - - + + + + + + + + + + +
 Cassandra: 1.2.x
(DSE 3.2)
2.0.x
(DSE 4.0 to 4.6)
2.1.x
(DSE 4.7)
2.2.x3.0.x
Driver: 1.0.x v1 v1 v1 v1 Unsupported (1)
2.0.x to 2.1.1 v1 v2 v2 v2 Unsupported (1)
2.1.2 to 2.1.x v1 v2 v3 v3 Unsupported (2)
3.x v1 v2 v3 v4 v4
Driver VersionCassandra 1.2.x
(DSE 3.2)
Cassandra 2.0.x
(DSE 4.0 to 4.6)
Cassandra 2.1.x
(DSE 4.7)
Cassandra 2.2.xCassandra 3.0.x & 3.x
(DSE 5.0+)
Cassandra 4.0+
1.0.x v1 v1 v1 v1 Unsupported (1)Unsupported (1)
2.0.x to 2.1.1 v1 v2 v2 v2Unsupported (1) Unsupported (1)
2.1.2 to 2.1.x v1 v2 v3 v3Unsupported (2)Unsupported (2)
3.x v1 v2 v3 v4 v4 v5
-*(1) Cassandra 3.0 does not support protocol versions v1 and v2* +*(1) Cassandra 3.0+ does not support protocol versions v1 and v2* -*(2) There is a matching protocol version (v3), but the driver 2.1.x can't read the new system table format of Cassandra 3.0* +*(2) There is a matching protocol version (v3), but the driver 2.1.x can't read the new system table +format of Cassandra 3.0+* For example, if you use version 2.1.5 of the driver to connect to Cassandra 2.0.9, the maximum version you can use (and the one you'll get @@ -63,7 +89,7 @@ All host(s) tried for query failed [/127.0.0.1:9042] Host /127.0.0.1:9042 does not support protocol version V3 but V2)) ``` -[gpv]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersion-- +[gpv]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersion-- #### Protocol version with mixed clusters @@ -94,19 +120,19 @@ To avoid this issue, you can use one the following workarounds: #### v1 to v2 * bound variables in simple statements - ([Session#execute(String, Object...)](http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Session.html#execute-java.lang.String-java.lang.Object...-)) -* [batch statements](http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/BatchStatement.html) + ([Session#execute(String, Object...)](https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Session.html#execute-java.lang.String-java.lang.Object...-)) +* [batch statements](https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/BatchStatement.html) * [query paging](../paging/) #### v2 to v3 * the number of stream ids per connection goes from 128 to 32768 (see [Connection pooling](../pooling/)) -* [serial consistency on batch statements](http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/BatchStatement.html#setSerialConsistencyLevel-com.datastax.driver.core.ConsistencyLevel-) +* [serial consistency on batch statements](https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/BatchStatement.html#setSerialConsistencyLevel-com.datastax.driver.core.ConsistencyLevel-) * [client-side timestamps](../query_timestamps/) #### v3 to v4 -* [query warnings](http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/ExecutionInfo.html#getWarnings--) +* [query warnings](https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ExecutionInfo.html#getWarnings--) * allowed unset values in bound statements * [Custom payloads](../custom_payloads/) diff --git a/manual/object_mapper/README.md b/manual/object_mapper/README.md index 054e9e6e97c..3c3cc021822 100644 --- a/manual/object_mapper/README.md +++ b/manual/object_mapper/README.md @@ -1,3 +1,22 @@ + + # Object Mapper The driver provides a simple object mapper, which @@ -9,9 +28,9 @@ The mapper is published as a separate Maven artifact: ```xml - com.datastax.cassandra + org.apache.cassandra cassandra-driver-mapping - 3.6.0 + 3.12.1 ``` diff --git a/manual/object_mapper/creating/README.md b/manual/object_mapper/creating/README.md index 0819888e0b2..200fccf571e 100644 --- a/manual/object_mapper/creating/README.md +++ b/manual/object_mapper/creating/README.md @@ -1,3 +1,22 @@ + + ## Definition of mapped classes The object mapper is configured by annotations on the mapped classes. @@ -149,9 +168,9 @@ User user = new User() .setName("John Doe"); ``` -[table]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/Table.html +[table]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/Table.html [case-sensitive]:http://docs.datastax.com/en/cql/3.3/cql/cql_reference/ucase-lcase_r.html -[consistency level]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/ConsistencyLevel.html +[consistency level]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ConsistencyLevel.html [java-beans]:https://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html [set-accessible]:https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible-boolean- @@ -189,7 +208,7 @@ CREATE TABLE users(id uuid PRIMARY KEY, "userName" text); private String userName; ``` -[column]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/Column.html +[column]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/Column.html #### Primary key fields @@ -213,8 +232,8 @@ private String areaCode; The order of the indices must match that of the columns in the table declaration. -[pk]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/PartitionKey.html -[cc]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/ClusteringColumn.html +[pk]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/PartitionKey.html +[cc]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/ClusteringColumn.html [pks]:http://thelastpickle.com/blog/2013/01/11/primary-keys-in-cql.html #### Computed fields @@ -250,7 +269,7 @@ version (see [JAVA-832](https://datastax-oss.atlassian.net/browse/JAVA-832)). [User Defined Functions]:http://www.planetcassandra.org/blog/user-defined-functions-in-cassandra-3-0/ -[computed]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/Computed.html +[computed]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/Computed.html #### Transient properties @@ -259,7 +278,7 @@ to table columns. [@Transient][transient] can be used to prevent a field or a Java bean property from being mapped. Like other column-level annotations, it should be placed on either the field declaration or the property getter method. -[transient]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/Transient.html +[transient]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/Transient.html ### Mapping User Types @@ -322,8 +341,8 @@ This also works with UDTs inside collections or other UDTs, with any arbitrary nesting level. [User Defined Types]: ../../udts/ -[udt]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/UDT.html -[field]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/Field.html +[udt]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/UDT.html +[field]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/Field.html ### Mapping collections @@ -359,9 +378,32 @@ private Map> frozenKeyValueMap; private Map> frozenValueMap; ``` -[frozen]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/Frozen.html -[frozenkey]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/FrozenKey.html -[frozenvalue]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/FrozenValue.html +With regards to tuples, these can be represented as `TupleValue` fields, i.e.: + +```java +@Frozen +private TupleValue myTupleValue; +``` + +Please note however that tuples are not a good fit for the mapper since it is up to the user to +resolve the associated `TupleType` when creating and accessing `TupleValue`s and properly use the +right types since java type information is not known. + +Also note that `@UDT`-annotated classes are not implicitly registered with `TupleValue` like they +otherwise are because the mapper is not able to identify the cql type information at the time +entities are constructed. + +To work around this, one may use [udtCodec] to register a `TypeCodec` that the mapper can use +to figure out how to appropriately handle UDT conversion, i.e.: + +```java +mappingManager.udtCodec(Address.class); +``` + +[frozen]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/Frozen.html +[frozenkey]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/FrozenKey.html +[frozenvalue]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/FrozenValue.html +[udtCodec]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/MappingManager.html#udtCodec-java.lang.Class- #### Prefer Frozen Collections diff --git a/manual/object_mapper/custom_codecs/README.md b/manual/object_mapper/custom_codecs/README.md index e423b3bae79..d3b5414fbe8 100644 --- a/manual/object_mapper/custom_codecs/README.md +++ b/manual/object_mapper/custom_codecs/README.md @@ -1,3 +1,22 @@ + + # Using custom codecs The mapper can take advantage of [custom codecs](../../custom_codecs/) @@ -98,9 +117,9 @@ instance (one per column) and cache it for future use. This also works with [@Field][field] and [@Param][param] annotations. -[column]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/Column.html -[field]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/Field.html -[param]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/Param.html +[column]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/Column.html +[field]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/Field.html +[param]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/Param.html ## Implicit UDT codecs diff --git a/manual/object_mapper/using/README.md b/manual/object_mapper/using/README.md index 457c00be5a3..35fdc54e088 100644 --- a/manual/object_mapper/using/README.md +++ b/manual/object_mapper/using/README.md @@ -1,3 +1,22 @@ + + ## Using the mapper First, create a [MappingManager]. It wraps an existing [Session] @@ -28,9 +47,9 @@ Mapper mapper = manager.mapper(User.class); calling `manager#mapper` more than once for the same class will return the previously generated mapper. -[Mapper]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/Mapper.html -[MappingManager]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/MappingManager.html -[Session]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Session.html +[Mapper]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/Mapper.html +[MappingManager]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/MappingManager.html +[Session]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Session.html #### Basic CRUD operations @@ -179,7 +198,7 @@ It provides methods `one()`, `all()`, `iterator()`, `getExecutionInfo()` and `isExhausted()`. Note that iterating the `Result` will consume the `ResultSet`, and vice-versa. -[Result]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/Result.html +[Result]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/Result.html ### Accessors @@ -229,7 +248,7 @@ corresponds to which marker: ResultSet insert(@Param("u") UUID userId, @Param("n") String name); ``` -[param]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/Param.html +[param]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/Param.html If a method argument is a Java enumeration, it must be annotated with `@Enumerated` to indicate how to convert it to a CQL type (the rules are @@ -301,7 +320,7 @@ query with the annotation [@QueryParameters]. Then, options like public ListenableFuture> getAllAsync(); ``` -[@QueryParameters]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/annotations/QueryParameters.html +[@QueryParameters]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/annotations/QueryParameters.html ### Mapping configuration @@ -345,6 +364,6 @@ PropertyMapper propertyMapper = new DefaultPropertyMapper() There is more to `DefaultPropertyMapper`; see the Javadocs and implementation for details. -[MappingConfiguration]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/MappingConfiguration.html -[PropertyMapper]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/PropertyMapper.html -[DefaultPropertyMapper]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/mapping/DefaultPropertyMapper.html +[MappingConfiguration]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/MappingConfiguration.html +[PropertyMapper]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/PropertyMapper.html +[DefaultPropertyMapper]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/mapping/DefaultPropertyMapper.html diff --git a/manual/osgi/README.md b/manual/osgi/README.md index 36a91b7155d..eb0c83e70da 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, @@ -12,7 +31,7 @@ the following Maven artifacts are actually valid OSGi bundles: We have complete examples demonstrating usage of the driver in an OSGi environment; please refer to our [OSGi examples repository]. -[OSGi examples repository]:https://github.com/datastax/java-driver-examples-osgi +[OSGi examples repository]:https://github.com/apache/cassandra-java-driver-examples-osgi ## Troubleshooting OSGi applications diff --git a/manual/paging/README.md b/manual/paging/README.md index 5453c34f80f..34ca70e8672 100644 --- a/manual/paging/README.md +++ b/manual/paging/README.md @@ -1,3 +1,22 @@ + + ## Paging When a query returns many rows, it would be inefficient to return them @@ -176,8 +195,8 @@ if (nextPage != null) { } ``` -[result_set]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/ResultSet.html -[paging_state]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/PagingState.html +[result_set]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ResultSet.html +[paging_state]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/PagingState.html Due to internal implementation details, `PagingState` instances are not @@ -239,8 +258,8 @@ There are two situations where you might want to use the unsafe API: implementing your own validation logic (for example, signing the raw state with a private key). -[gpsu]: https://www.datastax.com/drivers/java/3.6/com/datastax/driver/core/ExecutionInfo.html#getPagingStateUnsafe-- -[spsu]: https://www.datastax.com/drivers/java/3.6/com/datastax/driver/core/Statement.html#setPagingStateUnsafe-byte:A- +[gpsu]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ExecutionInfo.html#getPagingStateUnsafe-- +[spsu]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Statement.html#setPagingStateUnsafe-byte:A- ### Offset queries diff --git a/manual/pooling/README.md b/manual/pooling/README.md index 1838e2f926b..9bad1a995a4 100644 --- a/manual/pooling/README.md +++ b/manual/pooling/README.md @@ -1,3 +1,22 @@ + + ## Connection pooling ### Basics @@ -285,16 +304,16 @@ either: [newConnectionThreshold][nct] so that enough connections are added by the time you reach the bottleneck. -[result_set_future]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/ResultSetFuture.html -[pooling_options]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/PoolingOptions.html -[lbp]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/LoadBalancingPolicy.html -[nct]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold-com.datastax.driver.core.HostDistance-int- -[mrpc]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection-com.datastax.driver.core.HostDistance-int- -[sits]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds-int- -[rtm]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis-- -[smqs]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/PoolingOptions.html#setMaxQueueSize-int- -[sptm]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis-int- -[nhae]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/NoHostAvailableException.html -[getErrors]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/NoHostAvailableException.html#getErrors-- -[get_state]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Session.html#getState-- -[BusyPoolException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/BusyPoolException.html +[result_set_future]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ResultSetFuture.html +[pooling_options]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/PoolingOptions.html +[lbp]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/LoadBalancingPolicy.html +[nct]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold-com.datastax.driver.core.HostDistance-int- +[mrpc]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection-com.datastax.driver.core.HostDistance-int- +[sits]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds-int- +[rtm]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis-- +[smqs]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/PoolingOptions.html#setMaxQueueSize-int- +[sptm]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis-int- +[nhae]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/NoHostAvailableException.html +[getErrors]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/NoHostAvailableException.html#getErrors-- +[get_state]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Session.html#getState-- +[BusyPoolException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/BusyPoolException.html diff --git a/manual/query_timestamps/README.md b/manual/query_timestamps/README.md index 8b2fac9d5d9..27d60bdf20a 100644 --- a/manual/query_timestamps/README.md +++ b/manual/query_timestamps/README.md @@ -1,3 +1,22 @@ + + ## Query timestamps In Cassandra, each mutation has a microsecond-precision timestamp, which @@ -140,10 +159,10 @@ following: Steps 2 and 3 only apply if native protocol v3 or above is in use. -[TimestampGenerator]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TimestampGenerator.html -[AtomicMonotonicTimestampGenerator]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.html -[ThreadLocalMonotonicTimestampGenerator]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/ThreadLocalMonotonicTimestampGenerator.html -[ServerSideTimestampGenerator]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/ServerSideTimestampGenerator.html +[TimestampGenerator]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TimestampGenerator.html +[AtomicMonotonicTimestampGenerator]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.html +[ThreadLocalMonotonicTimestampGenerator]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ThreadLocalMonotonicTimestampGenerator.html +[ServerSideTimestampGenerator]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ServerSideTimestampGenerator.html [gettimeofday]: http://man7.org/linux/man-pages/man2/settimeofday.2.html [JNR]: https://github.com/jnr/jnr-ffi diff --git a/manual/reconnection/README.md b/manual/reconnection/README.md index d1273197077..797e8fc0ea4 100644 --- a/manual/reconnection/README.md +++ b/manual/reconnection/README.md @@ -1,11 +1,54 @@ -## Reconnection + -[ReconnectionPolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/ReconnectionPolicy.html \ No newline at end of file +## Reconnection + +If the driver loses a connection to a node, it tries to re-establish it according to a configurable +policy. This is used in two places: + +* [connection pools](../pooling/): for each node, a session has a fixed-size pool of connections to + execute user requests. If a node is detected as down, a reconnection is started. +* [control connection](../control_connection/): a session uses a single connection to an arbitrary + node for administrative requests. If that connection goes down, a reconnection gets started; each + attempt iterates through all active nodes until one of them accepts a connection. This goes on + until we have a control node again. + +[ReconnectionPolicy] controls the interval between each attempt. The policy to use may be +provided using [Cluster.Builder.withReconnectionPolicy]. For example, the following configures +an [ExponentialReconnectionPolicy] with a base delay of 1 second, and a max delay of 10 minutes +(this is the default behavior). + +```java +Cluster.builder() + .withReconnectionPolicy(new ExponentialReconnectionPolicy(1000, 10 * 60 * 1000)) + .build(); +``` + +[ConstantReconnectionPolicy] uses the same delay every time, regardless of the +previous number of attempts. + +You can also write your own policy; it must implement [ReconnectionPolicy]. + +For best results, use reasonable values: very low values (for example a constant delay of 10 +milliseconds) will quickly saturate your system. + +[ReconnectionPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/ReconnectionPolicy.html +[Cluster.Builder.withReconnectionPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Cluster.Builder.html#withReconnectionPolicy-com.datastax.driver.core.policies.ReconnectionPolicy- +[ExponentialReconnectionPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/ExponentialReconnectionPolicy.html +[ConstantReconnectionPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/ConstantReconnectionPolicy.html diff --git a/manual/retries/README.md b/manual/retries/README.md index 5c450ce1ebd..27091ad1526 100644 --- a/manual/retries/README.md +++ b/manual/retries/README.md @@ -1,3 +1,22 @@ + + ## Retries When a query fails, it sometimes makes sense to retry it: the error might be temporary, or the query might work on a @@ -146,37 +165,37 @@ implementations to handle idempotence (the new behavior is equivalent to what yo `IdempotenceAwareRetryPolicy` before). -[RetryDecision]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html -[retry()]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html#retry-com.datastax.driver.core.ConsistencyLevel- -[tryNextHost()]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html#tryNextHost-com.datastax.driver.core.ConsistencyLevel- -[rethrow()]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html#rethrow-- -[ignore()]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html#ignore-- -[NoHostAvailableException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/NoHostAvailableException.html -[getErrors()]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/NoHostAvailableException.html#getErrors-- -[RetryPolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/RetryPolicy.html -[DefaultRetryPolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/DefaultRetryPolicy.html -[onReadTimeout]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/DefaultRetryPolicy.html#onReadTimeout-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-int-int-boolean-int- -[onWriteTimeout]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/DefaultRetryPolicy.html#onWriteTimeout-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-com.datastax.driver.core.WriteType-int-int-int- -[onUnavailable]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/DefaultRetryPolicy.html#onUnavailable-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-int-int-int- -[onRequestError]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/DefaultRetryPolicy.html#onRequestError-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-com.datastax.driver.core.exceptions.DriverException-int- -[UnavailableException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/UnavailableException.html -[ReadTimeoutException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/ReadTimeoutException.html -[WriteTimeoutException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/WriteTimeoutException.html -[OverloadedException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/OverloadedException.html -[ServerError]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/ServerError.html -[OperationTimedOutException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/OperationTimedOutException.html -[ConnectionException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/ConnectionException.html -[QueryValidationException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/QueryValidationException.html -[InvalidQueryException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/InvalidQueryException.html -[InvalidConfigurationInQueryException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/InvalidConfigurationInQueryException.html -[UnauthorizedException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/UnauthorizedException.html -[SyntaxError]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/SyntaxError.html -[AlreadyExistsException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/AlreadyExistsException.html -[TruncateException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/TruncateException.html +[RetryDecision]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html +[retry()]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html#retry-com.datastax.driver.core.ConsistencyLevel- +[tryNextHost()]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html#tryNextHost-com.datastax.driver.core.ConsistencyLevel- +[rethrow()]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html#rethrow-- +[ignore()]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/RetryPolicy.RetryDecision.html#ignore-- +[NoHostAvailableException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/NoHostAvailableException.html +[getErrors()]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/NoHostAvailableException.html#getErrors-- +[RetryPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/RetryPolicy.html +[DefaultRetryPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/DefaultRetryPolicy.html +[onReadTimeout]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/DefaultRetryPolicy.html#onReadTimeout-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-int-int-boolean-int- +[onWriteTimeout]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/DefaultRetryPolicy.html#onWriteTimeout-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-com.datastax.driver.core.WriteType-int-int-int- +[onUnavailable]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/DefaultRetryPolicy.html#onUnavailable-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-int-int-int- +[onRequestError]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/DefaultRetryPolicy.html#onRequestError-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-com.datastax.driver.core.exceptions.DriverException-int- +[UnavailableException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/UnavailableException.html +[ReadTimeoutException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/ReadTimeoutException.html +[WriteTimeoutException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/WriteTimeoutException.html +[OverloadedException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/OverloadedException.html +[ServerError]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/ServerError.html +[OperationTimedOutException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/OperationTimedOutException.html +[ConnectionException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/ConnectionException.html +[QueryValidationException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/QueryValidationException.html +[InvalidQueryException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/InvalidQueryException.html +[InvalidConfigurationInQueryException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/InvalidConfigurationInQueryException.html +[UnauthorizedException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/UnauthorizedException.html +[SyntaxError]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/SyntaxError.html +[AlreadyExistsException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/AlreadyExistsException.html +[TruncateException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/TruncateException.html [query plan]: ../load_balancing/#query-plan [connection pool]: ../pooling/ [prepared]: ../statements/prepared/#preparing-on-multiple-nodes [driver read timeout]: ../socket_options/#driver-read-timeout [hinted handoffs]: https://docs.datastax.com/en/cassandra/2.1/cassandra/dml/dml_about_hh_c.html?scroll=concept_ds_ifg_jqx_zj__performance -[idempotence]: ../idempotence/ \ No newline at end of file +[idempotence]: ../idempotence/ diff --git a/manual/shaded_jar/README.md b/manual/shaded_jar/README.md index b4cfe416561..9bfe8e59564 100644 --- a/manual/shaded_jar/README.md +++ b/manual/shaded_jar/README.md @@ -1,3 +1,22 @@ + + ## Using the shaded JAR The default driver JAR depends on [Netty](http://netty.io/), which is @@ -10,9 +29,9 @@ package name: ```xml - com.datastax.cassandra + org.apache.cassandra cassandra-driver-core - 3.6.0 + 3.12.1 shaded @@ -21,6 +40,10 @@ package name: io.netty *
+ + io.dropwizard.metrics + metrics-core +
``` @@ -30,24 +53,28 @@ non-shaded JAR: ```xml - com.datastax.cassandra + org.apache.cassandra cassandra-driver-core - 3.6.0 + 3.12.1 shaded io.netty * + + io.dropwizard.metrics + metrics-core + - com.datastax.cassandra + org.apache.cassandra cassandra-driver-mapping - 3.6.0 + 3.12.1 - com.datastax.cassandra + org.apache.cassandra cassandra-driver-core @@ -74,5 +101,5 @@ detects that shaded Netty classes are being used: Detected shaded Netty classes in the classpath; native epoll transport will not work properly, defaulting to NIO. -[NettyOptions]:http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/NettyOptions.html +[NettyOptions]:https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/NettyOptions.html [Netty native transports]:http://netty.io/wiki/native-transports.html diff --git a/manual/socket_options/README.md b/manual/socket_options/README.md index 26e5fdad733..47021853d81 100644 --- a/manual/socket_options/README.md +++ b/manual/socket_options/README.md @@ -1,3 +1,22 @@ + + ## Socket options [SocketOptions] controls various low-level parameters related to TCP connections between the driver and Cassandra. @@ -117,15 +136,15 @@ To clarify: We might rename `SocketOptions.setReadTimeoutMillis` in a future version to clear up any confusion. -[SocketOptions]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SocketOptions.html -[setReadTimeoutMillis]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SocketOptions.html#setReadTimeoutMillis-int- -[setConnectTimeoutMillis]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SocketOptions.html#setConnectTimeoutMillis-int- -[setKeepAlive]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SocketOptions.html#setKeepAlive-boolean- -[setReceiveBufferSize]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SocketOptions.html#setReceiveBufferSize-int- -[setReuseAddress]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SocketOptions.html#setReuseAddress-boolean- -[setSendBufferSize]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SocketOptions.html#setSendBufferSize-int- -[setSoLinger]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SocketOptions.html#setSoLinger-int- -[setTcpNoDelay]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SocketOptions.html#setTcpNoDelay-boolean- -[onReadTimeout]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/RetryPolicy.html#onReadTimeout-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-int-int-boolean-int- -[onRequestError]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/RetryPolicy.html#onRequestError-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-com.datastax.driver.core.exceptions.DriverException-int- -[OperationTimedOutException]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/exceptions/OperationTimedOutException.html \ No newline at end of file +[SocketOptions]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SocketOptions.html +[setReadTimeoutMillis]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SocketOptions.html#setReadTimeoutMillis-int- +[setConnectTimeoutMillis]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SocketOptions.html#setConnectTimeoutMillis-int- +[setKeepAlive]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SocketOptions.html#setKeepAlive-boolean- +[setReceiveBufferSize]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SocketOptions.html#setReceiveBufferSize-int- +[setReuseAddress]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SocketOptions.html#setReuseAddress-boolean- +[setSendBufferSize]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SocketOptions.html#setSendBufferSize-int- +[setSoLinger]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SocketOptions.html#setSoLinger-int- +[setTcpNoDelay]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SocketOptions.html#setTcpNoDelay-boolean- +[onReadTimeout]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/RetryPolicy.html#onReadTimeout-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-int-int-boolean-int- +[onRequestError]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/RetryPolicy.html#onRequestError-com.datastax.driver.core.Statement-com.datastax.driver.core.ConsistencyLevel-com.datastax.driver.core.exceptions.DriverException-int- +[OperationTimedOutException]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/exceptions/OperationTimedOutException.html diff --git a/manual/speculative_execution/README.md b/manual/speculative_execution/README.md index 157cfae3b6c..90915bb2b8c 100644 --- a/manual/speculative_execution/README.md +++ b/manual/speculative_execution/README.md @@ -1,3 +1,22 @@ + + ## Speculative query execution Sometimes a Cassandra node might be experiencing difficulties (ex: long @@ -73,7 +92,7 @@ Speculative executions are controlled by an instance of `Cluster`. This policy defines the threshold after which a new speculative execution will be triggered. -[SpeculativeExecutionPolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html +[SpeculativeExecutionPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html Two implementations are provided with the driver: @@ -101,7 +120,7 @@ way: * if no response has been received at t0 + 1000 milliseconds, start another speculative execution on a third node. -[ConstantSpeculativeExecutionPolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.html +[ConstantSpeculativeExecutionPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.html #### [PercentileSpeculativeExecutionPolicy] @@ -160,10 +179,10 @@ Note that `PercentileTracker` may also be used with a slow query logger (see the [Logging](../logging/) section). In that case, you would create a single tracker object and share it with both components. -[PercentileSpeculativeExecutionPolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.html -[PercentileTracker]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/PercentileTracker.html -[ClusterWidePercentileTracker]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/ClusterWidePercentileTracker.html -[PerHostPercentileTracker]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/PerHostPercentileTracker.html +[PercentileSpeculativeExecutionPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.html +[PercentileTracker]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/PercentileTracker.html +[ClusterWidePercentileTracker]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ClusterWidePercentileTracker.html +[PerHostPercentileTracker]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/PerHostPercentileTracker.html [hdr]: http://hdrhistogram.github.io/HdrHistogram/ #### Using your own @@ -210,7 +229,7 @@ client driver exec1 exec2 The only impact is that all executions of the same query always share the same query plan, so each host will be used by at most one execution. -[retry_policy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/RetryPolicy.html +[retry_policy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/RetryPolicy.html ### Tuning and practical details @@ -225,8 +244,8 @@ You can monitor how many speculative executions were triggered with the It should only be a few percents of the total number of requests ([cluster.getMetrics().getRequestsTimer().getCount()][request_metric]). -[se_metric]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Metrics.Errors.html#getSpeculativeExecutions-- -[request_metric]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Metrics.html#getRequestsTimer-- +[se_metric]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Metrics.Errors.html#getSpeculativeExecutions-- +[request_metric]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Metrics.html#getRequestsTimer-- #### Stream id exhaustion @@ -255,8 +274,8 @@ sustained. If you're unsure of which native protocol version you're using, you can check with [cluster.getConfiguration().getProtocolOptions().getProtocolVersion()][protocol_version]. -[session_state]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Session.State.html -[protocol_version]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersion-- +[session_state]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Session.State.html +[protocol_version]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersion-- #### Request ordering and client timestamps diff --git a/manual/ssl/README.md b/manual/ssl/README.md index 8297660925e..e9d56d69d46 100644 --- a/manual/ssl/README.md +++ b/manual/ssl/README.md @@ -1,3 +1,22 @@ + + ## SSL You can secure traffic between the driver and Cassandra with SSL. There @@ -207,8 +226,8 @@ Cluster cluster = Cluster.builder() .build(); ``` -[RemoteEndpointAwareSSLOptions]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/RemoteEndpointAwareSSLOptions.html -[RemoteEndpointAwareJdkSSLOptions]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/RemoteEndpointAwareJdkSSLOptions.html -[newSSLEngine]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/RemoteEndpointAwareJdkSSLOptions.html#newSSLEngine-io.netty.channel.socket.SocketChannel-java.net.InetSocketAddress- -[RemoteEndpointAwareNettySSLOptions]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/RemoteEndpointAwareNettySSLOptions.html -[NettyOptions]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/NettyOptions.html +[RemoteEndpointAwareSSLOptions]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/RemoteEndpointAwareSSLOptions.html +[RemoteEndpointAwareJdkSSLOptions]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/RemoteEndpointAwareJdkSSLOptions.html +[newSSLEngine]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/RemoteEndpointAwareJdkSSLOptions.html#newSSLEngine-io.netty.channel.socket.SocketChannel-java.net.InetSocketAddress- +[RemoteEndpointAwareNettySSLOptions]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/RemoteEndpointAwareNettySSLOptions.html +[NettyOptions]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/NettyOptions.html diff --git a/manual/statements/README.md b/manual/statements/README.md index d06f5f33387..a078eec4446 100644 --- a/manual/statements/README.md +++ b/manual/statements/README.md @@ -1,3 +1,22 @@ + + ## Statements To execute a query, you create a [Statement] instance and pass it to [Session#execute()][execute] or @@ -32,11 +51,11 @@ If you use custom policies ([RetryPolicy], [LoadBalancingPolicy], properties that influence statement execution. To achieve this, you can wrap your statements in a custom [StatementWrapper] implementation. -[Statement]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Statement.html -[QueryBuilder]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/querybuilder/QueryBuilder.html -[StatementWrapper]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/StatementWrapper.html -[RetryPolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/RetryPolicy.html -[LoadBalancingPolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/LoadBalancingPolicy.html -[SpeculativeExecutionPolicy]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html -[execute]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Session.html#execute-com.datastax.driver.core.Statement- -[executeAsync]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Session.html#executeAsync-com.datastax.driver.core.Statement- +[Statement]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Statement.html +[QueryBuilder]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/querybuilder/QueryBuilder.html +[StatementWrapper]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/StatementWrapper.html +[RetryPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/RetryPolicy.html +[LoadBalancingPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/LoadBalancingPolicy.html +[SpeculativeExecutionPolicy]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html +[execute]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Session.html#execute-com.datastax.driver.core.Statement- +[executeAsync]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Session.html#executeAsync-com.datastax.driver.core.Statement- diff --git a/manual/statements/batch/README.md b/manual/statements/batch/README.md index ebc156d731b..776afb56227 100644 --- a/manual/statements/batch/README.md +++ b/manual/statements/batch/README.md @@ -1,5 +1,61 @@ + + ## Batch statements -*Coming soon... In the meantime, see the javadoc for [BatchStatement].* +Use [BatchStatement] to execute a set of queries as a single operation (refer to +[Batching inserts, updates and deletes][batch_dse] to understand how to use batching effectively): + +```java +PreparedStatement preparedInsertExpense = + session.prepare( + "INSERT INTO cyclist_expenses (cyclist_name, expense_id, amount, description, paid) " + + "VALUES (:name, :id, :amount, :description, :paid)"); +SimpleStatement simpleInsertBalance = + new SimpleStatement("INSERT INTO cyclist_expenses (cyclist_name, balance) VALUES (?, 0) IF NOT EXISTS", + "Vera ADRIAN"); + +BatchStatement batch = new BatchStatement(BatchStatement.Type.UNLOGGED) + .add(simpleInsertBalance) + .add(preparedInsertExpense.bind("Vera ADRIAN", 1, 7.95f, "Breakfast", false)); + +session.execute(batch); +``` + +As shown in the examples above, batches can contain any combination of simple statements and bound +statements. A given batch can contain at most 65536 statements. Past this limit, addition methods +throw an `IllegalStateException`. + +By default, batches are configured as [LOGGED]. This ensures that if any statement in the batch +succeeds, all will eventually succeed. Ensuring all queries in a batch succeed has a +performance cost. Consider using [UNLOGGED] as shown above if you do not need this capability. + +Please note that the size of a batch is subject to the [batch_size_fail_threshold] configuration +option on the server. + +In addition, simple statements with named parameters are currently not supported in batches (this is +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]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/BatchStatement.html +[BatchStatement]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/BatchStatement.html +[batch_dse]: http://docs.datastax.com/en/dse/5.1/cql/cql/cql_using/useBatch.html +[LOGGED]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/BatchStatement.Type.html#LOGGED +[UNLOGGED]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/BatchStatement.Type.html#UNLOGGED +[batch_size_fail_threshold]: https://docs.datastax.com/en/cassandra/3.x/cassandra/configuration/configCassandra_yaml.html#configCassandra_yaml__batch_size_fail_threshold_in_kb +[CASSANDRA-10246]: https://issues.apache.org/jira/browse/CASSANDRA-10246 diff --git a/manual/statements/built/README.md b/manual/statements/built/README.md index bafc20f3eeb..ac0ba28b1e6 100644 --- a/manual/statements/built/README.md +++ b/manual/statements/built/README.md @@ -1,3 +1,22 @@ + + ## Built statements Built statements are generated via [QueryBuilder]'s Fluent API. Use of Fluent API allows @@ -76,7 +95,7 @@ BuiltStatement ttlAndWriteTime = QueryBuilder.select().column("id").column("t") ``` You can also cast the value of the given column to another type by using the `cast` function, -[specifying](https://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/querybuilder/QueryBuilder.html#cast-java.lang.Object-com.datastax.driver.core.DataType-) +[specifying](https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/querybuilder/QueryBuilder.html#cast-java.lang.Object-com.datastax.driver.core.DataType-) the column for which it should be performed, and to what type it should be casted. #### Specifying conditions @@ -92,7 +111,7 @@ BuiltStatement selectOne = QueryBuilder.select().from("test", "test") The `where` function accepts the `Clause` object that is generated by calling `QueryBuilder`'s -[functions](https://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/querybuilder/QueryBuilder.html#eq-java.lang.Iterable-java.lang.Iterable-), +[functions](https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/querybuilder/QueryBuilder.html#eq-java.lang.Iterable-java.lang.Iterable-), such as, `eq`, `ne`, `lt`, `in`, `contains`, `notNull`, etc. In most cases, these functions receive 2 arguments: the name of the column, and the value to compare, but there are also variants that receive 2 iterables for columns and values correspondingly. @@ -263,6 +282,6 @@ Note: the call to these functions changes the object type from `BuiltStatement` -[QueryBuilder]: https://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/querybuilder/QueryBuilder.html -[TableMetadata]: https://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TableMetadata.html -[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/schemabuilder/SchemaBuilder.html +[QueryBuilder]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/querybuilder/QueryBuilder.html +[TableMetadata]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TableMetadata.html +[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/schemabuilder/SchemaBuilder.html diff --git a/manual/statements/prepared/README.md b/manual/statements/prepared/README.md index a1556b8c2c1..ccb0a33167a 100644 --- a/manual/statements/prepared/README.md +++ b/manual/statements/prepared/README.md @@ -1,3 +1,22 @@ + + ## Prepared statements Use [PreparedStatement] for queries that are executed multiple times in your application: @@ -256,11 +275,11 @@ relying on `SELECT *`. This will be addressed in a future release of both Cassandra and the driver. Follow [CASSANDRA-10786] and [JAVA-1196] for more information. -[PreparedStatement]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/PreparedStatement.html -[BoundStatement]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/BoundStatement.html -[setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts-boolean- -[setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp-boolean- -[execute]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Session.html#execute-com.datastax.driver.core.Statement- -[executeAsync]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/Session.html#executeAsync-com.datastax.driver.core.Statement- +[PreparedStatement]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/PreparedStatement.html +[BoundStatement]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/BoundStatement.html +[setPrepareOnAllHosts]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts-boolean- +[setReprepareOnUp]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp-boolean- +[execute]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Session.html#execute-com.datastax.driver.core.Statement- +[executeAsync]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/Session.html#executeAsync-com.datastax.driver.core.Statement- [CASSANDRA-10786]: https://issues.apache.org/jira/browse/CASSANDRA-10786 [JAVA-1196]: https://datastax-oss.atlassian.net/browse/JAVA-1196 diff --git a/manual/statements/simple/README.md b/manual/statements/simple/README.md index 386937c1ec2..35ba0e4c9ab 100644 --- a/manual/statements/simple/README.md +++ b/manual/statements/simple/README.md @@ -1,3 +1,22 @@ + + ## Simple statements Use [SimpleStatement] for queries that will be executed only once (or a few times) in your application: @@ -128,4 +147,4 @@ session.execute( 1, bytes); ``` -[SimpleStatement]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/SimpleStatement.html +[SimpleStatement]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/SimpleStatement.html diff --git a/manual/tuples/README.md b/manual/tuples/README.md index b524a634100..6e7f844718f 100644 --- a/manual/tuples/README.md +++ b/manual/tuples/README.md @@ -1,4 +1,23 @@ -## Using Tuples with the Java driver + + +## Using Tuples with the Java Driver Cassandra allows to use `tuple` data types [in tables and user-defined types](https://docs.datastax.com/en/cql/3.1/cql/cql_reference/tupleType.html): @@ -14,7 +33,7 @@ CREATE TABLE ks.collect_things ( ### Fetching Tuples from Rows results -The DataStax Java driver exposes a special [`TupleValue`][TupleValue] class to handle such columns. +The Java Driver exposes a special [`TupleValue`][TupleValue] class to handle such columns. [`TupleValue`][TupleValue] exposes getters allowing to extract from the tuple all the data types supported by Cassandra: @@ -83,7 +102,7 @@ session.execute(bs); More generally, the `IN` keyword in a `SELECT` query will be used to define a *list* of desired values of the filtered clustering keys, those would simply be bound as a list of -[`TupleValue`][TupleValue] with the Java driver: +[`TupleValue`][TupleValue] with the Java Driver: ```java TupleType oneTimeUsageTuple = cluster.getMetadata().newTupleType(DataType.text(), DataType.text()); @@ -96,7 +115,7 @@ bs.setList("l", Arrays.asList(oneTimeUsageTuple.newValue("1", "1"), oneTimeUsage session.execute(bs); ``` -[TupleType]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TupleType.html -[TupleValue]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TupleValue.html -[newValueVararg]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TupleType.html#newValue-java.lang.Object...- -[newValue]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/TupleType.html#newValue-- +[TupleType]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TupleType.html +[TupleValue]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TupleValue.html +[newValueVararg]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TupleType.html#newValue-java.lang.Object...- +[newValue]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/TupleType.html#newValue-- diff --git a/manual/udts/README.md b/manual/udts/README.md index 8fd946908d7..f8d15885b0b 100644 --- a/manual/udts/README.md +++ b/manual/udts/README.md @@ -1,5 +1,118 @@ + + ## User-defined types -*Coming soon... In the meantime, see the javadoc for [UserType].* +[CQL user-defined types][cql_doc] are ordered sets of named, typed fields. They must be defined in a +keyspace: + +``` +CREATE TYPE ks.type1 ( + a int, + b text, + c float); +``` + +And can then be used as a column type in tables, or a field type in other user-defined types in that +keyspace: + +``` +CREATE TABLE ks.collect_things ( + pk int, + ck1 text, + ck2 text, + v frozen, + PRIMARY KEY (pk, ck1, ck2) +); + +CREATE TYPE ks.type2 (v frozen); +``` + +### Fetching UDTs from results + +The driver maps UDT columns to the [UDTValue] class, which exposes getters and setters to access +individual fields by index or name: + +```java +Row row = session.execute("SELECT v FROM ks.collect_things WHERE pk = 1").one(); + +UDTValue udtValue = row.getUDTValue("v"); +int a = udtValue.getInt(0); +String b = udtValue.getString("b"); +Float c = udtValue.getFloat(2); +``` + +### Using UDTs as parameters + +Statements may contain UDTs as bound values: + +```java +PreparedStatement ps = + session.prepare( + "INSERT INTO ks.collect_things (pk, ck1, ck2, v) VALUES (:pk, :ck1, :ck2, :v)"); +``` + +To create a new UDT value, you must first have a reference to its [UserType]. There are +various ways to get it: + +* from the statement's metadata + + ```java + UserType udt = (UserType) ps.getVariables().getType("v"); + ``` + +* from the driver's [schema metadata](../metadata/#schema-metadata): + + ```java + UserType udt = session.getCluster().getMetadata().getKeyspace("ks").getUserType("type1"); + ``` + +* from another UDT value: + + ```java + UserType udt = udtValue.getType(); + ``` + +Note that the driver's official API does not expose a way to build [UserType] instances manually. +This is because the type's internal definition must precisely match the database schema; +if it doesn't (for example if the fields are not in the same order), you run the risk of inserting +corrupt data, that you won't be able to read back. + +Once you have the type, call `newValue()` and set the fields: + +```java +UDTValue udtValue = udt.newValue().setInt(0, 1).setString(1, "hello").setFloat(2, 2.3f); +``` + +And bind your UDT value like any other type: + +```java +BoundStatement bs = + ps.bind() + .setInt("pk", 1) + .setString("ck1", "1") + .setString("ck2", "1") + .setUDTValue("v", udtValue); +session.execute(bs); +``` + +[cql_doc]: https://docs.datastax.com/en/cql/3.3/cql/cql_reference/cqlRefUDType.html -[UserType]: http://docs.datastax.com/en/drivers/java/3.6/com/datastax/driver/core/UserType.html \ No newline at end of file +[UDTValue]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/UDTValue.html +[UserType]: https://docs.datastax.com/en/drivers/java/3.11/com/datastax/driver/core/UserType.html diff --git a/pom.xml b/pom.xml index f6408522554..d179f45d04f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,12 +1,14 @@ - 2.7.9.3 + 2.7.9.7 2.9.9 1.0 1.0.4 @@ -78,6 +85,7 @@ 6.8.8 1.7.0 1.10.8 + 2.25.0 1.3 1.1.2 1.2.3 @@ -94,33 +102,33 @@ - com.datastax.cassandra + org.apache.cassandra cassandra-driver-core ${project.parent.version} - com.datastax.cassandra + org.apache.cassandra cassandra-driver-core ${project.parent.version} shaded - com.datastax.cassandra + org.apache.cassandra cassandra-driver-core ${project.parent.version} test-jar - com.datastax.cassandra + org.apache.cassandra cassandra-driver-mapping ${project.parent.version} - com.datastax.cassandra + org.apache.cassandra cassandra-driver-extras ${project.parent.version} @@ -323,6 +331,12 @@ ${mockito.version} + + com.github.tomakehurst + wiremock + ${wiremock.version} + + org.scassandra java-client @@ -343,7 +357,7 @@ io.netty - netty-tcnative + netty-tcnative-boringssl-static ${netty-tcnative.version} ${os.detected.classifier} @@ -489,77 +503,14 @@ jar-no-fork - - - - - - maven-javadoc-plugin - 2.10.4 - true - - true - false - ${javadoc.opts} - - https://docs.oracle.com/javase/8/docs/api/ - https://google.github.io/guava/releases/19.0/api/docs/ - http://netty.io/4.0/api/ - http://www.joda.org/joda-time/apidocs/ - http://fasterxml.github.io/jackson-core/javadoc/2.8/ - http://fasterxml.github.io/jackson-databind/javadoc/2.7/ - https://javaee-spec.java.net/nonav/javadocs/ - - - - - org.xerial.snappy - snappy-java - ${snappy.version} - - - org.lz4 - lz4-java - ${lz4.version} - - - org.hdrhistogram - HdrHistogram - ${hdr.version} - - - com.fasterxml.jackson.core - jackson-core - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind.version} - - - joda-time - joda-time - ${joda.version} - - - javax.json - javax.json-api - ${jsr353-api.version} - - - - - - attach-javadocs - - jar - + + + NOTICE.txt + + + NOTICE_binary.txt + + @@ -634,7 +585,7 @@ - 3.5.0 + 3.11.5 ../clirr-ignores.xml com/datastax/shaded/** @@ -658,7 +609,7 @@ com.coveo fmt-maven-plugin - 2.5.1 + 2.9 @@ -668,13 +619,15 @@ org.codehaus.mojo animal-sniffer-maven-plugin - 1.15 + 1.16 check-jdk6 @@ -725,8 +678,7 @@ limitations under the License. 1.0
- com.datastax.driver.extras.codecs.jdk8.IgnoreJDK6Requirement - + com.datastax.driver.core.IgnoreJDK6Requirement @@ -894,6 +846,14 @@ limitations under the License. + + org.apache.maven.plugins + maven-remote-resources-plugin + 1.7.0 + + true + + @@ -1012,17 +972,14 @@ limitations under the License. jar-no-fork - - - - - maven-javadoc-plugin - - - attach-javadocs - - jar - + + + NOTICE.txt + + + NOTICE_binary.txt + + @@ -1058,9 +1015,6 @@ limitations under the License. [1.8,) - - -Xdoclint:none - @@ -1077,6 +1031,13 @@ limitations under the License. + + org.apache.maven.plugins + maven-javadoc-plugin + + none + + @@ -1119,14 +1080,24 @@ limitations under the License. true - - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - + + apple-silicon-dev + + + mac os x + mac + aarch64 + + + + + 2.2.10 + 1.1.10.1 + + + + @@ -1140,7 +1111,7 @@ limitations under the License. scm:git:git@github.com:datastax/java-driver.git scm:git:git@github.com:datastax/java-driver.git - https://github.com/datastax/java-driver + https://github.com/apache/cassandra-java-driver HEAD diff --git a/testing/README.md b/testing/README.md index 4dfbb525351..d1d97a6620b 100644 --- a/testing/README.md +++ b/testing/README.md @@ -1,3 +1,22 @@ + + ## Testing Prerequisites ### Install CCM diff --git a/testing/bin/coverage b/testing/bin/coverage old mode 100755 new mode 100644 index c920e9fa6d1..82702a91f4b --- a/testing/bin/coverage +++ b/testing/bin/coverage @@ -1,4 +1,20 @@ #!/usr/bin/env python +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this 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. import argparse import ConfigParser diff --git a/upgrade_guide/README.md b/upgrade_guide/README.md index e85262ed847..acec88fefdd 100644 --- a/upgrade_guide/README.md +++ b/upgrade_guide/README.md @@ -1,7 +1,26 @@ + + ## Upgrade guide The purpose of this guide is to detail changes made by successive -versions of the Java driver. +versions of the Java Driver. ### 3.6.0 @@ -52,7 +71,7 @@ versions of the Java driver. [JAVA-1752]:https://datastax-oss.atlassian.net/browse/JAVA-1752 [JAVA-1376]:https://datastax-oss.atlassian.net/browse/JAVA-1376 -[online example]:https://github.com/datastax/java-driver/blob/3.x/driver-examples/src/main/java/com/datastax/driver/examples/retry/DowngradingRetry.java +[online example]:https://github.com/apache/cassandra-java-driver/blob/3.x/driver-examples/src/main/java/com/datastax/driver/examples/retry/DowngradingRetry.java 2. The `TokenAwarePolicy` now has a new constructor that takes a `ReplicaOrdering` argument, see [JAVA-1448]. diff --git a/upgrade_guide/migrating_from_astyanax/README.md b/upgrade_guide/migrating_from_astyanax/README.md index 0b518322a28..72bd82f9c58 100644 --- a/upgrade_guide/migrating_from_astyanax/README.md +++ b/upgrade_guide/migrating_from_astyanax/README.md @@ -1,10 +1,29 @@ + + # Migrating from Astyanax This section is a guide for users previously using *Astyanax* and looking for -migrating to the *DataStax Java driver*. +migrating to the *Java Driver*. See the child pages for more information: * [Changes at the language level](language_level_changes/) -* [Migrating Astyanax configurations to DataStax Java driver configurations](configuration/) +* [Migrating Astyanax configurations to Java Driver configurations](configuration/) * [Querying and retrieving results comparisons.](queries_and_results/) diff --git a/upgrade_guide/migrating_from_astyanax/configuration/README.md b/upgrade_guide/migrating_from_astyanax/configuration/README.md index c6629113d7f..6e94149dc47 100644 --- a/upgrade_guide/migrating_from_astyanax/configuration/README.md +++ b/upgrade_guide/migrating_from_astyanax/configuration/README.md @@ -1,22 +1,41 @@ + + # Configuration -## How Configuring the Java driver works +## How Configuring the Java Driver works -The two basic components in the Java driver are the `Cluster` and the `Session`. +The two basic components in the Java Driver are the `Cluster` and the `Session`. The `Cluster` is the object to create first, and on to which all global configurations apply. Connecting to the `Cluster` creates a `Session`. Queries are executed through the `Session`. The `Cluster` object then is to be viewed as the equivalent of the `AstyanaxContext` object. "Starting" an `AstyanaxContext` object typically returns a `Keyspace` -object, the `Keyspace` object is the equivalent of the *Java driver*’s `Session`. +object, the `Keyspace` object is the equivalent of the *Java Driver*’s `Session`. Configuring a `Cluster` works with the *Builder* pattern. The `Builder` takes all the configurations into account before building the `Cluster`. Following are some examples of the most important configurations that were -possible with *Astyanax* and how to translate them into *DataStax Java driver* -configurations. Please note that the Java driver has been optimized to handle most use +possible with *Astyanax* and how to translate them into *Java Driver* +configurations. Please note that the Java Driver has been optimized to handle most use cases at best and even though the following sections show how to tune some various options, the driver should provide the best performances with the default configurations and these options should not be changed unless there is a good reason to. @@ -25,11 +44,11 @@ and these options should not be changed unless there is a good reason to. Configuration of connection pools in *Astyanax* are made through the `ConnectionPoolConfigurationImpl`. This object gathers important configurations -that the *Java driver* has categorized in multiple *Option* and *Policy* kinds. +that the *Java Driver* has categorized in multiple *Option* and *Policy* kinds. ### Connections pools internals Everything concerning the internal pools of connections to the *Cassandra nodes* -will be gathered in the Java driver in the [`PoolingOptions`](../../../manual/pooling): +will be gathered in the Java Driver in the [`PoolingOptions`](../../../manual/pooling): *Astyanax*: @@ -40,7 +59,7 @@ ConnectionPoolConfigurationImpl cpool = .setMaxConnsPerHost(3) ``` -*Java driver*: +*Java Driver*: ```java PoolingOptions poolingOptions = @@ -50,10 +69,10 @@ PoolingOptions poolingOptions = The first number is the initial number of connections, the second is the maximum number of connections the driver is allowed to create for each host. -Note that the *Java driver* allows multiple simultaneous requests on one single +Note that the *Java Driver* allows multiple simultaneous requests on one single connection, as it is based upon the [*Native protocol*](../../../manual/native_protocol), an asynchronous binary protocol that can handle up to 32768 simultaneous requests on a -single connection. The Java driver is able to manage and distribute simultaneous requests +single connection. The Java Driver is able to manage and distribute simultaneous requests by itself even under high contention, and changing the default `PoolingOptions` is not necessary most of the time except for very [specific use cases](../../../manual/pooling/#tuning-protocol-v3-for-very-high-throughputs). @@ -83,18 +102,18 @@ Changing the client timeout options might have more impacts than expected, **ple sure to properly document before changing these options.** ## Load Balancing -Both *Astyanax* and the *Java driver* connect to multiple nodes of the *Cassandra* +Both *Astyanax* and the *Java Driver* connect to multiple nodes of the *Cassandra* cluster. Distributing requests through all the nodes plays an important role in the good operation of the `Cluster` and for best performances. With *Astyanax*, requests (or “operations”) can be sent directly to replicas that have a copy of the data targeted by the *“Row key”* specified in the operation. Since the *Thrift* API is low-level, it forces the user to provide *Row keys*, known as the `TokenAware` -connection pool type. This setting is also present in the *Java driver*, however +connection pool type. This setting is also present in the *Java Driver*, however the configuration is different and provides more options to tweak. -Load balancing in the *Java driver* is a *Policy*, it is a class that will be -plugged in the *Java driver*’s code and the Driver will call its methods when it -needs to. The *Java driver* comes with a preset of specific load balancing policies. +Load balancing in the *Java Driver* is a *Policy*, it is a class that will be +plugged in the *Java Driver*’s code and the Driver will call its methods when it +needs to. The *Java Driver* comes with a preset of specific load balancing policies. Here’s an equivalent code: *Astyanax*: @@ -111,7 +130,7 @@ AstyanaxConfigurationImpl aconf = .setDiscoveryType(discType) ``` -*Java driver*: +*Java Driver*: ```java LoadBalancingPolicy lbp = new TokenAwarePolicy( @@ -121,7 +140,7 @@ LoadBalancingPolicy lbp = new TokenAwarePolicy( ); ``` -*By default* the *Java driver* will instantiate the exact Load balancing policy +*By default* the *Java Driver* will instantiate the exact Load balancing policy shown above, with the `LocalDC` being the DC of the first host the driver connects to. So to get the same behaviour than the *TokenAware* pool type of *Astyanax*, users shouldn’t need to specify a load balancing policy since the default one @@ -129,14 +148,14 @@ should cover it. Important: Note that since *CQL* is an abstraction of the Cassandra’s architecture, a simple query needs to have the *Row key* specified explicitly on a `Statement` in order -to benefit from the *TokenAware* routing (the *Row key* in the *Java driver* is +to benefit from the *TokenAware* routing (the *Row key* in the *Java Driver* is referenced as *Routing Key*), unlike the *Astyanax* driver. Some differences occur related to the different kinds of `Statements` the *Java driver* provides. Please see [this link](../../../manual/load_balancing/#token-aware-policy) for specific information. Custom load balancing policies can easily be implemented by users, and supplied to -the *Java driver* for specific use cases. All information necessary is available +the *Java Driver* for specific use cases. All information necessary is available in the [Load balaning policies docs](../../../manual/load_balancing). ## Consistency levels @@ -151,26 +170,26 @@ AstyanaxConfigurationImpl aconf = .setDefaultWriteConsistencyLevel(ConsistencyLevel.CL*ALL) ``` -*Java driver*: +*Java Driver*: ```java QueryOptions qo = new QueryOptions().setConsistencyLevel(ConsistencyLevel.ALL); ``` -Since the *Java driver* only executes *CQL* statements, which can be either reads +Since the *Java Driver* only executes *CQL* statements, which can be either reads or writes to *Cassandra*, it is not possible to globally configure the Consistency Level for only reads or only writes. To do so, since the Consistency Level can be set per-statement, you can either set it on every statement, or use `PreparedStatements` (if queries are to be repeated with different values): in this case, setting the CL on the `PreparedStatement`, causes the `BoundStatements` to inherit the CL from the prepared statements they were prepared from. More -informations about how `Statement`s work in the *Java driver* are detailed +informations about how `Statement`s work in the *Java Driver* are detailed in the [“Queries and Results” section](../queries_and_results/). ## Authentication -Authentication settings are managed by the `AuthProvider` class in the *Java driver*. +Authentication settings are managed by the `AuthProvider` class in the *Java Driver*. It can be highly customizable, but also comes with default simple implementations: *Astyanax*: @@ -182,7 +201,7 @@ ConnectionPoolConfigurationImpl cpool = .setAuthenticationCredentials(authCreds) ``` -*Java driver*: +*Java Driver*: ```java AuthProvider authProvider = new PlainTextAuthProvider("username", "password"); @@ -205,7 +224,7 @@ ConnectionPoolConfigurationImpl cpool = .setPort(9160) ``` -*Java driver*: +*Java Driver*: ```java Cluster cluster = Cluster.builder() @@ -213,7 +232,7 @@ Cluster cluster = Cluster.builder() .withPort(9042) ``` -The *Java driver* by default connects to port *9042*, hence you can supply only +The *Java Driver* by default connects to port *9042*, hence you can supply only host names with the `addContactPoints(String...)` method. Note that the contact points are only the entry points to the `Cluster` for the *Automatic discovery phase*. @@ -222,7 +241,7 @@ phase*. With all options previously presented, one may configure and create the `Cluster` object this way: -*Java driver*: +*Java Driver*: ```java Cluster cluster = Cluster.builder() @@ -240,7 +259,7 @@ Session session = cluster.connect(); A few best practices are summed up in [this blog post](http://www.datastax.com/dev/blog/4-simple-rules-when-using-the-datastax-drivers-for-cassandra). -Concerning connection pools, the Java driver’s default settings should allow +Concerning connection pools, the Java Driver’s default settings should allow most of the users to get the best out of the driver in terms of throughput, they have been thoroughly tested and tweaked to accommodate the users’ needs. If one still wishes to change those, first [Monitoring the pools](../../../manual/pooling/#monitoring-and-tuning-the-pool) is @@ -248,5 +267,5 @@ advised, then a [deep dive in the Pools management mechanism](../../../manual/po provide enough insight. A lot more options are available in the different `XxxxOption`s classes, policies are -also highly customizable since the base Java driver's implementations can easily be +also highly customizable since the base Java Driver's implementations can easily be extended and implement user-specific actions. diff --git a/upgrade_guide/migrating_from_astyanax/language_level_changes/README.md b/upgrade_guide/migrating_from_astyanax/language_level_changes/README.md index 8116e82b566..8b17c78b81d 100644 --- a/upgrade_guide/migrating_from_astyanax/language_level_changes/README.md +++ b/upgrade_guide/migrating_from_astyanax/language_level_changes/README.md @@ -1,3 +1,22 @@ + + # Language change : from Thrift to CQL The data model changes when using *CQL* (Cassandra Query Language). *CQL* is providing an abstraction of the low-level data stored in *Cassandra*, in diff --git a/upgrade_guide/migrating_from_astyanax/queries_and_results/README.md b/upgrade_guide/migrating_from_astyanax/queries_and_results/README.md index 3f14620bac7..6fee3b2705e 100644 --- a/upgrade_guide/migrating_from_astyanax/queries_and_results/README.md +++ b/upgrade_guide/migrating_from_astyanax/queries_and_results/README.md @@ -1,8 +1,27 @@ + + # Queries and Results There are many resources such as [this post][planetCCqlLink] or [this post][dsBlogCqlLink] to learn how to transform previous Thrift operations to CQL queries. -The *Java driver* executes CQL queries through the `Session`. +The *Java Driver* executes CQL queries through the `Session`. The queries can either be simple *CQL* Strings or represented in the form of `Statement`s. The driver offers 4 kinds of statements, `SimpleStatement`, `Prepared/BoundStatement`, `BuiltStatement`, and `BatchStatement`. All necessary @@ -14,7 +33,7 @@ results of a *CQL* query will be in the form of *Rows* from *Tables*, composed of fixed set of columns, each with a type and a name. The driver exposes the set of *Rows* returned from a query as a ResultSet, thus containing *Rows* on which `getXXX()` can be called. Here are simple examples of translation from -*Astyanax* to *Java driver* in querying and retrieving query results. +*Astyanax* to *Java Driver* in querying and retrieving query results. ## Single column @@ -30,7 +49,7 @@ Column result = keyspace.prepareQuery(CF_STANDARD1) String value = result.getStringValue(); ``` -*Java driver*: +*Java Driver*: ``` Row row = session.execute("SELECT value FROM table1 WHERE key = '1' AND column1 = '3'").one(); @@ -57,7 +76,7 @@ while (!(columns = query.execute().getResult()).isEmpty()) { } ``` -*Java driver*: +*Java Driver*: ```java ResultSet rs = session.execute("SELECT value FROM table1 WHERE key = '1'"); @@ -84,7 +103,7 @@ while (it.hasNext()) { } ``` -*Java driver*: +*Java Driver*: ```java ResultSet rs = session.execute("SELECT value FROM table1 WHERE key = '1'" + @@ -96,11 +115,11 @@ for (Row row : rs) { ``` ## Async -The *Java driver* provides native support for asynchronous programming since it +The *Java Driver* provides native support for asynchronous programming since it is built on top of an [asynchronous protocol](../../../manual/native_protocol/), please see [this page](../../../manual/async/) for best practices regarding asynchronous programming -with the *Java driver*. +with the *Java Driver*. [planetCCqlLink]: http://www.planetcassandra.org/making-the-change-from-thrift-to-cql/ -[dsBlogCqlLink]: http://www.datastax.com/dev/blog/thrift-to-cql3 \ No newline at end of file +[dsBlogCqlLink]: http://www.datastax.com/dev/blog/thrift-to-cql3