├── driver-core └── src │ ├── main │ ├── resources │ │ └── com │ │ │ └── datastax │ │ │ └── driver │ │ │ └── core │ │ │ └── Driver.properties │ └── java │ │ └── com │ │ └── datastax │ │ └── driver │ │ └── core │ │ ├── Clock.java │ │ ├── exceptions │ │ ├── package-info.java │ │ ├── InvalidTypeException.java │ │ ├── SyntaxError.java │ │ ├── QueryValidationException.java │ │ ├── TruncateException.java │ │ ├── UnsupportedFeatureException.java │ │ ├── QueryExecutionException.java │ │ ├── InvalidQueryException.java │ │ ├── InvalidConfigurationInQueryException.java │ │ ├── UnauthorizedException.java │ │ ├── TraceRetrievalException.java │ │ ├── DriverInternalError.java │ │ ├── DriverException.java │ │ ├── AuthenticationException.java │ │ ├── WriteTimeoutException.java │ │ └── QueryTimeoutException.java │ │ ├── policies │ │ ├── package-info.java │ │ ├── ChainableLoadBalancingPolicy.java │ │ ├── CloseableLoadBalancingPolicy.java │ │ ├── IdentityTranslater.java │ │ ├── ConstantReconnectionPolicy.java │ │ └── ReconnectionPolicy.java │ │ ├── querybuilder │ │ ├── package-info.java │ │ ├── Ordering.java │ │ ├── BindMarker.java │ │ ├── Truncate.java │ │ └── Using.java │ │ ├── schemabuilder │ │ ├── package-info.java │ │ ├── StatementStart.java │ │ ├── ColumnType.java │ │ └── UDTType.java │ │ ├── package-info.java │ │ ├── GettableData.java │ │ ├── BusyConnectionException.java │ │ ├── SettableData.java │ │ ├── ProtocolV1Authenticator.java │ │ ├── SystemProperties.java │ │ ├── ServerSideTimestampGenerator.java │ │ ├── TransportException.java │ │ ├── TimestampGenerator.java │ │ ├── ConnectionException.java │ │ ├── ExceptionCatchingRunnable.java │ │ ├── MetricsOptions.java │ │ ├── PreparedId.java │ │ ├── UnsupportedProtocolVersionException.java │ │ ├── ClusterNameMismatchException.java │ │ ├── AbstractTimestampGenerator.java │ │ ├── HostDistance.java │ │ ├── AtomicMonotonicTimestampGenerator.java │ │ ├── MD5Digest.java │ │ ├── ThreadLocalMonotonicTimestampGenerator.java │ │ ├── WriteType.java │ │ ├── AuthProvider.java │ │ ├── LatencyTracker.java │ │ ├── ExceptionCode.java │ │ ├── ConsistencyLevel.java │ │ ├── PooledConnection.java │ │ ├── TupleValue.java │ │ ├── ConvictionPolicy.java │ │ ├── UDTValue.java │ │ └── ArrayBackedRow.java │ └── test │ ├── resources │ ├── META-INF │ │ └── services │ │ │ └── org.testng.ITestNGListener │ └── log4j.properties │ └── java │ └── com │ └── datastax │ └── driver │ └── core │ ├── Assertions.java │ ├── SimpleStatementTest.java │ ├── MockClocks.java │ ├── MemoryAppender.java │ ├── SessionAssert.java │ ├── ClusterAssert.java │ ├── SimpleJSONParserTest.java │ ├── policies │ ├── CloseableLoadBalancingPolicyTest.java │ ├── AlwaysIgnoreRetryPolicy.java │ ├── AlwaysRetryRetryPolicy.java │ └── DelegatingLoadBalancingPolicy.java │ ├── schemabuilder │ ├── CreateIndexTest.java │ └── CompressionOptionsTest.java │ ├── TokenMapTest.java │ ├── StreamIdGeneratorTest.java │ ├── VersionNumberTest.java │ ├── SingleConnectionPoolTest.java │ ├── AsyncQueryTest.java │ ├── MetricsTest.java │ ├── FetchingTest.java │ ├── CaseSensitivityTest.java │ ├── TypeCodecTest.java │ ├── MissingRpcAddressTest.java │ └── AtomicMonotonicTimestampGeneratorTest.java ├── src └── main │ └── config │ └── ide │ ├── intellij-code-style.jar │ └── eclipse.importorder ├── .gitignore ├── driver-examples ├── stress │ ├── README.rst │ ├── src │ │ └── main │ │ │ └── java │ │ │ └── com │ │ │ └── datastax │ │ │ └── driver │ │ │ └── stress │ │ │ ├── Consumer.java │ │ │ ├── BlockingConsumer.java │ │ │ └── QueryGenerator.java │ └── bin │ │ ├── stress │ │ └── build └── pom.xml ├── driver-mapping └── src │ ├── main │ └── java │ │ └── com │ │ └── datastax │ │ └── driver │ │ └── mapping │ │ ├── annotations │ │ ├── FrozenKey.java │ │ ├── FrozenValue.java │ │ ├── Accessor.java │ │ ├── Param.java │ │ ├── Transient.java │ │ ├── ClusteringColumn.java │ │ ├── PartitionKey.java │ │ ├── Enumerated.java │ │ ├── Query.java │ │ ├── UDT.java │ │ ├── QueryParameters.java │ │ ├── Column.java │ │ ├── Field.java │ │ ├── Frozen.java │ │ └── Table.java │ │ ├── EnumType.java │ │ ├── ReflectionUtils.java │ │ ├── AccessorReflectionMapper.java │ │ ├── AccessorMapper.java │ │ ├── ColumnMapper.java │ │ └── AccessorInvocationHandler.java │ └── test │ └── java │ └── com │ └── datastax │ └── driver │ └── mapping │ ├── MapperAccessorTest.java │ ├── AnnotationChecksTest.java │ └── MapperCompositeKeyTest.java ├── driver-dist └── src │ └── assembly │ └── binary-tarball.xml ├── testing └── README.md └── CONTRIBUTING.rst /driver-core/src/main/resources/com/datastax/driver/core/Driver.properties: -------------------------------------------------------------------------------- 1 | driver.version=${project.version} -------------------------------------------------------------------------------- /driver-core/src/test/resources/META-INF/services/org.testng.ITestNGListener: -------------------------------------------------------------------------------- 1 | com.datastax.driver.core.TestListener 2 | -------------------------------------------------------------------------------- /src/main/config/ide/intellij-code-style.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Bridge/java-driver/2.1/src/main/config/ide/intellij-code-style.jar -------------------------------------------------------------------------------- /src/main/config/ide/eclipse.importorder: -------------------------------------------------------------------------------- 1 | #Organize Import Order 2 | #Sun Oct 19 21:16:33 CEST 2014 3 | 5=\#com.datastax.driver.core 4 | 4=com.datastax.driver.core 5 | 3=\# 6 | 2= 7 | 1=\#java 8 | 0=java 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | cobertura-history/ 3 | testing/ 4 | .settings 5 | .classpath 6 | .project 7 | doc 8 | notes 9 | .DS_Store 10 | 11 | /.idea 12 | *.iml 13 | 14 | /driver-core/dependency-reduced-pom.xml 15 | -------------------------------------------------------------------------------- /driver-core/src/test/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # Set root logger level to DEBUG and its only appender to A1. 2 | log4j.rootLogger=INFO, A1 3 | 4 | # A1 is set to be a ConsoleAppender. 5 | log4j.appender.A1=org.apache.log4j.ConsoleAppender 6 | 7 | # A1 uses PatternLayout. 8 | log4j.appender.A1.layout=org.apache.log4j.PatternLayout 9 | log4j.appender.A1.layout.ConversionPattern=\ %-6r [%t] %-5p %c %x - %m%n 10 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/Assertions.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.core; 2 | 3 | /** 4 | * Augment AssertJ with custom assertions for the Java driver. 5 | */ 6 | public class Assertions extends org.assertj.core.api.Assertions{ 7 | public static ClusterAssert assertThat(Cluster cluster) { 8 | return new ClusterAssert(cluster); 9 | } 10 | 11 | public static SessionAssert assertThat(Session session) { 12 | return new SessionAssert(session); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.core; 2 | 3 | import java.util.Collections; 4 | import java.util.List; 5 | 6 | import org.testng.annotations.Test; 7 | 8 | public class SimpleStatementTest { 9 | @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class }) 10 | public void should_fail_if_too_many_variables() { 11 | List args = Collections.nCopies(1 << 16, (Object)1); 12 | new SimpleStatement("mock query", args.toArray()); 13 | } 14 | } -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/MockClocks.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.core; 2 | 3 | class MockClocks { 4 | static class BackInTimeClock implements Clock { 5 | final long arbitraryTimeStamp = 1412610226270L; 6 | int calls; 7 | 8 | @Override 9 | public long currentTime() { 10 | return arbitraryTimeStamp - calls++; 11 | } 12 | } 13 | 14 | static class FixedTimeClock implements Clock { 15 | final long fixedTime; 16 | 17 | public FixedTimeClock(long fixedTime) { 18 | this.fixedTime = fixedTime; 19 | } 20 | 21 | @Override 22 | public long currentTime() { 23 | return fixedTime; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/Clock.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.core; 2 | 3 | /** 4 | * This interface allows us not to have a direct call to {@code System.currentTimeMillis()} for testing purposes 5 | */ 6 | interface Clock { 7 | /** 8 | * Returns the current time in milliseconds 9 | * 10 | * @return the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC. 11 | * @see System#currentTimeMillis() 12 | */ 13 | long currentTime(); 14 | } 15 | 16 | /** 17 | * Default implementation of a clock that delegate its calls to the system clock. 18 | */ 19 | class SystemClock implements Clock { 20 | @Override 21 | public long currentTime() { 22 | return System.currentTimeMillis(); 23 | } 24 | } -------------------------------------------------------------------------------- /driver-examples/stress/README.rst: -------------------------------------------------------------------------------- 1 | Stress application 2 | ================== 3 | 4 | A simple example application that uses the java driver to stress test 5 | Cassandra. This also somewhat stress test the java driver as a result. 6 | 7 | Please note that this simple example is far from being a complete stress 8 | application. In particular it currently supports a very limited number of 9 | stress scenario. 10 | 11 | Usage 12 | ----- 13 | 14 | You will need to build the stress application fist: 15 | 16 | ./bin/build 17 | 18 | After which you can run it using for instance: 19 | 20 | ./bin/stress insert_prepared 21 | 22 | Of course, you will need to have at least one Cassandra node running (on 23 | 127.0.0.1 by default) for this to work. Please refer to: 24 | 25 | ./bin/stress -h 26 | 27 | for more details on the options available. 28 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/MemoryAppender.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.core; 2 | 3 | import java.io.StringWriter; 4 | 5 | import org.apache.log4j.PatternLayout; 6 | import org.apache.log4j.WriterAppender; 7 | 8 | /** 9 | * Simple Log4J appender that captures logs to memory in order to inspect them in unit tests. 10 | *

11 | * There is no purging mechanism, so make sure it doesn't stay enabled for too long (this is best 12 | * done with an {@code @After} method that removes it). 13 | */ 14 | public class MemoryAppender extends WriterAppender { 15 | public final StringWriter writer = new StringWriter(); 16 | 17 | public MemoryAppender() { 18 | setWriter(writer); 19 | setLayout(new PatternLayout("%m%n")); 20 | } 21 | 22 | public String get() { 23 | return writer.toString(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | /** 17 | * Exceptions thrown by the DataStax Java driver for Cassandra. 18 | */ 19 | package com.datastax.driver.core.exceptions; 20 | -------------------------------------------------------------------------------- /driver-examples/stress/src/main/java/com/datastax/driver/stress/Consumer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.stress; 17 | 18 | public interface Consumer { 19 | 20 | public void start(); 21 | public void join(); 22 | } 23 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/policies/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | /** 17 | * Policies that allow to control some of the behavior of the DataStax Java driver for Cassandra. 18 | */ 19 | package com.datastax.driver.core.policies; 20 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/querybuilder/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | /** 17 | * A CQL3 query builder. 18 | *

19 | * The main entry for this package is the {@code QueryBuilder} class. 20 | */ 21 | package com.datastax.driver.core.querybuilder; 22 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/schemabuilder/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | /** 17 | * A CQL3 schema builder. 18 | *

19 | * The main entry for this package is the {@code SchemaBuilder} class. 20 | */ 21 | package com.datastax.driver.core.schemabuilder; 22 | -------------------------------------------------------------------------------- /driver-examples/stress/bin/stress: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | SCRIPT_DIR=$( cd "$( dirname "$0" )" && pwd ) 4 | CURRENT_DIR=$( pwd ) 5 | 6 | # Use $JAVA_HOME if set 7 | if [ -n "$JAVA_HOME" ]; then 8 | JAVA="$JAVA_HOME/bin/java" 9 | else 10 | JAVA=java 11 | fi 12 | 13 | if [ "x$STRESS_JAR" = "x" ]; then 14 | 15 | STRESS_JAR="$SCRIPT_DIR/../target/cassandra-driver-examples-stress-*-jar-with-dependencies.jar" 16 | 17 | if [ ! -f $STRESS_JAR ]; then 18 | # Trash the version file in case there was some crap in it 19 | RELATIVE_SCRIPT_DIR=`dirname $0` 20 | echo "Stress application does not seem to be build, try $RELATIVE_SCRIPT_DIR/build first" 1>&2 21 | exit 1 22 | fi 23 | else 24 | if [ ! -f $STRESS_JAR ]; then 25 | echo "Cannot find file $STRESS_JAR" 1>&2 26 | exit 1 27 | fi 28 | fi 29 | 30 | "$JAVA" -Dlog4j.configuration="$SCRIPT_DIR/../conf/log4j.properties" -jar $STRESS_JAR $@ 31 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | /** 17 | * The main package for the DataStax Java driver for Cassandra. 18 | *

19 | * The main entry for this package is the {@code Cluster} class. 20 | */ 21 | package com.datastax.driver.core; 22 | -------------------------------------------------------------------------------- /driver-examples/stress/bin/build: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | SCRIPT_DIR=$( cd "$( dirname "$0" )" && pwd ) 4 | CURRENT_DIR=$( pwd ) 5 | 6 | LOG_FILE="$CURRENT_DIR/stress_build.log" 7 | [ -f $LOG_FILE ] && rm $LOG_FILE 8 | 9 | echo "Building java driver ..." 10 | echo "-- Driver build --\n" > $LOG_FILE 11 | 12 | cd $SCRIPT_DIR/../../.. 13 | mvn clean install -Dmaven.test.skip=true >> $LOG_FILE 2>&1 14 | EXIT_CODE=$? 15 | if [ $EXIT_CODE -ne 0 ]; 16 | then 17 | echo "Error building driver. See $LOG_FILE for details." 1>&2 18 | cd $CURRENT_DIR 19 | exit $EXIT_CODE 20 | fi 21 | 22 | echo "Building stress application ..." 23 | echo "\n-- Stress build --\n" >> $LOG_FILE 24 | 25 | cd $SCRIPT_DIR/.. 26 | mvn package assembly:single >> $LOG_FILE 2>&1 27 | EXIT_CODE=$? 28 | if [ $EXIT_CODE -ne 0 ]; 29 | then 30 | echo "Error building stress application. See $LOG_FILE for details." 1>&2 31 | cd $CURRENT_DIR 32 | exit $EXIT_CODE 33 | fi 34 | 35 | cd $CURRENT_DIR 36 | rm $LOG_FILE 37 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/GettableData.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | /** 19 | * Collection of (typed) CQL values that can be retrieved either by index (starting a 0) or by name. 20 | */ 21 | public interface GettableData extends GettableByIndexData, GettableByNameData { 22 | } 23 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/BusyConnectionException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | class BusyConnectionException extends Exception 19 | { 20 | private static final long serialVersionUID = 0; 21 | 22 | public BusyConnectionException() { 23 | super(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/schemabuilder/StatementStart.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.schemabuilder; 17 | 18 | /** 19 | * The start of a statement, that another class will append to, to build the final statement. 20 | */ 21 | interface StatementStart { 22 | String buildInternal(); 23 | } 24 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/SessionAssert.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.core; 2 | 3 | import org.assertj.core.api.AbstractAssert; 4 | 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | 7 | public class SessionAssert extends AbstractAssert { 8 | 9 | protected SessionAssert(Session actual) { 10 | // We are cheating a bit by casting, but this is the only implementation anyway 11 | super((SessionManager)actual, SessionAssert.class); 12 | } 13 | 14 | public SessionAssert hasPoolFor(int hostNumber) { 15 | Host host = TestUtils.findHost(actual.cluster, hostNumber); 16 | assertThat(actual.pools.containsKey(host)).isTrue(); 17 | return this; 18 | } 19 | 20 | public SessionAssert hasNoPoolFor(int hostNumber) { 21 | Host host = TestUtils.findHost(actual.cluster, hostNumber); 22 | assertThat(actual.pools.containsKey(host)).isFalse(); 23 | return this; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/SettableData.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | import java.util.*; 18 | 19 | /** 20 | * Collection of (typed) CQL values that can set either by index (starting a 0) or by name. 21 | */ 22 | public interface SettableData> extends SettableByIndexData, SettableByNameData { 23 | } 24 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/ProtocolV1Authenticator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.util.Map; 19 | 20 | // Not an interface because we don't want to expose it. We only support password authentication 21 | // for the protocol V1 similarly to what the driver 1.x branch do. 22 | abstract class ProtocolV1Authenticator { 23 | abstract Map getCredentials(); 24 | } 25 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.core; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import org.assertj.core.api.AbstractAssert; 5 | 6 | public class ClusterAssert extends AbstractAssert { 7 | protected ClusterAssert(Cluster actual) { 8 | super(actual, ClusterAssert.class); 9 | } 10 | 11 | public ClusterAssert usesControlHost(int node) { 12 | String expectedAddress = CCMBridge.ipOfNode(node); 13 | Host controlHost = actual.manager.controlConnection.connectedHost(); 14 | assertThat(controlHost.getAddress().getHostAddress()).isEqualTo(expectedAddress); 15 | return this; 16 | } 17 | 18 | public HostAssert host(int hostNumber) { 19 | // TODO at some point this won't work anymore if we have assertions that wait for a node to 20 | // join the cluster, e.g. assertThat(cluster).node(3).comesUp(). 21 | Host host = TestUtils.findHost(actual, hostNumber); 22 | 23 | return new HostAssert(host, actual); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/policies/ChainableLoadBalancingPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.policies; 17 | 18 | /** 19 | * A load balancing policy that wraps another policy. 20 | */ 21 | public interface ChainableLoadBalancingPolicy extends LoadBalancingPolicy { 22 | /** 23 | * Returns the child policy. 24 | * 25 | * @return the child policy. 26 | */ 27 | LoadBalancingPolicy getChildPolicy(); 28 | } 29 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/FrozenKey.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.*; 19 | 20 | /** 21 | * Shorthand to specify that the key type of a MAP field is frozen. 22 | *

23 | * This is equivalent to {@code @Frozen("map, bar>")}. 24 | * 25 | * @see Frozen 26 | */ 27 | @Target(ElementType.FIELD) 28 | @Retention(RetentionPolicy.RUNTIME) 29 | public @interface FrozenKey { 30 | } 31 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/SystemProperties.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.core; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | /** 7 | * Allows overriding internal settings via system properties. 8 | *

9 | * Warning: this is meant for integration tests only, NOT FOR PRODUCTION USE. 10 | */ 11 | class SystemProperties { 12 | private static final Logger logger = LoggerFactory.getLogger(SystemProperties.class); 13 | 14 | static int getInt(String key, int defaultValue) { 15 | String stringValue = System.getProperty(key); 16 | if (stringValue == null) { 17 | logger.debug("{} is undefined, using default value {}", key, defaultValue); 18 | return defaultValue; 19 | } 20 | try { 21 | int value = Integer.parseInt(stringValue); 22 | logger.warn("{} is defined, using value {}", key, value); 23 | return value; 24 | } catch (NumberFormatException e) { 25 | logger.warn("{} is defined but could not parse value {}, using default value {}", key, stringValue, defaultValue); 26 | return defaultValue; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/EnumType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping; 17 | 18 | /** 19 | * The types of way to persist a JAVA Enum. 20 | */ 21 | public enum EnumType { 22 | /** 23 | * Persists enumeration values using their ordinal in the Enum declaration. 24 | *

25 | * Note that this relies on the order of the values in source code, and will change 26 | * if values are added/removed before existing ones. 27 | */ 28 | ORDINAL, 29 | /** Persists enumeration values using the string they have been declared with. */ 30 | STRING 31 | } 32 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidTypeException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | public class InvalidTypeException extends DriverException { 19 | 20 | private static final long serialVersionUID = 0; 21 | 22 | public InvalidTypeException(String msg) { 23 | super(msg); 24 | } 25 | 26 | public InvalidTypeException(String msg, Throwable cause) { 27 | super(msg, cause); 28 | } 29 | 30 | @Override 31 | public DriverException copy() { 32 | return new InvalidTypeException(getMessage(), this); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/SyntaxError.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | /** 19 | * Indicates a syntax error in a query. 20 | */ 21 | public class SyntaxError extends QueryValidationException { 22 | 23 | private static final long serialVersionUID = 0; 24 | 25 | public SyntaxError(String msg) { 26 | super(msg); 27 | } 28 | 29 | private SyntaxError(String msg, Throwable cause) { 30 | super(msg, cause); 31 | } 32 | 33 | @Override 34 | public DriverException copy() { 35 | return new SyntaxError(getMessage(), this); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryValidationException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | /** 19 | * An exception indicating that a query cannot be executed because it is 20 | * syntactically incorrect, invalid, unauthorized or any other reason. 21 | */ 22 | @SuppressWarnings("serial") 23 | public abstract class QueryValidationException extends DriverException { 24 | 25 | protected QueryValidationException(String msg) { 26 | super(msg); 27 | } 28 | 29 | protected QueryValidationException(String msg, Throwable cause) { 30 | super(msg, cause); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/TruncateException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | /** 19 | * Error during a truncation operation. 20 | */ 21 | public class TruncateException extends QueryExecutionException { 22 | 23 | private static final long serialVersionUID = 0; 24 | 25 | public TruncateException(String msg) { 26 | super(msg); 27 | } 28 | 29 | private TruncateException(String msg, Throwable cause) { 30 | super(msg, cause); 31 | } 32 | 33 | @Override 34 | public DriverException copy() { 35 | return new TruncateException(getMessage(), this); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/FrozenValue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.*; 19 | 20 | /** 21 | * Shorthand to specify that the value type of a collection field is frozen. 22 | *

23 | * This is equivalent to any of the following: 24 | *

29 | * 30 | * @see Frozen 31 | */ 32 | @Target(ElementType.FIELD) 33 | @Retention(RetentionPolicy.RUNTIME) 34 | public @interface FrozenValue { 35 | } 36 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/ServerSideTimestampGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | /** 19 | * A timestamp generator that always returns {@link Long#MIN_VALUE}, in order to let Cassandra 20 | * assign server-side timestamps. 21 | */ 22 | public class ServerSideTimestampGenerator implements TimestampGenerator { 23 | /** 24 | * The unique instance of this generator. 25 | */ 26 | public static final TimestampGenerator INSTANCE = new ServerSideTimestampGenerator(); 27 | 28 | @Override 29 | public long next() { 30 | return Long.MIN_VALUE; 31 | } 32 | 33 | private ServerSideTimestampGenerator() { 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedFeatureException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | import com.datastax.driver.core.ProtocolVersion; 19 | 20 | /** 21 | * Exception thrown when a feature is not supported by the native protocol 22 | * currently in use. 23 | */ 24 | public class UnsupportedFeatureException extends DriverException { 25 | 26 | private static final long serialVersionUID = 0; 27 | 28 | public UnsupportedFeatureException(ProtocolVersion currentVersion, String msg) { 29 | super("Unsupported feature with the native protocol " + currentVersion + " (which is currently in use): " + msg); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryExecutionException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | /** 19 | * Exception related to the execution of a query. 20 | * 21 | * This correspond to the exception that Cassandra throw when a (valid) query 22 | * cannot be executed (TimeoutException, UnavailableException, ...). 23 | */ 24 | @SuppressWarnings("serial") 25 | public abstract class QueryExecutionException extends DriverException { 26 | 27 | protected QueryExecutionException(String msg) { 28 | super(msg); 29 | } 30 | 31 | protected QueryExecutionException(String msg, Throwable cause) { 32 | super(msg, cause); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/TransportException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.net.InetSocketAddress; 19 | 20 | /** 21 | * A connection exception that has to do with the transport itself, i.e. that 22 | * suggests the node is down. 23 | */ 24 | class TransportException extends ConnectionException 25 | { 26 | private static final long serialVersionUID = 0; 27 | 28 | public TransportException(InetSocketAddress address, String msg, Throwable cause) 29 | { 30 | super(address, msg, cause); 31 | } 32 | 33 | public TransportException(InetSocketAddress address, String msg) 34 | { 35 | super(address, msg); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidQueryException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | /** 19 | * Indicates a syntactically correct but invalid query. 20 | */ 21 | public class InvalidQueryException extends QueryValidationException { 22 | 23 | private static final long serialVersionUID = 0; 24 | 25 | public InvalidQueryException(String msg) { 26 | super(msg); 27 | } 28 | 29 | private InvalidQueryException(String msg, Throwable cause) { 30 | super(msg, cause); 31 | } 32 | 33 | @Override 34 | public DriverException copy() { 35 | return new InvalidQueryException(getMessage(), this); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/TimestampGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | /** 19 | * Generates client-side, microsecond-precision query timestamps. 20 | *

21 | * Given that Cassandra uses those timestamps to resolve conflicts, implementations should generate 22 | * incrementing timestamps for successive implementations. 23 | */ 24 | public interface TimestampGenerator { 25 | /** 26 | * Returns the next timestamp. 27 | * 28 | * @return the next timestamp (in microseconds). If it equals {@link Long#MIN_VALUE}, it won't be 29 | * sent by the driver, letting Cassandra generate a server-side timestamp. 30 | */ 31 | long next(); 32 | } 33 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidConfigurationInQueryException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | /** 19 | * A specific invalid query exception that indicates that the query is invalid 20 | * because of some configuration problem. 21 | *

22 | * This is generally throw by query that manipulate the schema (CREATE and 23 | * ALTER) when the required configuration options are invalid. 24 | */ 25 | public class InvalidConfigurationInQueryException extends InvalidQueryException { 26 | 27 | private static final long serialVersionUID = 0; 28 | 29 | public InvalidConfigurationInQueryException(String msg) { 30 | super(msg); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Accessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * An accessor is an interface that defines a set of method to read and write 25 | * from Cassandra. 26 | *

27 | * Each method declaration of an interface with the annotation {@link Accessor} must 28 | * have a {@link Query} annotation that defines the query the method executes. 29 | */ 30 | @Target(ElementType.TYPE) 31 | @Retention(RetentionPolicy.RUNTIME) 32 | public @interface Accessor {} 33 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Param.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * Provides a name for a parameter of a method in an {@link Accessor} interface that 25 | * can be used to reference to that parameter in method {@link Query}. 26 | */ 27 | @Target(ElementType.PARAMETER) 28 | @Retention(RetentionPolicy.RUNTIME) 29 | public @interface Param { 30 | /** 31 | * The name for the parameter 32 | * 33 | * @return the name of the parameter. 34 | */ 35 | String value(); 36 | } 37 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/querybuilder/Ordering.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.querybuilder; 17 | 18 | import java.nio.ByteBuffer; 19 | import java.util.List; 20 | 21 | public class Ordering extends Utils.Appendeable { 22 | 23 | private final String name; 24 | private final boolean isDesc; 25 | 26 | Ordering(String name, boolean isDesc) { 27 | this.name = name; 28 | this.isDesc = isDesc; 29 | } 30 | 31 | @Override 32 | void appendTo(StringBuilder sb, List variables) { 33 | Utils.appendName(name, sb); 34 | sb.append(isDesc ? " DESC" : " ASC"); 35 | } 36 | 37 | @Override 38 | boolean containsBindMarker() { 39 | return false; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/UnauthorizedException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | /** 19 | * Indicates that a query cannot be performed due to the authorization 20 | * restrictions of the logged user. 21 | */ 22 | public class UnauthorizedException extends QueryValidationException { 23 | 24 | private static final long serialVersionUID = 0; 25 | 26 | public UnauthorizedException(String msg) { 27 | super(msg); 28 | } 29 | 30 | private UnauthorizedException(String msg, Throwable cause) { 31 | super(msg, cause); 32 | } 33 | 34 | @Override 35 | public DriverException copy() { 36 | return new UnauthorizedException(getMessage(), this); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/TraceRetrievalException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | /** 19 | * Exception thrown if a query trace cannot be retrieved. 20 | * 21 | * @see com.datastax.driver.core.QueryTrace 22 | */ 23 | public class TraceRetrievalException extends DriverException { 24 | 25 | private static final long serialVersionUID = 0; 26 | 27 | public TraceRetrievalException(String message) { 28 | super(message); 29 | } 30 | 31 | public TraceRetrievalException(String message, Throwable cause) { 32 | super(message, cause); 33 | } 34 | 35 | @Override 36 | public DriverException copy() { 37 | return new TraceRetrievalException(getMessage(), this); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/policies/CloseableLoadBalancingPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.policies; 17 | 18 | /** 19 | * A load balancing policy that wants to be notified at cluster shutdown. 20 | * 21 | * The only reason that this is separate from {@link LoadBalancingPolicy} is to avoid breaking binary compatibility at the 22 | * time this was introduced (2.0.7 / 2.1.3). It might be merged with the parent interface in a future major version. 23 | */ 24 | public interface CloseableLoadBalancingPolicy extends LoadBalancingPolicy { 25 | /** 26 | * Gets invoked at cluster shutdown. 27 | * 28 | * This gives the policy the opportunity to perform some cleanup, for instance stop threads that it might have started. 29 | */ 30 | void close(); 31 | } 32 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Transient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * Whenever this annotation is added on a field, the field will not be mapped 25 | * to any column (neither during reads nor writes). 26 | *

27 | * Please note that it is thus illegal to have a field that has both the 28 | * {@code Transcient} annotation and one of the {@link Column}, {@link PartitionKey} 29 | * or {@link ClusteringColumn} annotation. 30 | */ 31 | @Target(ElementType.FIELD) 32 | @Retention(RetentionPolicy.RUNTIME) 33 | public @interface Transient { 34 | } 35 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/ConnectionException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.net.InetSocketAddress; 19 | 20 | class ConnectionException extends Exception { 21 | 22 | private static final long serialVersionUID = 0; 23 | 24 | public final InetSocketAddress address; 25 | 26 | public ConnectionException(InetSocketAddress address, String msg, Throwable cause) 27 | { 28 | super(msg, cause); 29 | this.address = address; 30 | } 31 | 32 | public ConnectionException(InetSocketAddress address, String msg) 33 | { 34 | super(msg); 35 | this.address = address; 36 | } 37 | 38 | @Override 39 | public String getMessage() { 40 | return String.format("[%s] %s", address, super.getMessage()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/SimpleJSONParserTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import com.google.common.collect.ImmutableMap; 19 | import com.google.common.collect.ImmutableList; 20 | 21 | import org.testng.annotations.Test; 22 | import static org.testng.Assert.assertEquals; 23 | 24 | public class SimpleJSONParserTest { 25 | 26 | @Test(groups = "unit") 27 | public void SimpleParsingTest() throws Exception { 28 | 29 | assertEquals(ImmutableList.of("1", "2", "3"), SimpleJSONParser.parseStringList("[\"1\",\"2\",\"3\"]")); 30 | assertEquals(ImmutableList.of("foo ' bar \""), SimpleJSONParser.parseStringList("[\"foo ' bar \\\"\"]")); 31 | 32 | assertEquals(ImmutableMap.of("foo", "bar", "bar", "foo"), SimpleJSONParser.parseStringMap("{\"foo\":\"bar\",\"bar\":\"foo\"}")); 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/policies/IdentityTranslater.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.policies; 17 | 18 | import java.net.InetSocketAddress; 19 | 20 | /** 21 | * The default {@link AddressTranslater} used by the driver that do no 22 | * translation. 23 | */ 24 | public class IdentityTranslater implements AddressTranslater { 25 | 26 | /** 27 | * Translates a Cassandra {@code rpc_address} to another address if necessary. 28 | *

29 | * This method is the identity function, it always return the address passed 30 | * in argument, doing no translation. 31 | * 32 | * @param address the address of a node as returned by Cassandra. 33 | * @return {@code address} unmodified. 34 | */ 35 | public InetSocketAddress translate(InetSocketAddress address) { 36 | return address; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/ExceptionCatchingRunnable.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import org.slf4j.Logger; 19 | import org.slf4j.LoggerFactory; 20 | 21 | // Simple utility class to make sure we don't let exception slip away and kill 22 | // our executors. 23 | abstract class ExceptionCatchingRunnable implements Runnable { 24 | 25 | private static final Logger logger = LoggerFactory.getLogger(ExceptionCatchingRunnable.class); 26 | 27 | public abstract void runMayThrow() throws Exception; 28 | 29 | @Override 30 | public void run() { 31 | try { 32 | runMayThrow(); 33 | } catch (InterruptedException e) { 34 | Thread.currentThread().interrupt(); 35 | } catch (Exception e) { 36 | logger.error("Unexpected error while executing task", e); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverInternalError.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | /** 19 | * An unexpected error happened internally. 20 | * 21 | * This should never be raise and indicates a bug (either in the driver or in 22 | * Cassandra). 23 | */ 24 | public class DriverInternalError extends DriverException { 25 | 26 | private static final long serialVersionUID = 0; 27 | 28 | public DriverInternalError(String message) { 29 | super(message); 30 | } 31 | 32 | public DriverInternalError(Throwable cause) { 33 | super(cause); 34 | } 35 | 36 | public DriverInternalError(String message, Throwable cause) { 37 | super(message, cause); 38 | } 39 | 40 | @Override 41 | public DriverException copy() { 42 | return new DriverInternalError(getMessage(), this); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/ClusteringColumn.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * Annotation for fields that map to a CQL clustering column. 25 | *

26 | * If the mapped table has multiple clustering columns, it is mandatory 27 | * to specify the ordinal parameter to avoid ordering ambiguity. 28 | */ 29 | @Target(ElementType.FIELD) 30 | @Retention(RetentionPolicy.RUNTIME) 31 | public @interface ClusteringColumn { 32 | /** 33 | * Ordinal to add when several clustering columns are declared within a single 34 | * entity. 35 | * 36 | * @return the ordinal value. 37 | */ 38 | int value() default 0; 39 | } 40 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/PartitionKey.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * Annotation for fields that map to a CQL partition key (or one of it's 25 | * component if the partition key is composite). 26 | *

27 | * If the partition key of the mapped table is composite, it is mandatory 28 | * to specify the ordinal parameter to avoid ordering ambiguity. 29 | */ 30 | @Target(ElementType.FIELD) 31 | @Retention(RetentionPolicy.RUNTIME) 32 | public @interface PartitionKey { 33 | /** 34 | * Ordinal to add when the partition key has multiple components. 35 | * 36 | * @return the ordinal to use. 37 | */ 38 | int value() default 0; 39 | } 40 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Enumerated.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | import com.datastax.driver.mapping.EnumType; 24 | 25 | /** 26 | * Defines that the annotated field (that must be a Java Enum) must be 27 | * persisted as an enumerated type. 28 | *

29 | * The optional {@link EnumType} value defined how the enumeration must be 30 | * persisted. 31 | */ 32 | @Target(ElementType.FIELD) 33 | @Retention(RetentionPolicy.RUNTIME) 34 | public @interface Enumerated { 35 | /** 36 | * How the enumeration must be persisted. 37 | * 38 | * @return the {@link EnumType} to use for mapping this enumeration. 39 | */ 40 | EnumType value() default EnumType.STRING; 41 | } 42 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/policies/CloseableLoadBalancingPolicyTest.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.core.policies; 2 | 3 | import org.testng.annotations.Test; 4 | 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | 7 | import com.datastax.driver.core.CCMBridge; 8 | import com.datastax.driver.core.Cluster; 9 | 10 | public class CloseableLoadBalancingPolicyTest { 11 | @Test(groups = "short") 12 | public void should_be_invoked_at_shutdown() { 13 | CloseMonitoringPolicy policy = new CloseMonitoringPolicy(Policies.defaultLoadBalancingPolicy()); 14 | CCMBridge ccm = null; 15 | Cluster cluster = null; 16 | try { 17 | ccm = CCMBridge.create("test", 1); 18 | cluster = Cluster.builder() 19 | .addContactPoint(CCMBridge.ipOfNode(1)) 20 | .withLoadBalancingPolicy(policy) 21 | .build(); 22 | cluster.connect(); 23 | } finally { 24 | if (cluster != null) 25 | cluster.close(); 26 | if (ccm != null) 27 | ccm.remove(); 28 | } 29 | assertThat(policy.wasClosed).isTrue(); 30 | } 31 | 32 | static class CloseMonitoringPolicy extends DelegatingLoadBalancingPolicy { 33 | 34 | volatile boolean wasClosed = false; 35 | 36 | public CloseMonitoringPolicy(LoadBalancingPolicy delegate) { 37 | super(delegate); 38 | } 39 | 40 | @Override 41 | public void close() { 42 | wasClosed = true; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping; 17 | 18 | import java.lang.reflect.ParameterizedType; 19 | import java.lang.reflect.Type; 20 | 21 | /** 22 | * Utility methods related to reflection. 23 | */ 24 | class ReflectionUtils { 25 | 26 | /** 27 | * Gets a type argument from a parameterized type. 28 | * 29 | * @param pt the parameterized type. 30 | * @param arg the index of the argument to retrieve. 31 | * @param name the name of the element (field or method argument). 32 | * @return the type argument. 33 | */ 34 | static Class getParam(ParameterizedType pt, int arg, String name) { 35 | Type ft = pt.getActualTypeArguments()[arg]; 36 | if (!(ft instanceof Class)) 37 | throw new IllegalArgumentException(String.format("Cannot map parameter of class %s for %s", pt, name)); 38 | return (Class)ft; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/MetricsOptions.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | /** 19 | * {@link Metrics} options. 20 | */ 21 | public class MetricsOptions { 22 | 23 | private final boolean jmxEnabled; 24 | 25 | /** 26 | * Creates a new {@code MetricsOptions} object with default values. 27 | */ 28 | public MetricsOptions() 29 | { 30 | this(true); 31 | } 32 | 33 | /** 34 | * Creates a new {@code MetricsOptions} object. 35 | * 36 | * @param jmxEnabled whether to enable JMX reporting or not. 37 | */ 38 | public MetricsOptions(boolean jmxEnabled) 39 | { 40 | this.jmxEnabled = jmxEnabled; 41 | } 42 | 43 | /** 44 | * Returns whether JMX reporting is enabled (the default). 45 | * 46 | * @return whether JMX reporting is enabled. 47 | */ 48 | public boolean isJMXReportingEnabled() 49 | { 50 | return jmxEnabled; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/PreparedId.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | /** 19 | * Identifies a PreparedStatement. 20 | */ 21 | public class PreparedId 22 | { 23 | // This class is mostly here to group PreparedStatement data that are need for 24 | // execution but that we don't want to expose publicly (see JAVA-195) 25 | final MD5Digest id; 26 | 27 | final ColumnDefinitions metadata; 28 | final ColumnDefinitions resultSetMetadata; 29 | 30 | final int[] routingKeyIndexes; 31 | final ProtocolVersion protocolVersion; 32 | 33 | PreparedId(MD5Digest id, ColumnDefinitions metadata, ColumnDefinitions resultSetMetadata, int[] routingKeyIndexes, ProtocolVersion protocolVersion) 34 | { 35 | this.id = id; 36 | this.metadata = metadata; 37 | this.resultSetMetadata = resultSetMetadata; 38 | this.routingKeyIndexes = routingKeyIndexes; 39 | this.protocolVersion = protocolVersion; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/schemabuilder/ColumnType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.schemabuilder; 17 | 18 | import com.datastax.driver.core.DataType; 19 | 20 | /** 21 | * Wrapper around UDT and non-UDT types. 22 | *

23 | * The reason for this interface is that the core API doesn't let us build {@link com.datastax.driver.core.DataType}s representing UDTs, we have to obtain 24 | * them from the cluster metadata. Since we want to use SchemaBuilder without a Cluster instance, UDT types will be provided via 25 | * {@link UDTType} instances. 26 | */ 27 | interface ColumnType { 28 | String asCQLString(); 29 | 30 | class NativeColumnType implements ColumnType { 31 | private final String asCQLString; 32 | 33 | NativeColumnType(DataType nativeType) { 34 | asCQLString = nativeType.toString(); 35 | } 36 | 37 | @Override public String asCQLString() { 38 | return asCQLString; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/querybuilder/BindMarker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.querybuilder; 17 | 18 | /** 19 | * A CQL3 bind marker. 20 | *

21 | * This can be either an anonymous bind marker or a named one (but note that 22 | * named ones are only supported starting in Cassandra 2.0.1). 23 | *

24 | * Please note that to create a new bind maker object you should use 25 | * {@link QueryBuilder#bindMarker()} (anonymous marker) or 26 | * {@link QueryBuilder#bindMarker(String)} (named marker). 27 | */ 28 | public class BindMarker { 29 | static final BindMarker ANONYMOUS = new BindMarker(null); 30 | 31 | private final String name; 32 | 33 | BindMarker(String name) { 34 | this.name = name; 35 | } 36 | 37 | @Override 38 | public String toString() { 39 | if (name == null) 40 | return "?"; 41 | 42 | return Utils.appendName(name, new StringBuilder(name.length() + 1).append(':')).toString(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /driver-dist/src/assembly/binary-tarball.xml: -------------------------------------------------------------------------------- 1 | 3 | binary-tarball 4 | 5 | tar.gz 6 | 7 | 8 | 9 | true 10 | 11 | com.datastax.cassandra:cassandra-driver-core 12 | com.datastax.cassandra:cassandra-driver-dse 13 | com.datastax.cassandra:cassandra-driver-mapping 14 | 15 | 16 | / 17 | false 18 | 19 | 20 | lib 21 | 22 | com.datastax.cassandra:* 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | target/apidocs 32 | apidocs 33 | 34 | 35 | ../driver-core 36 | 37 | CHANGELOG.rst 38 | Upgrade_guide*.rst 39 | 40 | / 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorTest.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.mapping; 2 | 3 | import java.util.Collection; 4 | 5 | import com.google.common.collect.Lists; 6 | import org.testng.annotations.Test; 7 | 8 | import static org.assertj.core.api.Assertions.assertThat; 9 | 10 | import com.datastax.driver.core.CCMBridge; 11 | import com.datastax.driver.core.ResultSet; 12 | import com.datastax.driver.mapping.annotations.Accessor; 13 | import com.datastax.driver.mapping.annotations.Query; 14 | 15 | public class MapperAccessorTest extends CCMBridge.PerClassSingleNodeCluster { 16 | 17 | @Override protected Collection getTableDefinitions() { 18 | return Lists.newArrayList("CREATE TABLE foo (i int primary key)"); 19 | } 20 | 21 | @Test(groups = "short") 22 | public void should_implement_toString() { 23 | SystemAccessor accessor = new MappingManager(session) 24 | .createAccessor(SystemAccessor.class); 25 | 26 | assertThat(accessor.toString()) 27 | .isEqualTo("SystemAccessor implementation generated by the Cassandra driver mapper"); 28 | } 29 | 30 | @Test(groups = "short") 31 | public void should_implement_equals_and_hashCode() { 32 | SystemAccessor accessor = new MappingManager(session) 33 | .createAccessor(SystemAccessor.class); 34 | 35 | assertThat(accessor).isNotEqualTo(new Object()); 36 | assertThat(accessor.hashCode()).isEqualTo(System.identityHashCode(accessor)); 37 | } 38 | 39 | @Accessor 40 | public interface SystemAccessor { 41 | @Query("select release_version from system.local") 42 | ResultSet getCassandraVersion(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/UnsupportedProtocolVersionException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.net.InetSocketAddress; 19 | 20 | /** 21 | * Indicates that we've attempted to connect to a 1.2 C* node with version 2 of 22 | * the protocol. 23 | */ 24 | class UnsupportedProtocolVersionException extends Exception { 25 | 26 | private static final long serialVersionUID = 0; 27 | 28 | public final InetSocketAddress address; 29 | public final ProtocolVersion unsupportedVersion; 30 | public final ProtocolVersion serverVersion; 31 | 32 | public UnsupportedProtocolVersionException(InetSocketAddress address, ProtocolVersion unsupportedVersion, ProtocolVersion serverVersion) 33 | { 34 | super(String.format("[%s] Host %s does not support protocol version %s but %s", address, address, unsupportedVersion, serverVersion)); 35 | this.address = address; 36 | this.unsupportedVersion = unsupportedVersion; 37 | this.serverVersion = serverVersion; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/querybuilder/Truncate.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.querybuilder; 17 | 18 | import java.nio.ByteBuffer; 19 | import java.util.List; 20 | 21 | import com.datastax.driver.core.TableMetadata; 22 | 23 | /** 24 | * A built TRUNCATE statement. 25 | */ 26 | public class Truncate extends BuiltStatement { 27 | 28 | private final String table; 29 | 30 | Truncate(String keyspace, String table) { 31 | super(keyspace); 32 | this.table = table; 33 | } 34 | 35 | Truncate(TableMetadata table) { 36 | super(table); 37 | this.table = escapeId(table.getName()); 38 | } 39 | 40 | @Override 41 | protected StringBuilder buildQueryString(List variables) { 42 | StringBuilder builder = new StringBuilder(); 43 | 44 | builder.append("TRUNCATE "); 45 | if (keyspace != null) 46 | Utils.appendName(keyspace, builder).append('.'); 47 | Utils.appendName(table, builder); 48 | 49 | return builder; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Query.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * Defines the CQL query that an {@link Accessor} method must implement. 25 | */ 26 | @Target(ElementType.METHOD) 27 | @Retention(RetentionPolicy.RUNTIME) 28 | public @interface Query { 29 | /** 30 | * The CQL query to use. 31 | *

32 | * In that query string, the parameter of the annotated method can be referenced using 33 | * name bind markers. For instance, the first parameter can be refered by {@code :arg0}, 34 | * the second one by {@code :arg1}, ... Alternatively, if a parameter of the annonated 35 | * method has a {@link Param} annotation, the value of that latter annoation should be 36 | * used instead. 37 | * 38 | * @return the CQL query to use. 39 | */ 40 | String value(); 41 | } 42 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/ClusterNameMismatchException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.net.InetSocketAddress; 19 | 20 | /** 21 | * 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. 22 | */ 23 | class ClusterNameMismatchException extends Exception { 24 | 25 | private static final long serialVersionUID = 0; 26 | 27 | public final InetSocketAddress address; 28 | public final String expectedClusterName; 29 | public final String actualClusterName; 30 | 31 | public ClusterNameMismatchException(InetSocketAddress address, String actualClusterName, String expectedClusterName) { 32 | super(String.format("[%s] Host %s reports cluster name '%s' that doesn't match our cluster name '%s'. This host will be ignored.", 33 | address, address, actualClusterName, expectedClusterName)); 34 | this.address = address; 35 | this.expectedClusterName = expectedClusterName; 36 | this.actualClusterName = actualClusterName; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/policies/AlwaysIgnoreRetryPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.policies; 17 | 18 | import com.datastax.driver.core.ConsistencyLevel; 19 | import com.datastax.driver.core.Statement; 20 | import com.datastax.driver.core.WriteType; 21 | 22 | public class AlwaysIgnoreRetryPolicy implements RetryPolicy { 23 | 24 | public static final AlwaysIgnoreRetryPolicy INSTANCE = new AlwaysIgnoreRetryPolicy(); 25 | 26 | private AlwaysIgnoreRetryPolicy() {} 27 | 28 | public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { 29 | return RetryDecision.ignore(); 30 | } 31 | 32 | public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { 33 | return RetryDecision.ignore(); 34 | } 35 | 36 | public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { 37 | return RetryDecision.ignore(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/policies/AlwaysRetryRetryPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.policies; 17 | 18 | import com.datastax.driver.core.ConsistencyLevel; 19 | import com.datastax.driver.core.Statement; 20 | import com.datastax.driver.core.WriteType; 21 | 22 | public class AlwaysRetryRetryPolicy implements RetryPolicy { 23 | 24 | public static final AlwaysRetryRetryPolicy INSTANCE = new AlwaysRetryRetryPolicy(); 25 | 26 | private AlwaysRetryRetryPolicy() {} 27 | 28 | public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { 29 | return RetryDecision.retry(ConsistencyLevel.ONE); 30 | } 31 | 32 | public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { 33 | return RetryDecision.retry(ConsistencyLevel.ONE); 34 | } 35 | 36 | public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { 37 | return RetryDecision.retry(ConsistencyLevel.ONE); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateIndexTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.schemabuilder; 17 | 18 | import org.testng.annotations.Test; 19 | 20 | import static org.assertj.core.api.Assertions.assertThat; 21 | 22 | import static com.datastax.driver.core.schemabuilder.SchemaBuilder.createIndex; 23 | 24 | public class CreateIndexTest { 25 | 26 | @Test(groups = "unit") 27 | public void should_create_index() throws Exception { 28 | //Given //When 29 | SchemaStatement statement = createIndex("myIndex").ifNotExists().onTable("ks", "test").andColumn("col"); 30 | 31 | //Then 32 | assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE INDEX IF NOT EXISTS myIndex ON ks.test(col)"); 33 | } 34 | 35 | @Test(groups = "unit") 36 | public void should_create_index_on_keys_of_map_column() throws Exception { 37 | //Given //When 38 | SchemaStatement statement = createIndex("myIndex").ifNotExists().onTable("ks", "test").andKeysOfColumn("col"); 39 | 40 | //Then 41 | assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE INDEX IF NOT EXISTS myIndex ON ks.test(KEYS(col))"); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/TokenMapTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.nio.ByteBuffer; 19 | import java.util.Set; 20 | 21 | import org.testng.annotations.*; 22 | 23 | import static org.testng.Assert.assertFalse; 24 | 25 | import com.datastax.driver.core.CCMBridge.CCMCluster; 26 | 27 | /** 28 | * Tests that the token map is correctly initialized at startup (JAVA-415). 29 | */ 30 | public class TokenMapTest { 31 | CCMCluster ccmCluster = null; 32 | Cluster cluster = null; 33 | 34 | @BeforeMethod(groups = "short") 35 | public void setup() { 36 | ccmCluster = CCMBridge.buildCluster(1, Cluster.builder()); 37 | cluster = ccmCluster.cluster; 38 | } 39 | 40 | @Test(groups = "short") 41 | public void initTest() { 42 | // If the token map is initialized correctly, we should get replicas for any partition key 43 | ByteBuffer anyKey = ByteBuffer.wrap(new byte[]{}); 44 | Set replicas = cluster.getMetadata().getReplicas("system", anyKey); 45 | assertFalse(replicas.isEmpty()); 46 | } 47 | 48 | @AfterMethod(groups = "short") 49 | public void teardown() { 50 | ccmCluster.discard(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/UDT.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * Defines to which User Defined Type a class must be mapped to. 25 | */ 26 | @Target(ElementType.TYPE) 27 | @Retention(RetentionPolicy.RUNTIME) 28 | public @interface UDT { 29 | /** 30 | * The name of the keyspace the type is part of. 31 | * 32 | * @return the name of the keyspace. 33 | */ 34 | String keyspace() default ""; 35 | /** 36 | * The name of the type. 37 | * 38 | * @return the name of the type. 39 | */ 40 | String name(); 41 | 42 | /** 43 | * Whether the keyspace name is a case sensitive one. 44 | * 45 | * @return whether the keyspace name is a case sensitive one. 46 | */ 47 | boolean caseSensitiveKeyspace() default false; 48 | /** 49 | * Whether the type name is a case sensitive one. 50 | * 51 | * @return whether the type name is a case sensitive one. 52 | */ 53 | boolean caseSensitiveType() default false; 54 | } 55 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/AbstractTimestampGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import org.slf4j.Logger; 19 | import org.slf4j.LoggerFactory; 20 | 21 | /** 22 | * Base implementation for generators based on {@link System#currentTimeMillis()} and a counter to generate 23 | * the sub-millisecond part. 24 | */ 25 | abstract class AbstractMonotonicTimestampGenerator implements TimestampGenerator { 26 | private static final Logger logger = LoggerFactory.getLogger(AbstractMonotonicTimestampGenerator.class); 27 | 28 | volatile Clock clock = new SystemClock(); 29 | 30 | protected long computeNext(long last) { 31 | long millis = last / 1000; 32 | long counter = last % 1000; 33 | 34 | long now = clock.currentTime(); 35 | 36 | // System.currentTimeMillis can go backwards on an NTP resync, hence the ">" below 37 | if (millis >= now) { 38 | if (counter == 999) 39 | logger.warn("Sub-millisecond counter overflowed, some query timestamps will not be distinct"); 40 | else 41 | counter += 1; 42 | } else { 43 | millis = now; 44 | counter = 0; 45 | } 46 | 47 | return millis * 1000 + counter; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/HostDistance.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | /** 19 | * The distance to a Cassandra node as assigned by a 20 | * {@link com.datastax.driver.core.policies.LoadBalancingPolicy} (through its {@code 21 | * distance} method). 22 | * 23 | * The distance assigned to an host influences how many connections the driver 24 | * maintains towards this host. If for a given host the assigned {@code HostDistance} 25 | * is {@code LOCAL} or {@code REMOTE}, some connections will be maintained by 26 | * the driver to this host. More active connections will be kept to 27 | * {@code LOCAL} host than to a {@code REMOTE} one (and thus well behaving 28 | * {@code LoadBalancingPolicy} should assign a {@code REMOTE} distance only to 29 | * hosts that are the less often queried). 30 | *

31 | * However, if a host is assigned the distance {@code IGNORED}, no connection 32 | * to that host will maintained active. In other words, {@code IGNORED} should 33 | * be assigned to hosts that should not be used by this driver (because they 34 | * are in a remote data center for instance). 35 | */ 36 | public enum HostDistance { 37 | // Note: PoolingOptions rely on the order of the enum. 38 | LOCAL, 39 | REMOTE, 40 | IGNORED 41 | } 42 | -------------------------------------------------------------------------------- /testing/README.md: -------------------------------------------------------------------------------- 1 | ## Testing Prerequisites 2 | 3 | ### Install CCM 4 | 5 | pip install ccm 6 | 7 | ### Setup CCM Loopbacks (required for OSX) 8 | 9 | # For basic ccm 10 | sudo ifconfig lo0 alias 127.0.0.2 up 11 | sudo ifconfig lo0 alias 127.0.0.3 up 12 | 13 | # Additional loopbacks for java-driver testing 14 | sudo ifconfig lo0 alias 127.0.1.1 up 15 | sudo ifconfig lo0 alias 127.0.1.2 up 16 | sudo ifconfig lo0 alias 127.0.1.3 up 17 | sudo ifconfig lo0 alias 127.0.1.4 up 18 | sudo ifconfig lo0 alias 127.0.1.5 up 19 | sudo ifconfig lo0 alias 127.0.1.6 up 20 | 21 | 22 | 23 | ## Building the Driver 24 | 25 | mvn clean package 26 | 27 | 28 | 29 | ## Testing the Driver 30 | 31 | ### Unit Tests 32 | 33 | Use the following command to run only the unit tests: 34 | 35 | mvn test 36 | 37 | _**Estimated Run Time**: x minutes_ 38 | 39 | ### Integration Tests 40 | 41 | The following command runs the full set of unit and integration tests: 42 | 43 | mvn verify 44 | 45 | _**Estimated Run Time**: 4 minutes_ 46 | 47 | ### Coverage Report 48 | 49 | The following command runs the full set of integration tests and produces a 50 | coverage report: 51 | 52 | mvn cobertura:cobertura 53 | 54 | Coverage report can be found at: 55 | 56 | driver-core/target/site/cobertura/index.html 57 | 58 | _**Estimated Run Time**: 4 minutes_ 59 | 60 | 61 | 62 | ## Test Utility 63 | 64 | `testing/bin/coverage` exists to make testing a bit more straight-forward. 65 | 66 | The main commands are as follows: 67 | 68 | Displays the available parameters: 69 | 70 | testing/bin/coverage --help 71 | 72 | Runs all the integration tests, creates the Cobertura report, and uploads Cobertura 73 | site to a remote machine, if applicable: 74 | 75 | testing/bin/coverage 76 | 77 | Runs a single integration test along with the Cobertura report for that test: 78 | 79 | testing/bin/coverage --test TestClass[#optionalTestMethod] 80 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/StreamIdGeneratorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import org.testng.annotations.Test; 19 | import static org.testng.Assert.assertEquals; 20 | import static org.testng.Assert.fail; 21 | 22 | public class StreamIdGeneratorTest { 23 | 24 | @Test(groups = "unit") 25 | public void SimpleGenIdTest() throws Exception { 26 | 27 | StreamIdGenerator generator = StreamIdGenerator.newInstance(ProtocolVersion.V2); 28 | 29 | assertEquals(generator.next(), 0); 30 | assertEquals(generator.next(), 64); 31 | generator.release(0); 32 | assertEquals(generator.next(), 0); 33 | assertEquals(generator.next(), 65); 34 | assertEquals(generator.next(), 1); 35 | generator.release(64); 36 | assertEquals(generator.next(), 64); 37 | assertEquals(generator.next(), 2); 38 | 39 | for (int i = 5; i < 128; i++) 40 | generator.next(); 41 | 42 | generator.release(100); 43 | assertEquals(generator.next(), 100); 44 | 45 | try { 46 | generator.next(); 47 | fail("No more streamId should be available"); 48 | } catch (BusyConnectionException e) { 49 | // Ok, expected 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/AtomicMonotonicTimestampGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.util.concurrent.atomic.AtomicLong; 19 | 20 | /** 21 | * A timestamp generator based on {@code System.currentTimeMillis()}, with an incrementing atomic counter 22 | * to generate the sub-millisecond part. 23 | *

24 | * This implementation guarantees incrementing timestamps among all client threads, provided that no more than 25 | * 1000 are requested for a given clock tick (the exact granularity of of {@link System#currentTimeMillis()} 26 | * depends on the operating system). 27 | *

28 | * If that rate is exceeded, a warning is logged and the timestamps don't increment anymore until the next clock 29 | * tick. If you consistently exceed that rate, consider using {@link ThreadLocalMonotonicTimestampGenerator}. 30 | */ 31 | public class AtomicMonotonicTimestampGenerator extends AbstractMonotonicTimestampGenerator { 32 | private AtomicLong lastRef = new AtomicLong(0); 33 | 34 | @Override 35 | public long next() { 36 | while (true) { 37 | long last = lastRef.get(); 38 | long next = computeNext(last); 39 | if (lastRef.compareAndSet(last, next)) 40 | return next; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | /** 19 | * Top level class for exceptions thrown by the driver. 20 | */ 21 | public class DriverException extends RuntimeException { 22 | 23 | private static final long serialVersionUID = 0; 24 | 25 | DriverException() { 26 | super(); 27 | } 28 | 29 | public DriverException(String message) { 30 | super(message); 31 | } 32 | 33 | public DriverException(Throwable cause) { 34 | super(cause); 35 | } 36 | 37 | public DriverException(String message, Throwable cause) { 38 | super(message, cause); 39 | } 40 | 41 | /** 42 | * Copy the exception. 43 | *

44 | * This return a new exception, equivalent to the original one, except that 45 | * because a new object is created in the current thread, the top-most 46 | * element in the stacktrace of the exception will refer to the current 47 | * thread (this mainly use for internal use by the driver). The cause of 48 | * the copied exception will be the original exception. 49 | * 50 | * @return a copy/clone of this exception. 51 | */ 52 | public DriverException copy() { 53 | return new DriverException(getMessage(), this); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/MD5Digest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.util.Arrays; 19 | 20 | import com.datastax.driver.core.utils.Bytes; 21 | 22 | /** 23 | * The result of the computation of an MD5 digest. 24 | * 25 | * A MD5 is really just a byte[] but arrays are a no go as map keys. We could 26 | * wrap it in a ByteBuffer but: 27 | * 1. MD5Digest is a more explicit name than ByteBuffer to represent a md5. 28 | * 2. Using our own class allows to use our FastByteComparison for equals. 29 | */ 30 | class MD5Digest { 31 | 32 | public final byte[] bytes; 33 | 34 | private MD5Digest(byte[] bytes) { 35 | this.bytes = bytes; 36 | } 37 | 38 | public static MD5Digest wrap(byte[] digest) { 39 | return new MD5Digest(digest); 40 | } 41 | 42 | @Override 43 | public final int hashCode() { 44 | return Arrays.hashCode(bytes); 45 | } 46 | 47 | @Override 48 | public final boolean equals(Object o) { 49 | if(!(o instanceof MD5Digest)) 50 | return false; 51 | MD5Digest that = (MD5Digest)o; 52 | // handles nulls properly 53 | return Arrays.equals(this.bytes, that.bytes); 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return Bytes.toHexString(bytes); 59 | } 60 | } 61 | 62 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/ThreadLocalMonotonicTimestampGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | 19 | /** 20 | * A timestamp generator based on {@code System.currentTimeMillis()}, with an incrementing thread-local counter 21 | * to generate the sub-millisecond part. 22 | *

23 | * This implementation guarantees incrementing timestamps for a given client thread, provided that no more than 24 | * 1000 are requested for a given clock tick (the exact granularity of of {@link System#currentTimeMillis()} 25 | * depends on the operating system). 26 | *

27 | * If that rate is exceeded, a warning is logged and the timestamps don't increment anymore until the next clock 28 | * tick. 29 | */ 30 | public class ThreadLocalMonotonicTimestampGenerator extends AbstractMonotonicTimestampGenerator { 31 | // We're deliberately avoiding an anonymous subclass with initialValue(), because this can introduce 32 | // classloader leaks in managed environments like Tomcat 33 | private final ThreadLocal lastRef = new ThreadLocal(); 34 | 35 | @Override 36 | public long next() { 37 | Long last = this.lastRef.get(); 38 | if (last == null) 39 | last = 0L; 40 | 41 | long next = computeNext(last); 42 | 43 | this.lastRef.set(next); 44 | return next; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/WriteType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | /** 19 | * The type of a Cassandra write query. 20 | *

21 | * This information is returned by Cassandra when a write timeout is raised to 22 | * indicate what type of write timed out. This information is useful to decide 23 | * which retry policy to adopt. 24 | */ 25 | public enum WriteType 26 | { 27 | /** A write to a single partition key. Such writes are guaranteed to be atomic and isolated. */ 28 | SIMPLE, 29 | /** A write to a multiple partition key that used the distributed batch log to ensure atomicity. */ 30 | BATCH, 31 | /** A write to a multiple partition key that doesn't use the distributed batch log. Atomicity for such writes is not guaranteed */ 32 | UNLOGGED_BATCH, 33 | /** A counter write (that can be for one or multiple partition key). Such write should not be replayed to avoid over-counting. */ 34 | COUNTER, 35 | /** The initial write to the distributed batch log that Cassandra performs internally before a BATCH write. */ 36 | BATCH_LOG, 37 | /** 38 | * A conditional write. If a timeout has this {@code WriteType}, the timeout has happened while doing the compare-and-swap for 39 | * an conditional update. In this case, the update may or may not have been applied. 40 | */ 41 | CAS; 42 | } 43 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/AuthProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.net.InetSocketAddress; 19 | 20 | import com.datastax.driver.core.exceptions.AuthenticationException; 21 | 22 | /** 23 | * Provides {@link Authenticator} instances for use when connecting 24 | * to Cassandra nodes. 25 | * 26 | * See {@link PlainTextAuthProvider} for an implementation which uses SASL 27 | * PLAIN mechanism to authenticate using username/password strings 28 | */ 29 | public interface AuthProvider { 30 | 31 | /** 32 | * A provider that provides no authentication capability. 33 | *

34 | * This is only useful as a placeholder when no authentication is to be used. 35 | */ 36 | public static final AuthProvider NONE = new AuthProvider() { 37 | public Authenticator newAuthenticator(InetSocketAddress host) { 38 | throw new AuthenticationException(host, 39 | String.format("Host %s requires authentication, but no authenticator found in Cluster configuration", host)); 40 | } 41 | }; 42 | 43 | /** 44 | * The {@code Authenticator} to use when connecting to {@code host} 45 | * 46 | * @param host the Cassandra host to connect to. 47 | * @return The authentication implementation to use. 48 | */ 49 | public Authenticator newAuthenticator(InetSocketAddress host) throws AuthenticationException; 50 | } 51 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/policies/DelegatingLoadBalancingPolicy.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.core.policies; 2 | 3 | import java.util.Collection; 4 | import java.util.Iterator; 5 | 6 | import com.datastax.driver.core.Cluster; 7 | import com.datastax.driver.core.Host; 8 | import com.datastax.driver.core.HostDistance; 9 | import com.datastax.driver.core.Statement; 10 | 11 | /** 12 | * Base class for tests that want to wrap a policy to add some instrumentation. 13 | * 14 | * NB: this is currently only used in tests, but could be provided as a convenience in the production code. 15 | */ 16 | public abstract class DelegatingLoadBalancingPolicy implements ChainableLoadBalancingPolicy, CloseableLoadBalancingPolicy { 17 | protected final LoadBalancingPolicy delegate; 18 | 19 | public DelegatingLoadBalancingPolicy(LoadBalancingPolicy delegate) { 20 | this.delegate = delegate; 21 | } 22 | 23 | public void init(Cluster cluster, Collection hosts) { 24 | delegate.init(cluster, hosts); 25 | } 26 | 27 | public HostDistance distance(Host host) { 28 | return delegate.distance(host); 29 | } 30 | 31 | public Iterator newQueryPlan(String loggedKeyspace, Statement statement) { 32 | return delegate.newQueryPlan(loggedKeyspace, statement); 33 | } 34 | 35 | public void onAdd(Host host) { 36 | delegate.onAdd(host); 37 | } 38 | 39 | public void onUp(Host host) { 40 | delegate.onUp(host); 41 | } 42 | 43 | public void onSuspected(Host host) { 44 | delegate.onSuspected(host); 45 | } 46 | 47 | public void onDown(Host host) { 48 | delegate.onDown(host); 49 | } 50 | 51 | public void onRemove(Host host) { 52 | delegate.onRemove(host); 53 | } 54 | 55 | @Override 56 | public LoadBalancingPolicy getChildPolicy() { 57 | return delegate; 58 | } 59 | 60 | @Override 61 | public void close() { 62 | if (delegate instanceof CloseableLoadBalancingPolicy) 63 | ((CloseableLoadBalancingPolicy)delegate).close(); 64 | } 65 | } -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/VersionNumberTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import org.testng.annotations.Test; 19 | import static org.testng.Assert.assertEquals; 20 | 21 | public class VersionNumberTest { 22 | 23 | @Test(groups = "unit") 24 | public void versionNumberTest() { 25 | 26 | String[] versions = new String[] { 27 | "1.2.0", 28 | "2.0.0", 29 | "2.0.0-beta1", 30 | "2.0.0-beta1-SNAPSHOT", 31 | "2.0.0-beta1-SNAPSHOT+abc01", 32 | "2.0.0.22" // DSE 33 | }; 34 | 35 | VersionNumber[] numbers = new VersionNumber[versions.length]; 36 | for (int i = 0; i < versions.length; i++) 37 | numbers[i] = VersionNumber.parse(versions[i]); 38 | 39 | for (int i = 0; i < versions.length; i++) 40 | assertEquals(numbers[i].toString(), versions[i]); 41 | 42 | assertEquals(numbers[0].compareTo(numbers[1]), -1); 43 | assertEquals(numbers[1].compareTo(numbers[2]), 1); 44 | assertEquals(numbers[2].compareTo(numbers[3]), -1); 45 | assertEquals(numbers[3].compareTo(numbers[4]), 0); 46 | assertEquals(numbers[1].compareTo(numbers[5]), -1); 47 | 48 | VersionNumber deb = VersionNumber.parse("2.0.0~beta1"); 49 | assertEquals(deb, numbers[2]); 50 | 51 | VersionNumber shorter = VersionNumber.parse("2.0"); 52 | assertEquals(shorter, numbers[1]); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/LatencyTracker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | /** 19 | * Interface for object that are interested in tracking the latencies 20 | * of the driver queries to each Cassandra nodes. 21 | *

22 | * An implementation of this interface can be registered against a Cluster 23 | * object trough the {@link Cluster#register} method, after which the 24 | * {@code update} will be called after each query of the driver to a Cassandra 25 | * host with the latency/duration (in nanoseconds) of this operation. 26 | */ 27 | public interface LatencyTracker { 28 | 29 | /** 30 | * A method that is called after each request to a Cassandra node with 31 | * the duration of that operation. 32 | *

33 | * Note that there is no guarantee that this method won't be called 34 | * concurrently by multiple thread, so implementations should synchronize 35 | * internally if need be. 36 | * 37 | * @param host the Cassandra host on which a request has been performed. 38 | * @param newLatencyNanos the latency in nanoseconds of the operation. This 39 | * latency corresponds to the time elapsed between when the query was send 40 | * to {@code host} and when the response was received by the driver (or the 41 | * operation timed out, in which {@code newLatencyNanos} will approximately 42 | * be the timeout value). 43 | */ 44 | public void update(Host host, long newLatencyNanos); 45 | } 46 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/querybuilder/Using.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.querybuilder; 17 | 18 | import java.nio.ByteBuffer; 19 | import java.util.List; 20 | 21 | public abstract class Using extends Utils.Appendeable { 22 | 23 | final String optionName; 24 | 25 | private Using(String optionName) { 26 | this.optionName = optionName; 27 | } 28 | 29 | static class WithValue extends Using { 30 | private final long value; 31 | 32 | WithValue(String optionName, long value) { 33 | super(optionName); 34 | this.value = value; 35 | } 36 | 37 | @Override 38 | void appendTo(StringBuilder sb, List variables) { 39 | sb.append(optionName).append(' ').append(value); 40 | } 41 | 42 | @Override 43 | boolean containsBindMarker() { 44 | return false; 45 | } 46 | } 47 | 48 | static class WithMarker extends Using { 49 | private final BindMarker marker; 50 | 51 | WithMarker(String optionName, BindMarker marker) { 52 | super(optionName); 53 | this.marker = marker; 54 | } 55 | 56 | @Override 57 | void appendTo(StringBuilder sb, List variables) { 58 | sb.append(optionName).append(' ').append(marker); 59 | } 60 | 61 | @Override 62 | boolean containsBindMarker() { 63 | return true; 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/QueryParameters.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | import com.datastax.driver.core.Configuration; 24 | 25 | /** 26 | * Query parameters to use in the (generated) implementation of a method of an {@link Accessor} 27 | * interface. 28 | *

29 | * All the parameters of this annotation are optional, and when not provided default to whatever 30 | * default the {@code Cluster} instance used underneath are (those set in 31 | * {@link Configuration#getQueryOptions}). 32 | */ 33 | @Target(ElementType.METHOD) 34 | @Retention(RetentionPolicy.RUNTIME) 35 | public @interface QueryParameters { 36 | /** 37 | * The consistency level to use for the operation. 38 | * 39 | * @return the consistency level to use for the operation. 40 | */ 41 | String consistency() default ""; 42 | 43 | /** 44 | * The fetch size to use for paging the result of this operation. 45 | * 46 | * @return the fetch size to use for the operation. 47 | */ 48 | int fetchSize() default -1; 49 | 50 | /** 51 | * Whether tracing should be enabled for this operation. 52 | * 53 | * @return whether tracing should be enabled for this operation. 54 | */ 55 | boolean tracing() default false; 56 | } 57 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Column.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * Annotation that allows to specify the name of the CQL column to which the 25 | * field should be mapped. 26 | *

27 | * Note that this annotation is generally optional in the sense that any field 28 | * of a class annotated by {@link Table} will be mapped by default to a column 29 | * having the same name than this field unless that field has the 30 | * {@link Transient} annotation. As such, this annotation is mainly useful when 31 | * the name to map the field to is not the same one that the field itself (but 32 | * can be added without it's name parameter for documentation sake). 33 | */ 34 | @Target(ElementType.FIELD) 35 | @Retention(RetentionPolicy.RUNTIME) 36 | public @interface Column { 37 | /** 38 | * Name of the column being mapped in Cassandra. By default, the name of the 39 | * field will be used. 40 | * 41 | * @return the name of the mapped column in Cassandra, or {@code ""} to use 42 | * the field name. 43 | */ 44 | String name() default ""; 45 | 46 | /** 47 | * Whether the column name is a case sensitive one. 48 | * 49 | * @return whether the column name is a case sensitive one. 50 | */ 51 | boolean caseSensitive() default false; 52 | } 53 | -------------------------------------------------------------------------------- /driver-examples/pom.xml: -------------------------------------------------------------------------------- 1 | 14 | 15 | 4.0.0 16 | 17 | com.datastax.cassandra 18 | cassandra-driver-parent 19 | 2.1.4-SNAPSHOT 20 | 21 | cassandra-driver-examples-parent 22 | pom 23 | DataStax Java Driver for Apache Cassandra Examples 24 | A collection of examples to demonstrate DataStax Java Driver for Apache Cassandra. 25 | https://github.com/datastax/java-driver 26 | 27 | 28 | stress 29 | 30 | 31 | 32 | 33 | Apache 2 34 | http://www.apache.org/licenses/LICENSE-2.0.txt 35 | repo 36 | Apache License Version 2.0 37 | 38 | 39 | 40 | 41 | scm:git:git@github.com:datastax/java-driver.git 42 | scm:git:git@github.com:datastax/java-driver.git 43 | https://github.com/datastax/java-driver 44 | HEAD 45 | 46 | 47 | 48 | 49 | Various 50 | DataStax 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/AccessorReflectionMapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping; 17 | 18 | import java.lang.reflect.Proxy; 19 | import java.util.*; 20 | 21 | class AccessorReflectionMapper extends AccessorMapper { 22 | 23 | private static AccessorReflectionFactory factory = new AccessorReflectionFactory(); 24 | 25 | private final Class[] proxyClasses; 26 | private final AccessorInvocationHandler handler; 27 | 28 | @SuppressWarnings({"unchecked", "rawtypes"}) 29 | private AccessorReflectionMapper(Class daoClass, List methods) { 30 | super(daoClass, methods); 31 | this.proxyClasses = (Class[])new Class[]{ daoClass }; 32 | this.handler = new AccessorInvocationHandler(this); 33 | } 34 | 35 | public static Factory factory() { 36 | return factory; 37 | } 38 | 39 | @SuppressWarnings("unchecked") 40 | @Override 41 | public T createProxy() { 42 | try { 43 | return (T) Proxy.newProxyInstance(daoClass.getClassLoader(), proxyClasses, handler); 44 | } catch (Exception e) { 45 | throw new RuntimeException("Cannot create instance for Accessor interface " + daoClass.getName()); 46 | } 47 | } 48 | 49 | private static class AccessorReflectionFactory implements Factory { 50 | public AccessorMapper create(Class daoClass, List methods) { 51 | return new AccessorReflectionMapper(daoClass, methods); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Field.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * Annotation that allows to specify the name of the CQL UDT field to which the 25 | * Java field should be mapped. 26 | *

27 | * Note that this annotation is generally optional in the sense that any field 28 | * of a class annotated by {@link UDT} will be mapped by default to a UDT field 29 | * having the same name than this Java field unless that Java field has the 30 | * {@link Transient} annotation. As such, this annotation is mainly useful when 31 | * the name to map the field to is not the same one that the field itself (but 32 | * can be added without it's name parameter for documentation sake). 33 | */ 34 | @Target(ElementType.FIELD) 35 | @Retention(RetentionPolicy.RUNTIME) 36 | public @interface Field { 37 | /** 38 | * Name of the column being mapped in Cassandra. By default, the name of the 39 | * field will be used. 40 | * 41 | * @return the name of the mapped column in Cassandra, or {@code ""} to use 42 | * the field name. 43 | */ 44 | String name() default ""; 45 | 46 | /** 47 | * Whether the column name is a case sensitive one. 48 | * 49 | * @return whether the column name is a case sensitive one. 50 | */ 51 | boolean caseSensitive() default false; 52 | } 53 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/AccessorMapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping; 17 | 18 | import java.util.*; 19 | 20 | import com.google.common.util.concurrent.Futures; 21 | import com.google.common.util.concurrent.ListenableFuture; 22 | 23 | import com.datastax.driver.core.*; 24 | 25 | abstract class AccessorMapper { 26 | 27 | public final Class daoClass; 28 | protected final List methods; 29 | 30 | protected AccessorMapper(Class daoClass, List methods) { 31 | this.daoClass = daoClass; 32 | this.methods = methods; 33 | } 34 | 35 | abstract T createProxy(); 36 | 37 | public void prepare(MappingManager manager) { 38 | List> statements = new ArrayList>(methods.size()); 39 | 40 | for (MethodMapper method : methods) 41 | statements.add(manager.getSession().prepareAsync(method.queryString)); 42 | 43 | try { 44 | List preparedStatements = Futures.allAsList(statements).get(); 45 | for (int i = 0; i < methods.size(); i++) 46 | methods.get(i).prepare(manager, preparedStatements.get(i)); 47 | } catch (Exception e) { 48 | throw new RuntimeException("Error preparing queries for accessor " + daoClass.getSimpleName(), e); 49 | } 50 | } 51 | 52 | interface Factory { 53 | public AccessorMapper create(Class daoClass, List methods); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Frozen.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | import com.datastax.driver.core.DataType; 24 | 25 | /** 26 | * Specifies that the field decorated with this annotation maps to a CQL type that is {@link DataType#isFrozen() frozen}, 27 | * or contains frozen subtypes. 28 | *

29 | * This annotation is purely informational at this stage, but will become useful when a schema generation feature is 30 | * added to the mapper. 31 | * 32 | * @see FrozenKey 33 | * @see FrozenValue 34 | */ 35 | @Target(ElementType.FIELD) 36 | @Retention(RetentionPolicy.RUNTIME) 37 | public @interface Frozen { 38 | 39 | /** 40 | * Contains the full CQL type of the target column. As a convenience, this can be left out when only the top-level 41 | * type is frozen. 42 | *

43 | * Examples: 44 | *

45 |      * // Will map to frozen<user>
46 |      * @Frozen
47 |      * private User user;
48 |      *
49 |      * @Frozen("map<text, map<text, frozen<user>>>")
50 |      * private Map<String, Map<String, User>> m;
51 |      * 
52 | *

53 | * Also consider the {@link FrozenKey @FrozenKey} and {@link FrozenValue @FrozenValue} shortcuts for simple collections. 54 | * 55 | * @return the full CQL type of the target column. 56 | */ 57 | String value() default ""; 58 | } 59 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/ExceptionCode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.util.HashMap; 19 | import java.util.Map; 20 | 21 | import com.datastax.driver.core.exceptions.DriverInternalError; 22 | 23 | /** 24 | * Exceptions code, as defined by the native protocol. 25 | */ 26 | enum ExceptionCode { 27 | 28 | SERVER_ERROR (0x0000), 29 | PROTOCOL_ERROR (0x000A), 30 | 31 | BAD_CREDENTIALS (0x0100), 32 | 33 | // 1xx: problem during request execution 34 | UNAVAILABLE (0x1000), 35 | OVERLOADED (0x1001), 36 | IS_BOOTSTRAPPING(0x1002), 37 | TRUNCATE_ERROR (0x1003), 38 | WRITE_TIMEOUT (0x1100), 39 | READ_TIMEOUT (0x1200), 40 | 41 | // 2xx: problem validating the request 42 | SYNTAX_ERROR (0x2000), 43 | UNAUTHORIZED (0x2100), 44 | INVALID (0x2200), 45 | CONFIG_ERROR (0x2300), 46 | ALREADY_EXISTS (0x2400), 47 | UNPREPARED (0x2500); 48 | 49 | public final int value; 50 | private static final Map valueToCode = new HashMap(ExceptionCode.values().length); 51 | static { 52 | for (ExceptionCode code : ExceptionCode.values()) 53 | valueToCode.put(code.value, code); 54 | } 55 | 56 | private ExceptionCode(int value) { 57 | this.value = value; 58 | } 59 | 60 | public static ExceptionCode fromValue(int value) { 61 | ExceptionCode code = valueToCode.get(value); 62 | if (code == null) 63 | throw new DriverInternalError(String.format("Unknown error code %d", value)); 64 | return code; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/AuthenticationException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | import java.net.InetAddress; 19 | import java.net.InetSocketAddress; 20 | 21 | /** 22 | * Indicates an error during the authentication phase while connecting to a node. 23 | */ 24 | public class AuthenticationException extends DriverException { 25 | 26 | private static final long serialVersionUID = 0; 27 | 28 | private final InetSocketAddress address; 29 | 30 | public AuthenticationException(InetSocketAddress address, String message) { 31 | super(String.format("Authentication error on host %s: %s", address, message)); 32 | this.address = address; 33 | } 34 | 35 | private AuthenticationException(String message, Throwable cause, InetSocketAddress address) 36 | { 37 | super(message, cause); 38 | this.address = address; 39 | } 40 | 41 | /** 42 | * The host for which the authentication failed. 43 | *

44 | * This is a shortcut for {@code getAddress().getAddress()}. 45 | * 46 | * @return the host for which the authentication failed. 47 | */ 48 | public InetAddress getHost() { 49 | return address.getAddress(); 50 | } 51 | 52 | /** 53 | * The full address of the host for which the authentication failed. 54 | * 55 | * @return the host for which the authentication failed. 56 | */ 57 | public InetSocketAddress getAddress() { 58 | return address; 59 | } 60 | 61 | @Override 62 | public DriverException copy() { 63 | return new AuthenticationException(getMessage(), this, address); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /driver-mapping/src/test/java/com/datastax/driver/mapping/AnnotationChecksTest.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.mapping; 2 | 3 | import java.lang.reflect.Field; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import com.datastax.driver.mapping.annotations.Frozen; 8 | import com.datastax.driver.mapping.annotations.FrozenValue; 9 | import org.testng.annotations.Test; 10 | 11 | import static org.testng.Assert.fail; 12 | 13 | public class AnnotationChecksTest { 14 | // Dummy UDT class: 15 | public class User { 16 | } 17 | 18 | // Dummy fields to run our checks on: 19 | String string; 20 | @Frozen 21 | String frozenString; 22 | List listOfStrings; 23 | User unfrozenUser; 24 | @Frozen 25 | User frozenUser; 26 | List listOfUnfrozenUsers; 27 | @FrozenValue 28 | List listOfFrozenUsers; 29 | Map> deeplyNestedUnfrozenUser; 30 | @Frozen("map>>") 31 | Map> deeplyNestedFrozenUser; 32 | 33 | @Test(groups = "unit") 34 | public void checkFrozenTypesTest() throws Exception { 35 | checkFrozenTypesTest("string", true); 36 | checkFrozenTypesTest("frozenString", false); 37 | checkFrozenTypesTest("listOfStrings", true); 38 | checkFrozenTypesTest("unfrozenUser", false); 39 | checkFrozenTypesTest("frozenUser", true); 40 | checkFrozenTypesTest("listOfUnfrozenUsers", false); 41 | checkFrozenTypesTest("listOfFrozenUsers", true); 42 | checkFrozenTypesTest("deeplyNestedUnfrozenUser", false); 43 | checkFrozenTypesTest("deeplyNestedFrozenUser", true); 44 | } 45 | 46 | private void checkFrozenTypesTest(String fieldName, boolean expectSuccess) throws Exception { 47 | Field field = AnnotationChecksTest.class.getDeclaredField(fieldName); 48 | Exception exception = null; 49 | try { 50 | AnnotationChecks.checkFrozenTypes(field); 51 | } catch (IllegalArgumentException e) { 52 | exception = e; 53 | } 54 | if (expectSuccess && exception != null) 55 | fail("expected check to succeed but got exception " + exception.getMessage()); 56 | else if (!expectSuccess && exception == null) 57 | fail("expected check to fail but got no exception"); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/policies/ConstantReconnectionPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.policies; 17 | 18 | /** 19 | * A reconnection policy that waits a constant time between each reconnection attempt. 20 | */ 21 | public class ConstantReconnectionPolicy implements ReconnectionPolicy { 22 | 23 | private final long delayMs; 24 | 25 | /** 26 | * Creates a reconnection policy that creates with the provided constant wait 27 | * time between reconnection attempts. 28 | * 29 | * @param constantDelayMs the constant delay in milliseconds to use. 30 | */ 31 | public ConstantReconnectionPolicy(long constantDelayMs) { 32 | if (constantDelayMs < 0) 33 | throw new IllegalArgumentException(String.format("Invalid negative delay (got %d)", constantDelayMs)); 34 | 35 | this.delayMs = constantDelayMs; 36 | } 37 | 38 | /** 39 | * The constant delay used by this reconnection policy. 40 | * 41 | * @return the constant delay used by this reconnection policy. 42 | */ 43 | public long getConstantDelayMs() { 44 | return delayMs; 45 | } 46 | 47 | /** 48 | * A new schedule that uses a constant {@code getConstantDelayMs()} delay 49 | * between reconnection attempt. 50 | * 51 | * @return the newly created schedule. 52 | */ 53 | @Override 54 | public ReconnectionSchedule newSchedule() { 55 | return new ConstantSchedule(); 56 | } 57 | 58 | private class ConstantSchedule implements ReconnectionSchedule { 59 | 60 | @Override 61 | public long nextDelayMs() { 62 | return delayMs; 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/SingleConnectionPoolTest.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.core; 2 | 3 | import java.net.InetSocketAddress; 4 | import java.util.Collection; 5 | import java.util.concurrent.Executors; 6 | import java.util.concurrent.ScheduledExecutorService; 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.concurrent.atomic.AtomicBoolean; 9 | 10 | import org.testng.annotations.Test; 11 | import org.testng.collections.Lists; 12 | 13 | import static org.testng.Assert.fail; 14 | 15 | public class SingleConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster { 16 | @Override 17 | protected Collection getTableDefinitions() { 18 | TestUtils.versionCheck(2.1, 0, "This will only work with Cassandra 2.1.0+"); 19 | 20 | return Lists.newArrayList(); 21 | } 22 | 23 | @Test(groups = "short") 24 | public void should_throttle_requests() { 25 | // Throttle to a very low value. Even a single thread can generate a higher throughput. 26 | final int maxRequests = 10; 27 | cluster.getConfiguration().getPoolingOptions() 28 | .setMaxSimultaneousRequestsPerHostThreshold(HostDistance.LOCAL, maxRequests); 29 | 30 | // Track in flight requests in a dedicated thread every second 31 | final AtomicBoolean excessInflightQueriesSpotted = new AtomicBoolean(false); 32 | final Host host = cluster.getMetadata().getHost(new InetSocketAddress(CCMBridge.IP_PREFIX + "1", 9042)); 33 | ScheduledExecutorService openConnectionsWatcherExecutor = Executors.newScheduledThreadPool(1); 34 | final Runnable openConnectionsWatcher = new Runnable() { 35 | @Override 36 | public void run() { 37 | int inFlight = session.getState().getInFlightQueries(host); 38 | if (inFlight > maxRequests) 39 | excessInflightQueriesSpotted.set(true); 40 | } 41 | }; 42 | openConnectionsWatcherExecutor.scheduleAtFixedRate(openConnectionsWatcher, 200, 200, TimeUnit.MILLISECONDS); 43 | 44 | // Generate the load 45 | for (int i = 0; i < 10000; i++) 46 | session.executeAsync("SELECT release_version FROM system.local"); 47 | 48 | openConnectionsWatcherExecutor.shutdownNow(); 49 | if (excessInflightQueriesSpotted.get()) { 50 | fail("Inflight queries exceeded the limit"); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.util.Collection; 19 | import java.util.concurrent.TimeUnit; 20 | 21 | import com.google.common.collect.Lists; 22 | import org.testng.annotations.Test; 23 | 24 | import static org.testng.Assert.*; 25 | 26 | public class AsyncQueryTest extends CCMBridge.PerClassSingleNodeCluster { 27 | 28 | @Override 29 | protected Collection getTableDefinitions() { 30 | return Lists.newArrayList(); 31 | } 32 | 33 | /** 34 | * Checks that a cancelled query releases the connection (JAVA-407). 35 | */ 36 | @Test(groups = "short") 37 | public void cancelQueryTest() throws InterruptedException { 38 | ResultSetFuture future = session.executeAsync("select release_version from system.local"); 39 | future.cancel(true); 40 | assertTrue(future.isCancelled()); 41 | 42 | TimeUnit.MILLISECONDS.sleep(100); 43 | 44 | HostConnectionPool pool = getPool(session); 45 | if (pool instanceof DynamicConnectionPool) { 46 | DynamicConnectionPool p = (DynamicConnectionPool)pool; 47 | for (Connection connection : p.connections) { 48 | assertEquals(connection.inFlight.get(), 0); 49 | } 50 | } else if (pool instanceof SingleConnectionPool){ 51 | SingleConnectionPool p = (SingleConnectionPool)pool; 52 | assertEquals(p.connectionRef.get().inFlight.get(), 0); 53 | } 54 | } 55 | 56 | private static HostConnectionPool getPool(Session session) { 57 | Collection pools = ((SessionManager) session).pools.values(); 58 | assertEquals(pools.size(), 1); 59 | return pools.iterator().next(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/ConsistencyLevel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import com.datastax.driver.core.exceptions.DriverInternalError; 19 | 20 | public enum ConsistencyLevel { 21 | 22 | ANY (0), 23 | ONE (1), 24 | TWO (2), 25 | THREE (3), 26 | QUORUM (4), 27 | ALL (5), 28 | LOCAL_QUORUM (6), 29 | EACH_QUORUM (7), 30 | SERIAL (8), 31 | LOCAL_SERIAL (9), 32 | LOCAL_ONE (10); 33 | 34 | // Used by the native protocol 35 | final int code; 36 | private static final ConsistencyLevel[] codeIdx; 37 | static { 38 | int maxCode = -1; 39 | for (ConsistencyLevel cl : ConsistencyLevel.values()) 40 | maxCode = Math.max(maxCode, cl.code); 41 | codeIdx = new ConsistencyLevel[maxCode + 1]; 42 | for (ConsistencyLevel cl : ConsistencyLevel.values()) { 43 | if (codeIdx[cl.code] != null) 44 | throw new IllegalStateException("Duplicate code"); 45 | codeIdx[cl.code] = cl; 46 | } 47 | } 48 | 49 | private ConsistencyLevel(int code) { 50 | this.code = code; 51 | } 52 | 53 | static ConsistencyLevel fromCode(int code) { 54 | if (code < 0 || code >= codeIdx.length) 55 | throw new DriverInternalError(String.format("Unknown code %d for a consistency level", code)); 56 | return codeIdx[code]; 57 | } 58 | 59 | /** 60 | * Whether or not the the consistency level applies to the local data-center only. 61 | * 62 | * @return whether this consistency level is {@code LOCAL_ONE} or {@code LOCAL_QUORUM}. 63 | */ 64 | public boolean isDCLocal() { 65 | return this == LOCAL_ONE || this == LOCAL_QUORUM; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.net.InetSocketAddress; 19 | import java.util.concurrent.atomic.AtomicBoolean; 20 | 21 | /** 22 | * A connection that is associated to a pool. 23 | */ 24 | class PooledConnection extends Connection { 25 | 26 | private final HostConnectionPool pool; 27 | 28 | /** Used in {@link HostConnectionPool} to handle races between two threads trying to trash the same connection */ 29 | final AtomicBoolean markForTrash = new AtomicBoolean(); 30 | 31 | PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { 32 | super(name, address, factory); 33 | this.pool = pool; 34 | } 35 | 36 | /** 37 | * Return the pooled connection to its pool. 38 | * The connection should generally not be reused after that. 39 | */ 40 | public void release() { 41 | // This can happen if the query to initialize the transport in the 42 | // parent constructor times out. In that case the pool will handle 43 | // it itself. 44 | if (pool == null) 45 | return; 46 | 47 | pool.returnConnection(this); 48 | } 49 | 50 | @Override 51 | protected void notifyOwnerWhenDefunct(boolean hostIsDown) { 52 | // This can happen if an exception is thrown at construction time. In 53 | // that case the pool will handle it itself. 54 | if (pool == null) 55 | return; 56 | 57 | if (hostIsDown) { 58 | pool.closeAsync().force(); 59 | } else { 60 | pool.replaceDefunctConnection(this); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/ColumnMapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping; 17 | 18 | import java.lang.reflect.Field; 19 | 20 | import com.datastax.driver.core.DataType; 21 | import static com.datastax.driver.core.querybuilder.QueryBuilder.quote; 22 | 23 | abstract class ColumnMapper { 24 | 25 | public enum Kind { PARTITION_KEY, CLUSTERING_COLUMN, REGULAR }; 26 | 27 | private final String columnName; 28 | protected final String fieldName; 29 | protected final Class javaType; 30 | // Note: dataType is not guaranteed to be exact. Typically, it will be uuid even if the underlying 31 | // type is timeuuid. Currently, this is not a problem, but we might allow some @Timeuuid annotation 32 | // for the sake of validation (similarly, we'll always have text, never ascii). 33 | protected final DataType dataType; 34 | protected final Kind kind; 35 | protected final int position; 36 | 37 | protected ColumnMapper(Field field, DataType dataType, int position) { 38 | this(AnnotationParser.columnName(field), field.getName(), field.getType(), dataType, AnnotationParser.kind(field), position); 39 | } 40 | 41 | private ColumnMapper(String columnName, String fieldName, Class javaType, DataType dataType, Kind kind, int position) { 42 | this.columnName = columnName; 43 | this.fieldName = fieldName; 44 | this.javaType = javaType; 45 | this.dataType = dataType; 46 | this.kind = kind; 47 | this.position = position; 48 | } 49 | 50 | public abstract Object getValue(T entity); 51 | public abstract void setValue(T entity, Object value); 52 | 53 | public String getColumnName() { 54 | return quote(columnName); 55 | } 56 | 57 | public DataType getDataType() { 58 | return dataType; 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Table.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | import com.datastax.driver.mapping.Mapper; 24 | 25 | /** 26 | * Defines to which table a class must be mapped to. 27 | */ 28 | @Target(ElementType.TYPE) 29 | @Retention(RetentionPolicy.RUNTIME) 30 | public @interface Table { 31 | /** 32 | * The name of the keyspace the table is part of. 33 | * 34 | * @return the name of the keyspace. 35 | */ 36 | String keyspace() default ""; 37 | /** 38 | * The name of the table. 39 | * 40 | * @return the name of the table. 41 | */ 42 | String name(); 43 | 44 | /** 45 | * Whether the keyspace name is a case sensitive one. 46 | * 47 | * @return whether the keyspace name is a case sensitive one. 48 | */ 49 | boolean caseSensitiveKeyspace() default false; 50 | /** 51 | * Whether the table name is a case sensitive one. 52 | * 53 | * @return whether the table name is a case sensitive one. 54 | */ 55 | boolean caseSensitiveTable() default false; 56 | 57 | /** 58 | * The consistency level to use for the write operations provded by the {@link Mapper} class. 59 | * 60 | * @return the consistency level to use for the write operations provded by the {@link Mapper} class. 61 | */ 62 | String writeConsistency() default ""; 63 | 64 | /** 65 | * The consistency level to use for the read operations provded by the {@link Mapper} class. 66 | * 67 | * @return the consistency level to use for the read operations provded by the {@link Mapper} class. 68 | */ 69 | String readConsistency() default ""; 70 | } 71 | -------------------------------------------------------------------------------- /driver-examples/stress/src/main/java/com/datastax/driver/stress/BlockingConsumer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.stress; 17 | 18 | import java.util.Iterator; 19 | 20 | import com.google.common.util.concurrent.Uninterruptibles; 21 | 22 | import com.datastax.driver.core.Session; 23 | import com.datastax.driver.core.exceptions.DriverException; 24 | 25 | public class BlockingConsumer implements Consumer { 26 | 27 | private final Runner runner = new Runner(); 28 | 29 | private final Session session; 30 | private final QueryGenerator requests; 31 | private final Reporter reporter; 32 | 33 | public BlockingConsumer(Session session, 34 | QueryGenerator requests, 35 | Reporter reporter) { 36 | this.session = session; 37 | this.requests = requests; 38 | this.reporter = reporter; 39 | this.runner.setDaemon(true); 40 | } 41 | 42 | @Override 43 | public void start() { 44 | this.runner.start(); 45 | } 46 | 47 | @Override 48 | public void join() { 49 | Uninterruptibles.joinUninterruptibly(this.runner); 50 | } 51 | 52 | private class Runner extends Thread { 53 | 54 | public Runner() { 55 | super("Consumer Threads"); 56 | } 57 | 58 | public void run() { 59 | try { 60 | while (requests.hasNext()) 61 | handle(requests.next()); 62 | } catch (DriverException e) { 63 | System.err.println("Error during query: " + e.getMessage()); 64 | } 65 | } 66 | 67 | protected void handle(QueryGenerator.Request request) { 68 | Reporter.Context ctx = reporter.newRequest(); 69 | try { 70 | request.execute(session); 71 | } finally { 72 | ctx.done(); 73 | } 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteTimeoutException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | import com.datastax.driver.core.ConsistencyLevel; 19 | import com.datastax.driver.core.WriteType; 20 | 21 | /** 22 | * A Cassandra timeout during a write query. 23 | */ 24 | public class WriteTimeoutException extends QueryTimeoutException { 25 | 26 | private static final long serialVersionUID = 0; 27 | 28 | private final WriteType writeType; 29 | 30 | public WriteTimeoutException(ConsistencyLevel consistency, WriteType writeType, int received, int required) { 31 | super(String.format("Cassandra timeout during write query at consistency %s (%d replica were required but only %d acknowledged the write)", consistency, required, received), 32 | consistency, 33 | received, 34 | required); 35 | this.writeType = writeType; 36 | } 37 | 38 | private WriteTimeoutException(String msg, Throwable cause, ConsistencyLevel consistency, WriteType writeType, int received, int required) { 39 | super(msg, cause, consistency, received, required); 40 | this.writeType = writeType; 41 | } 42 | 43 | /** 44 | * The type of the write for which a timeout was raised. 45 | * 46 | * @return the type of the write for which a timeout was raised. 47 | */ 48 | public WriteType getWriteType() { 49 | return writeType; 50 | } 51 | 52 | @Override 53 | public DriverException copy() { 54 | return new WriteTimeoutException(getMessage(), 55 | this, 56 | getConsistencyLevel(), 57 | getWriteType(), 58 | getReceivedAcknowledgements(), 59 | getRequiredAcknowledgements()); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/policies/ReconnectionPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.policies; 17 | 18 | /** 19 | * Policy that decides how often the reconnection to a dead node is attempted. 20 | * 21 | * Each time a node is detected dead (because a connection error occurs), a new 22 | * {@code ReconnectionSchedule} instance is created (through the {@link #newSchedule()}). 23 | * Then each call to the {@link ReconnectionSchedule#nextDelayMs} method of 24 | * this instance will decide when the next reconnection attempt to this node 25 | * will be tried. 26 | * 27 | * Note that if the driver receives a push notification from the Cassandra cluster 28 | * that a node is UP, any existing {@code ReconnectionSchedule} on that node 29 | * will be cancelled and a new one will be created (in effect, the driver reset 30 | * the scheduler). 31 | * 32 | * The default {@link ExponentialReconnectionPolicy} policy is usually 33 | * adequate. 34 | */ 35 | public interface ReconnectionPolicy { 36 | 37 | /** 38 | * Creates a new schedule for reconnection attempts. 39 | * 40 | * @return the created schedule. 41 | */ 42 | public ReconnectionSchedule newSchedule(); 43 | 44 | /** 45 | * Schedules reconnection attempts to a node. 46 | */ 47 | public interface ReconnectionSchedule { 48 | 49 | /** 50 | * When to attempt the next reconnection. 51 | * 52 | * This method will be called once when the host is detected down to 53 | * schedule the first reconnection attempt, and then once after each failed 54 | * reconnection attempt to schedule the next one. Hence each call to this 55 | * method are free to return a different value. 56 | * 57 | * @return a time in milliseconds to wait before attempting the next 58 | * reconnection. 59 | */ 60 | public long nextDelayMs(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/schemabuilder/UDTType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.schemabuilder; 17 | 18 | import com.datastax.driver.core.DataType; 19 | 20 | /** 21 | * Represents a CQL type containing a user-defined type (UDT) in a SchemaBuilder statement. 22 | *

23 | * Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)} to build instances of this type. 24 | */ 25 | public final class UDTType implements ColumnType { 26 | private final String asCQLString; 27 | 28 | private UDTType(String asCQLString) { 29 | this.asCQLString = asCQLString; 30 | } 31 | 32 | @Override public String asCQLString() { 33 | return asCQLString; 34 | } 35 | 36 | static UDTType frozen(String udtName) { 37 | SchemaStatement.validateNotEmpty(udtName, "UDT name"); 38 | return new UDTType("frozen<" + udtName + ">"); 39 | } 40 | 41 | static UDTType list(UDTType elementType) { 42 | return new UDTType("list<" + elementType.asCQLString() + ">"); 43 | } 44 | 45 | static UDTType set(UDTType elementType) { 46 | return new UDTType("set<" + elementType.asCQLString() + ">"); 47 | } 48 | 49 | static UDTType mapWithUDTKey(UDTType keyType, DataType valueType) { 50 | return new UDTType("map<" + keyType.asCQLString() + ", " + valueType + ">"); 51 | } 52 | 53 | static UDTType mapWithUDTValue(DataType keyType, UDTType valueType) { 54 | return new UDTType("map<" + keyType + ", " + valueType.asCQLString() + ">"); 55 | } 56 | 57 | static UDTType mapWithUDTKeyAndValue(UDTType keyType, UDTType valueType) { 58 | return new UDTType("map<" + keyType.asCQLString() + ", " + valueType.asCQLString() + ">"); 59 | } 60 | 61 | static UDTType literal(String literal) { 62 | SchemaStatement.validateNotEmpty(literal, "UDT type literal"); 63 | return new UDTType(literal); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCompositeKeyTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping; 17 | 18 | import java.util.Arrays; 19 | import java.util.Collection; 20 | 21 | import com.datastax.driver.mapping.annotations.*; 22 | import org.testng.annotations.Test; 23 | 24 | import com.datastax.driver.core.CCMBridge; 25 | 26 | /** 27 | * Tests for the mapper with composite partition keys and multiple clustering columns. 28 | */ 29 | public class MapperCompositeKeyTest extends CCMBridge.PerClassSingleNodeCluster { 30 | 31 | protected Collection getTableDefinitions() { 32 | return Arrays.asList("CREATE TABLE test_table (pk1 int, pk2 int, cc1 int, cc2 int, PRIMARY KEY ((pk1, pk2), cc1, cc2))"); 33 | } 34 | 35 | @Table(keyspace = "ks", name = "test_table") 36 | public static class TestTable { 37 | @PartitionKey(0) 38 | private int pk1; 39 | 40 | @PartitionKey(1) 41 | private int pk2; 42 | 43 | @ClusteringColumn(0) 44 | private int cc1; 45 | 46 | @ClusteringColumn(1) 47 | private int cc2; 48 | 49 | public int getPk1() { 50 | return pk1; 51 | } 52 | 53 | public void setPk1(int pk1) { 54 | this.pk1 = pk1; 55 | } 56 | 57 | public int getPk2() { 58 | return pk2; 59 | } 60 | 61 | public void setPk2(int pk2) { 62 | this.pk2 = pk2; 63 | } 64 | 65 | public int getCc1() { 66 | return cc1; 67 | } 68 | 69 | public void setCc1(int cc1) { 70 | this.cc1 = cc1; 71 | } 72 | 73 | public int getCc2() { 74 | return cc2; 75 | } 76 | 77 | public void setCc2(int cc2) { 78 | this.cc2 = cc2; 79 | } 80 | } 81 | 82 | @Test(groups = "short") 83 | public void testCreateMapper() throws Exception { 84 | new MappingManager(session).mapper(TestTable.class); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | Contributing guidelines 2 | ======================= 3 | 4 | Working on an issue 5 | ------------------- 6 | 7 | Before starting to work on something, please comment in JIRA or ask on the mailing list 8 | to make sure nobody else is working on it. 9 | 10 | If a fix applies both to 2.0 and 2.1, work on the 2.0 branch, your commit will eventually 11 | get merged in 2.1. 12 | 13 | Before you send your pull request, make sure that: 14 | 15 | - you have a unit test that failed before the fix and succeeds after. 16 | - the fix is mentioned in ``driver-core/CHANGELOG.rst``. 17 | - the commit message include the reference of the JIRA ticket for automatic linking 18 | (example: ``Fix NPE when a connection fails during pool construction (JAVA-503).``). 19 | 20 | As long as your pull request is not merged, it's OK to rebase your branch and push with 21 | ``--force``. 22 | 23 | If you want to contribute but don't have a specific issue in mind, the `lhf `_ 24 | label in JIRA is a good place to start: it marks "low hanging fruits" that don't require 25 | in-depth knowledge of the codebase. 26 | 27 | Editor configuration 28 | -------------------- 29 | 30 | General 31 | ~~~~~~~ 32 | 33 | We consider automatic formatting as a help, not a crutch. Sometimes it makes sense to 34 | break the rules to make the code more readable, for instance aligning columns (see the 35 | constant declarations in ``DataType.Name`` for an example of this). 36 | 37 | **Please do not reformat whole files, only the lines that you have added or modified**. 38 | 39 | 40 | Eclipse 41 | ~~~~~~~ 42 | 43 | Formatter: 44 | 45 | - Preferences > Java > Code Style > Formatter. 46 | - Click "Import". 47 | - Select ``src/main/config/ide/eclipse-formatter.xml``. 48 | 49 | Import order: 50 | 51 | - Preferences > Java > Code Style > Organize imports. 52 | - Click "Import". 53 | - Select ``src/main/config/ide/eclipse.importorder``. 54 | 55 | Prevent trailing whitespaces: 56 | 57 | - Preferences > Java > Editor > Save Actions. 58 | - Check "Perform the selected actions on save". 59 | - Ensure "Format source code" and "Organize imports" are unchecked. 60 | - Check "Additional actions". 61 | - Click "Configure". 62 | - In the "Code Organizing" tab, check "Remove trailing whitespace" and "All lines". 63 | - Click "OK" (the text area should only have one action "Remove trailing white spaces"). 64 | 65 | 66 | IntelliJ IDEA 67 | ~~~~~~~~~~~~~ 68 | 69 | - File > Import Settings... 70 | - Select ``src/main/config/ide/intellij-code-style.jar``. 71 | 72 | This should add a new Code Style scheme called "java-driver". 73 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.core; 2 | 3 | import java.util.Collection; 4 | 5 | import com.google.common.collect.Lists; 6 | import org.testng.annotations.Test; 7 | 8 | import static org.testng.Assert.assertEquals; 9 | 10 | import com.datastax.driver.core.Metrics.Errors; 11 | import com.datastax.driver.core.policies.RetryPolicy; 12 | import com.datastax.driver.core.policies.RetryPolicy.RetryDecision; 13 | 14 | public class MetricsTest extends CCMBridge.PerClassSingleNodeCluster { 15 | private volatile RetryDecision retryDecision; 16 | 17 | @Override 18 | protected Cluster.Builder configure(Cluster.Builder builder) { 19 | return builder.withRetryPolicy(new RetryPolicy() { 20 | @Override 21 | public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { 22 | return retryDecision; 23 | } 24 | 25 | @Override 26 | public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { 27 | return retryDecision; 28 | } 29 | 30 | @Override 31 | public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { 32 | return retryDecision; 33 | } 34 | }); 35 | } 36 | 37 | @Override 38 | protected Collection getTableDefinitions() { 39 | return Lists.newArrayList("CREATE TABLE test (k int primary key, v int)", 40 | "INSERT INTO test (k, v) VALUES (1, 1)"); 41 | } 42 | 43 | @Test(groups = "short") 44 | public void retriesTest() { 45 | retryDecision = RetryDecision.retry(ConsistencyLevel.ONE); 46 | 47 | // We only have one node, this will throw an unavailable exception 48 | Statement statement = new SimpleStatement("SELECT v FROM test WHERE k = 1").setConsistencyLevel(ConsistencyLevel.TWO); 49 | session.execute(statement); 50 | 51 | Errors errors = cluster.getMetrics().getErrorMetrics(); 52 | assertEquals(errors.getUnavailables().getCount(), 1); 53 | assertEquals(errors.getRetries().getCount(), 1); 54 | assertEquals(errors.getRetriesOnUnavailable().getCount(), 1); 55 | 56 | retryDecision = RetryDecision.ignore(); 57 | session.execute(statement); 58 | 59 | assertEquals(errors.getUnavailables().getCount(), 2); 60 | assertEquals(errors.getIgnores().getCount(), 1); 61 | assertEquals(errors.getIgnoresOnUnavailable().getCount(), 1); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/TupleValue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.util.Arrays; 19 | import java.util.List; 20 | 21 | /** 22 | * A value for a Tuple. 23 | */ 24 | public class TupleValue extends AbstractAddressableByIndexData { 25 | 26 | private final TupleType type; 27 | 28 | /** 29 | * Builds a new value for a tuple. 30 | * 31 | * @param types the types of the tuple's components. 32 | */ 33 | TupleValue(TupleType type) { 34 | // All things in a tuple are encoded with the protocol v3 35 | super(ProtocolVersion.V3, type.getComponentTypes().size()); 36 | this.type = type; 37 | } 38 | 39 | protected DataType getType(int i) { 40 | return type.getComponentTypes().get(i); 41 | } 42 | 43 | @Override 44 | protected String getName(int i) { 45 | // This is used for error messages 46 | return "component " + i; 47 | } 48 | 49 | /** 50 | * The tuple type this is a value of. 51 | * 52 | * @return The tuple type this is a value of. 53 | */ 54 | public TupleType getType() { 55 | return type; 56 | } 57 | 58 | @Override 59 | public boolean equals(Object o) { 60 | if (!(o instanceof TupleValue)) 61 | return false; 62 | 63 | TupleValue that = (TupleValue)o; 64 | if (!type.equals(that.type)) 65 | return false; 66 | 67 | return super.equals(o); 68 | } 69 | 70 | @Override 71 | public int hashCode() { 72 | return super.hashCode(); 73 | } 74 | 75 | @Override 76 | public String toString() { 77 | StringBuilder sb = new StringBuilder(); 78 | sb.append("("); 79 | for (int i = 0; i < values.length; i++) { 80 | if (i > 0) 81 | sb.append(", "); 82 | 83 | DataType dt = getType(i); 84 | sb.append(values[i] == null ? "null" : dt.format(dt.deserialize(values[i], ProtocolVersion.V3))); 85 | } 86 | sb.append(")"); 87 | return sb.toString(); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/FetchingTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.util.Collection; 19 | import java.util.Collections; 20 | 21 | import org.testng.annotations.Test; 22 | import static org.testng.Assert.*; 23 | 24 | import com.datastax.driver.core.exceptions.UnsupportedFeatureException; 25 | 26 | /** 27 | * Test ResultSet paging correct behavior. 28 | */ 29 | public class FetchingTest extends CCMBridge.PerClassSingleNodeCluster { 30 | 31 | @Override 32 | protected Collection getTableDefinitions() { 33 | return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))"); 34 | } 35 | 36 | @Test(groups = "short") 37 | public void simplePagingTest() throws Throwable { 38 | 39 | try { 40 | 41 | // Insert data 42 | String key = "paging_test"; 43 | for (int i = 0; i < 100; i++) 44 | session.execute(String.format("INSERT INTO test (k, v) VALUES ('%s', %d)", key, i)); 45 | 46 | SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", key)); 47 | st.setFetchSize(5); // Ridiculously small fetch size for testing purpose. Don't do at home. 48 | ResultSet rs = session.execute(st); 49 | 50 | assertFalse(rs.isFullyFetched()); 51 | 52 | for (int i = 0; i < 100; i++) { 53 | // isExhausted makes sure we do fetch if needed 54 | assertFalse(rs.isExhausted()); 55 | assertEquals(rs.getAvailableWithoutFetching(), 5-(i%5)); 56 | assertEquals(rs.one().getInt(0), i); 57 | } 58 | 59 | assertTrue(rs.isExhausted()); 60 | assertTrue(rs.isFullyFetched()); 61 | 62 | } catch (UnsupportedFeatureException e) { 63 | // This is expected when testing the protocol v1 64 | if (cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum() != ProtocolVersion.V1) 65 | throw e; 66 | } catch (Throwable e) { 67 | errorOut(); 68 | throw e; 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /driver-mapping/src/main/java/com/datastax/driver/mapping/AccessorInvocationHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.mapping; 17 | 18 | import java.lang.reflect.InvocationHandler; 19 | import java.lang.reflect.Method; 20 | import java.util.*; 21 | 22 | class AccessorInvocationHandler implements InvocationHandler { 23 | 24 | private static final Object[] NO_ARGS = new Object[0]; 25 | 26 | private static final Method TO_STRING; 27 | private static final Method EQUALS; 28 | private static final Method HASH_CODE; 29 | static { 30 | try { 31 | TO_STRING = Object.class.getMethod("toString"); 32 | EQUALS = Object.class.getMethod("equals", Object.class); 33 | HASH_CODE = Object.class.getMethod("hashCode"); 34 | } catch (NoSuchMethodException e) { 35 | throw new AssertionError(e); // Can't happen 36 | } 37 | } 38 | 39 | private final AccessorMapper mapper; 40 | 41 | private final Map methodMap = new HashMap(); 42 | 43 | AccessorInvocationHandler(AccessorMapper mapper) { 44 | this.mapper = mapper; 45 | 46 | for (MethodMapper method : mapper.methods) 47 | methodMap.put(method.method, method); 48 | } 49 | 50 | public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { 51 | if (m.equals(TO_STRING)) 52 | return mapper.daoClass.getSimpleName() + " implementation generated by the Cassandra driver mapper"; 53 | 54 | // It's unlikely that equals and hashCode will be used on accessor implementations, but better safe than sorry. 55 | // Identity equality is enough, given that the mapper always returns the same instance for a given accessor. 56 | if (m.equals(EQUALS)) 57 | return proxy == args[0]; 58 | 59 | if (m.equals(HASH_CODE)) 60 | return System.identityHashCode(proxy); 61 | 62 | MethodMapper method = methodMap.get(m); 63 | if (method == null) 64 | throw new UnsupportedOperationException(); 65 | return method.invoke(args == null ? NO_ARGS : args); 66 | } 67 | } 68 | 69 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | /** 19 | * The policy with which to decide whether a host should be considered down. 20 | * 21 | * TODO: this class is fully abstract (rather than an interface) because I'm 22 | * not sure it's worth exposing (and if we do expose it, we need to expose 23 | * ConnectionException). Maybe just exposing say a threshold of error before 24 | * convicting a node is enough. 25 | */ 26 | abstract class ConvictionPolicy { 27 | 28 | /** 29 | * Called when a connection error occurs on a connection to the host this policy applies to. 30 | * 31 | * @param exception the connection error that occurred. 32 | * 33 | * @return {@code true} if the host should be considered down. 34 | */ 35 | public abstract boolean addFailure(ConnectionException exception); 36 | 37 | /** 38 | * Called when the host has been detected up. 39 | */ 40 | public abstract void reset(); 41 | 42 | /** 43 | * Simple factory interface to allow creating {@link ConvictionPolicy} instances. 44 | */ 45 | public interface Factory { 46 | 47 | /** 48 | * Creates a new ConvictionPolicy instance for {@code host}. 49 | * 50 | * @param host the host this policy applies to 51 | * @return the newly created {@link ConvictionPolicy} instance. 52 | */ 53 | public ConvictionPolicy create(Host host); 54 | } 55 | 56 | public static class Simple extends ConvictionPolicy { 57 | private Simple(Host host) { 58 | } 59 | 60 | @Override 61 | public boolean addFailure(ConnectionException exception) { 62 | return true; 63 | } 64 | 65 | public boolean addFailureFromExternalDetector() { 66 | return true; 67 | } 68 | 69 | @Override 70 | public void reset() {} 71 | 72 | public static class Factory implements ConvictionPolicy.Factory { 73 | 74 | @Override 75 | public ConvictionPolicy create(Host host) { 76 | return new Simple(host); 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CompressionOptionsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.schemabuilder; 17 | 18 | import org.testng.annotations.Test; 19 | 20 | import static org.assertj.core.api.Assertions.assertThat; 21 | 22 | import static com.datastax.driver.core.schemabuilder.SchemaBuilder.deflate; 23 | import static com.datastax.driver.core.schemabuilder.SchemaBuilder.lz4; 24 | import static com.datastax.driver.core.schemabuilder.SchemaBuilder.noCompression; 25 | import static com.datastax.driver.core.schemabuilder.SchemaBuilder.snappy; 26 | 27 | public class CompressionOptionsTest { 28 | 29 | @Test(groups = "unit") 30 | public void should_build_compressions_options_for_lz4() throws Exception { 31 | //When 32 | final String built = lz4().withChunkLengthInKb(128).withCRCCheckChance(0.6D).build(); 33 | 34 | //Then 35 | assertThat(built).isEqualTo("{'sstable_compression' : 'LZ4Compressor', 'chunk_length_kb' : 128, 'crc_check_chance' : 0.6}"); 36 | } 37 | 38 | @Test(groups = "unit") 39 | public void should_create_snappy_compressions_options() throws Exception { 40 | //When 41 | final String built = snappy().withChunkLengthInKb(128).withCRCCheckChance(0.6D).build(); 42 | 43 | //Then 44 | assertThat(built).isEqualTo("{'sstable_compression' : 'SnappyCompressor', 'chunk_length_kb' : 128, 'crc_check_chance' : 0.6}"); 45 | } 46 | 47 | @Test(groups = "unit") 48 | public void should_create_deflate_compressions_options() throws Exception { 49 | //When 50 | final String built = deflate().withChunkLengthInKb(128).withCRCCheckChance(0.6D).build(); 51 | 52 | //Then 53 | assertThat(built).isEqualTo("{'sstable_compression' : 'DeflateCompressor', 'chunk_length_kb' : 128, 'crc_check_chance' : 0.6}"); 54 | } 55 | 56 | @Test(groups = "unit") 57 | public void should_create_no_compressions_options() throws Exception { 58 | //When 59 | final String built = noCompression().withChunkLengthInKb(128).withCRCCheckChance(0.6D).build(); 60 | 61 | //Then 62 | assertThat(built).isEqualTo("{'sstable_compression' : ''}"); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/UDTValue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | /** 19 | * A value for a User Defined Type. 20 | */ 21 | public class UDTValue extends AbstractData { 22 | 23 | private final UserType definition; 24 | 25 | UDTValue(UserType definition) { 26 | // All things in a UDT are encoded with the protocol v3 27 | super(ProtocolVersion.V3, definition.size()); 28 | this.definition = definition; 29 | } 30 | 31 | protected DataType getType(int i) { 32 | return definition.byIdx[i].getType(); 33 | } 34 | 35 | protected String getName(int i) { 36 | return definition.byIdx[i].getName(); 37 | } 38 | 39 | protected int[] getAllIndexesOf(String name) { 40 | int[] indexes = definition.byName.get(Metadata.handleId(name)); 41 | if (indexes == null) 42 | throw new IllegalArgumentException(name + " is not a field defined in this UDT"); 43 | return indexes; 44 | } 45 | 46 | /** 47 | * The UDT this is a value of. 48 | * 49 | * @return the UDT this is a value of. 50 | */ 51 | public UserType getType() { 52 | return definition; 53 | } 54 | 55 | @Override 56 | public boolean equals(Object o) { 57 | if (!(o instanceof UDTValue)) 58 | return false; 59 | 60 | UDTValue that = (UDTValue)o; 61 | if (!definition.equals(that.definition)) 62 | return false; 63 | 64 | return super.equals(o); 65 | } 66 | 67 | @Override 68 | public int hashCode() { 69 | return super.hashCode(); 70 | } 71 | 72 | @Override 73 | public String toString() { 74 | StringBuilder sb = new StringBuilder(); 75 | sb.append("{"); 76 | for (int i = 0; i < values.length; i++) { 77 | if (i > 0) 78 | sb.append(", "); 79 | 80 | sb.append(getName(i)); 81 | sb.append(":"); 82 | DataType dt = getType(i); 83 | sb.append(values[i] == null ? "null" : dt.format(dt.deserialize(values[i], ProtocolVersion.V3))); 84 | } 85 | sb.append("}"); 86 | return sb.toString(); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/ArrayBackedRow.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.math.BigDecimal; 19 | import java.math.BigInteger; 20 | import java.net.InetAddress; 21 | import java.nio.ByteBuffer; 22 | import java.util.*; 23 | 24 | import com.datastax.driver.core.exceptions.InvalidTypeException; 25 | 26 | /** 27 | * Implementation of a Row backed by an ArrayList. 28 | */ 29 | class ArrayBackedRow extends AbstractGettableData implements Row { 30 | 31 | private final ColumnDefinitions metadata; 32 | private final List data; 33 | 34 | private ArrayBackedRow(ColumnDefinitions metadata, ProtocolVersion protocolVersion, List data) { 35 | super(protocolVersion); 36 | this.metadata = metadata; 37 | this.data = data; 38 | } 39 | 40 | static Row fromData(ColumnDefinitions metadata, ProtocolVersion protocolVersion, List data) { 41 | if (data == null) 42 | return null; 43 | 44 | return new ArrayBackedRow(metadata, protocolVersion, data); 45 | } 46 | 47 | @Override 48 | public ColumnDefinitions getColumnDefinitions() { 49 | return metadata; 50 | } 51 | 52 | @Override 53 | protected DataType getType(int i) { 54 | return metadata.getType(i); 55 | } 56 | 57 | @Override 58 | protected String getName(int i) { 59 | return metadata.getName(i); 60 | } 61 | 62 | @Override 63 | protected ByteBuffer getValue(int i) { 64 | return data.get(i); 65 | } 66 | 67 | @Override 68 | protected int getIndexOf(String name) { 69 | return metadata.getFirstIdx(name); 70 | } 71 | 72 | @Override 73 | public String toString() { 74 | StringBuilder sb = new StringBuilder(); 75 | sb.append("Row["); 76 | for (int i = 0; i < metadata.size(); i++) { 77 | if (i != 0) 78 | sb.append(", "); 79 | ByteBuffer bb = data.get(i); 80 | if (bb == null) 81 | sb.append("NULL"); 82 | else 83 | sb.append(metadata.getType(i).codec(protocolVersion).deserialize(bb).toString()); 84 | } 85 | sb.append(']'); 86 | return sb.toString(); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /driver-examples/stress/src/main/java/com/datastax/driver/stress/QueryGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.stress; 17 | 18 | import java.util.Iterator; 19 | 20 | import com.datastax.driver.core.*; 21 | 22 | import joptsimple.OptionParser; 23 | import joptsimple.OptionSet; 24 | 25 | public abstract class QueryGenerator implements Iterator { 26 | 27 | protected final int iterations; 28 | 29 | protected QueryGenerator(int iterations) { 30 | this.iterations = iterations; 31 | } 32 | 33 | public abstract int currentIteration(); 34 | 35 | public int totalIterations() { 36 | return iterations; 37 | } 38 | 39 | public interface Builder { 40 | public String name(); 41 | public OptionParser addOptions(OptionParser parser); 42 | public void prepare(OptionSet options, Session session); 43 | public QueryGenerator create(int id, int iterations, OptionSet options, Session session); 44 | } 45 | 46 | public interface Request { 47 | 48 | public ResultSet execute(Session session); 49 | 50 | public ResultSetFuture executeAsync(Session session); 51 | 52 | public static class SimpleQuery implements Request { 53 | 54 | private final Statement statement; 55 | 56 | public SimpleQuery(Statement statement) { 57 | this.statement = statement; 58 | } 59 | 60 | public ResultSet execute(Session session) { 61 | return session.execute(statement); 62 | } 63 | 64 | public ResultSetFuture executeAsync(Session session) { 65 | return session.executeAsync(statement); 66 | } 67 | } 68 | 69 | public static class PreparedQuery implements Request { 70 | 71 | private final BoundStatement query; 72 | 73 | public PreparedQuery(BoundStatement query) { 74 | this.query = query; 75 | } 76 | 77 | public ResultSet execute(Session session) { 78 | return session.execute(query); 79 | } 80 | 81 | public ResultSetFuture executeAsync(Session session) { 82 | return session.executeAsync(query); 83 | } 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryTimeoutException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core.exceptions; 17 | 18 | import com.datastax.driver.core.ConsistencyLevel; 19 | 20 | /** 21 | * A Cassandra timeout during a query. 22 | * 23 | * Such an exception is returned when the query has been tried by Cassandra but 24 | * cannot be achieved with the requested consistency level within the rpc 25 | * timeout set for Cassandra. 26 | */ 27 | @SuppressWarnings("serial") 28 | public abstract class QueryTimeoutException extends QueryExecutionException { 29 | 30 | private final ConsistencyLevel consistency; 31 | private final int received; 32 | private final int required; 33 | 34 | protected QueryTimeoutException(String msg, ConsistencyLevel consistency, int received, int required) { 35 | super(msg); 36 | this.consistency = consistency; 37 | this.received = received; 38 | this.required = required; 39 | } 40 | 41 | protected QueryTimeoutException(String msg, Throwable cause, ConsistencyLevel consistency, int received, int required) { 42 | super(msg, cause); 43 | this.consistency = consistency; 44 | this.received = received; 45 | this.required = required; 46 | } 47 | 48 | /** 49 | * The consistency level of the operation that time outed. 50 | * 51 | * @return the consistency level of the operation that time outed. 52 | */ 53 | public ConsistencyLevel getConsistencyLevel() { 54 | return consistency; 55 | } 56 | 57 | /** 58 | * The number of replica that had acknowledged/responded to the operation 59 | * before it time outed. 60 | * 61 | * @return the number of replica that had acknowledged/responded the 62 | * operation before it time outed. 63 | */ 64 | public int getReceivedAcknowledgements() { 65 | return received; 66 | } 67 | 68 | /** 69 | * The minimum number of replica acknowledgements/responses that were 70 | * required to fulfill the operation. 71 | * 72 | * @return The minimum number of replica acknowledgements/response that 73 | * were required to fulfill the operation. 74 | */ 75 | public int getRequiredAcknowledgements() { 76 | return required; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.util.*; 19 | 20 | import org.testng.annotations.Test; 21 | import static org.testng.Assert.*; 22 | 23 | import static com.datastax.driver.core.TestUtils.*; 24 | 25 | public class CaseSensitivityTest { 26 | 27 | private void assertExists(CCMBridge.CCMCluster c, String fetchName, String realName) { 28 | KeyspaceMetadata km = c.cluster.getMetadata().getKeyspace(fetchName); 29 | assertNotNull(km); 30 | assertEquals(realName, km.getName()); 31 | } 32 | 33 | private void assertNotExists(CCMBridge.CCMCluster c, String name) { 34 | assertNull(c.cluster.getMetadata().getKeyspace(name)); 35 | } 36 | 37 | @Test(groups = "short") 38 | public void testCaseInsensitiveKeyspace() throws Throwable { 39 | CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder()); 40 | Session s = c.session; 41 | try { 42 | String ksName = "MyKeyspace"; 43 | s.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ksName, 1)); 44 | 45 | assertExists(c, ksName, "mykeyspace"); 46 | assertExists(c, "mykeyspace", "mykeyspace"); 47 | assertExists(c, "MYKEYSPACE", "mykeyspace"); 48 | 49 | } catch (Throwable e) { 50 | c.errorOut(); 51 | throw e; 52 | } finally { 53 | c.discard(); 54 | } 55 | } 56 | 57 | @Test(groups = "short") 58 | public void testCaseSensitiveKeyspace() throws Throwable { 59 | CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder()); 60 | Session s = c.session; 61 | try { 62 | String ksName = "\"MyKeyspace\""; 63 | s.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ksName, 1)); 64 | 65 | assertExists(c, ksName, "MyKeyspace"); 66 | assertExists(c, Metadata.quote("MyKeyspace"), "MyKeyspace"); 67 | assertNotExists(c, "mykeyspace"); 68 | assertNotExists(c, "MyKeyspace"); 69 | assertNotExists(c, "MYKEYSPACE"); 70 | 71 | } catch (Throwable e) { 72 | c.errorOut(); 73 | throw e; 74 | } finally { 75 | c.discard(); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/TypeCodecTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2014 DataStax Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.datastax.driver.core; 17 | 18 | import java.nio.ByteBuffer; 19 | import java.util.Map; 20 | import java.util.Collections; 21 | import java.util.List; 22 | 23 | import com.google.common.collect.Lists; 24 | import com.google.common.base.Strings; 25 | 26 | import org.testng.Assert; 27 | import org.testng.annotations.Test; 28 | 29 | import static com.datastax.driver.core.DataType.text; 30 | 31 | public class TypeCodecTest { 32 | 33 | public static final DataType CUSTOM_FOO = DataType.custom("com.example.FooBar"); 34 | 35 | @Test(groups = "unit") 36 | public void testCustomList() throws Exception { 37 | TypeCodec listType = TypeCodec.listOf(CUSTOM_FOO, ProtocolVersion.V2); 38 | Assert.assertNotNull(listType); 39 | } 40 | 41 | @Test(groups = "unit") 42 | public void testCustomSet() throws Exception { 43 | TypeCodec setType = TypeCodec.setOf(CUSTOM_FOO, ProtocolVersion.V2); 44 | Assert.assertNotNull(setType); 45 | } 46 | 47 | @Test(groups = "unit") 48 | public void testCustomKeyMap() throws Exception { 49 | TypeCodec> mapType = TypeCodec.mapOf(CUSTOM_FOO, text(), ProtocolVersion.V2); 50 | Assert.assertNotNull(mapType); 51 | } 52 | 53 | @Test(groups = "unit") 54 | public void testCustomValueMap() throws Exception { 55 | TypeCodec> mapType = TypeCodec.mapOf(text(), CUSTOM_FOO, ProtocolVersion.V2); 56 | Assert.assertNotNull(mapType); 57 | } 58 | 59 | @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class }) 60 | public void collectionTooLargeTest() throws Exception { 61 | TypeCodec> listType = TypeCodec.listOf(DataType.cint(), ProtocolVersion.V2); 62 | List list = Collections.nCopies(65536, 1); 63 | 64 | listType.serialize(list); 65 | } 66 | 67 | @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class }) 68 | public void collectionElementTooLargeTest() throws Exception { 69 | TypeCodec> listType = TypeCodec.listOf(DataType.text(), ProtocolVersion.V2); 70 | List list = Lists.newArrayList(Strings.repeat("a", 65536)); 71 | 72 | listType.serialize(list); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.core; 2 | 3 | import java.net.InetAddress; 4 | import java.net.InetSocketAddress; 5 | 6 | import com.google.common.collect.Lists; 7 | import org.testng.annotations.Test; 8 | 9 | import static org.testng.Assert.assertEquals; 10 | import static org.testng.Assert.assertNull; 11 | 12 | import com.datastax.driver.core.policies.Policies; 13 | import com.datastax.driver.core.policies.WhiteListPolicy; 14 | 15 | /** 16 | * Tests the behavior of the driver when some hosts have no rpc_address in the control host's system tables (JAVA-428). 17 | * 18 | * This can happen because of gossip bugs. We want to ignore these hosts because this is most likely indicative of an error state. 19 | */ 20 | public class MissingRpcAddressTest { 21 | 22 | @Test(groups = "short") 23 | public void testMissingRpcAddressAtStartup() throws Exception { 24 | CCMBridge ccm = CCMBridge.create("ccm", 2); 25 | deleteNode2RpcAddressFromNode1(); 26 | 27 | Cluster cluster = null; 28 | try { 29 | // Use only one contact point to make sure that the control connection is on node1 30 | cluster = Cluster.builder() 31 | .addContactPoint(CCMBridge.IP_PREFIX + "1") 32 | .build(); 33 | cluster.connect(); 34 | 35 | // Since node2's RPC address is unknown on our control host, it should have been ignored 36 | assertEquals(cluster.getMetrics().getConnectedToHosts().getValue().intValue(), 1); 37 | assertNull(cluster.getMetadata().getHost(socketAddress(2))); 38 | } finally { 39 | if (cluster != null) 40 | cluster.close(); 41 | ccm.remove(); 42 | } 43 | } 44 | 45 | // Artificially modify the system tables to simulate the missing rpc_address. 46 | private void deleteNode2RpcAddressFromNode1() throws Exception { 47 | Cluster cluster = null; 48 | try { 49 | cluster = Cluster.builder() 50 | .addContactPoint(CCMBridge.IP_PREFIX + "1") 51 | // ensure we will only connect to node1 52 | .withLoadBalancingPolicy(new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(), 53 | Lists.newArrayList(socketAddress(1)))) 54 | .build(); 55 | Session session = cluster.connect(); 56 | session.execute("DELETE rpc_address FROM system.peers WHERE peer = ?", InetAddress.getByName(CCMBridge.IP_PREFIX + "2")); 57 | session.close(); 58 | } finally { 59 | if (cluster != null) 60 | cluster.close(); 61 | } 62 | } 63 | 64 | private static InetSocketAddress socketAddress(int node) { 65 | return new InetSocketAddress(CCMBridge.IP_PREFIX + Integer.toString(node), 9042); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /driver-core/src/test/java/com/datastax/driver/core/AtomicMonotonicTimestampGeneratorTest.java: -------------------------------------------------------------------------------- 1 | package com.datastax.driver.core; 2 | 3 | import java.util.List; 4 | import java.util.SortedSet; 5 | import java.util.concurrent.ConcurrentSkipListSet; 6 | import java.util.concurrent.ExecutionException; 7 | import java.util.concurrent.Executors; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | import com.google.common.collect.Lists; 11 | import com.google.common.util.concurrent.Futures; 12 | import com.google.common.util.concurrent.ListenableFuture; 13 | import com.google.common.util.concurrent.ListeningExecutorService; 14 | import com.google.common.util.concurrent.MoreExecutors; 15 | import org.testng.annotations.Test; 16 | 17 | import static org.testng.Assert.assertEquals; 18 | import static org.testng.Assert.fail; 19 | 20 | public class AtomicMonotonicTimestampGeneratorTest { 21 | @Test(groups = "unit") 22 | public void should_generate_incrementing_timestamps_for_all_threads() throws InterruptedException { 23 | // Create a generator with a fixed millisecond value 24 | final long fixedTime = 1; 25 | final AtomicMonotonicTimestampGenerator generator = new AtomicMonotonicTimestampGenerator(); 26 | generator.clock = new MockClocks.FixedTimeClock(fixedTime); 27 | 28 | // Generate 1000 timestamps shared among multiple threads 29 | final int testThreadsCount = 2; 30 | assertEquals(1000 % testThreadsCount, 0); 31 | final SortedSet allTimestamps = new ConcurrentSkipListSet(); 32 | ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(testThreadsCount)); 33 | 34 | List> futures = Lists.newArrayListWithExpectedSize(testThreadsCount); 35 | for (int i = 0; i < testThreadsCount; i++) { 36 | futures.add(executor.submit( 37 | new Runnable() { 38 | @Override 39 | public void run() { 40 | for (int i = 0; i < 1000 / testThreadsCount; i++) 41 | allTimestamps.add(generator.next()); 42 | } 43 | })); 44 | } 45 | executor.shutdown(); 46 | executor.awaitTermination(1, TimeUnit.SECONDS); 47 | 48 | try { 49 | Futures.allAsList(futures).get(); 50 | } catch (ExecutionException e) { 51 | Throwable cause = e.getCause(); 52 | if (cause instanceof AssertionError) 53 | throw (AssertionError)cause; 54 | else 55 | fail("Error in a test thread", cause); 56 | } 57 | 58 | // Ensure that the 1000 microseconds for the mocked millisecond value have been generated 59 | int i = 0; 60 | for (Long timestamp : allTimestamps) { 61 | Long expected = fixedTime * 1000 + i; 62 | assertEquals(timestamp, expected); 63 | i += 1; 64 | } 65 | } 66 | } 67 | --------------------------------------------------------------------------------