0
# Connection and Access
1
2
Methods for obtaining connection information and establishing DataStax driver sessions for query execution.
3
4
## Capabilities
5
6
### Connection Information
7
8
Get connection details required for establishing DataStax driver sessions to the Cassandra container.
9
10
```java { .api }
11
/**
12
* Retrieve an InetSocketAddress for connecting to the Cassandra container via the driver.
13
* @return InetSocketAddress representation of this Cassandra container's host and port
14
*/
15
public InetSocketAddress getContactPoint();
16
17
/**
18
* Retrieve the Local Datacenter for connecting to the Cassandra container via the driver.
19
* @return The configured local Datacenter name (default: "datacenter1")
20
*/
21
public String getLocalDatacenter();
22
```
23
24
**Usage Examples:**
25
26
```java
27
import org.testcontainers.cassandra.CassandraContainer;
28
import com.datastax.oss.driver.api.core.CqlSession;
29
import java.net.InetSocketAddress;
30
31
try (CassandraContainer cassandra = new CassandraContainer("cassandra:3.11.2")) {
32
cassandra.start();
33
34
// Get connection information
35
InetSocketAddress contactPoint = cassandra.getContactPoint();
36
String datacenter = cassandra.getLocalDatacenter();
37
38
// Create DataStax driver 4.x session
39
CqlSession session = CqlSession.builder()
40
.addContactPoint(contactPoint)
41
.withLocalDatacenter(datacenter)
42
.build();
43
44
// Use session for queries
45
ResultSet result = session.execute("SELECT release_version FROM system.local");
46
session.close();
47
}
48
```
49
50
### Authentication Credentials
51
52
Access default authentication credentials for Cassandra connections when authentication is enabled.
53
54
```java { .api }
55
/**
56
* Get username.
57
* By default, Cassandra has authenticator: AllowAllAuthenticator in cassandra.yaml.
58
* If username and password need to be used, then authenticator should be set as PasswordAuthenticator
59
* (through custom Cassandra configuration) and through CQL with default cassandra-cassandra credentials
60
* user management should be modified.
61
* @return Default username ("cassandra")
62
*/
63
public String getUsername();
64
65
/**
66
* Get password.
67
* By default, Cassandra has authenticator: AllowAllAuthenticator in cassandra.yaml.
68
* If username and password need to be used, then authenticator should be set as PasswordAuthenticator
69
* (through custom Cassandra configuration) and through CQL with default cassandra-cassandra credentials
70
* user management should be modified.
71
* @return Default password ("cassandra")
72
*/
73
public String getPassword();
74
```
75
76
**Usage Examples:**
77
78
```java
79
// Connection with authentication enabled
80
try (CassandraContainer cassandra = new CassandraContainer("cassandra:3.11.2")
81
.withConfigurationOverride("cassandra-auth-enabled")) {
82
cassandra.start();
83
84
// Create authenticated session
85
CqlSession session = CqlSession.builder()
86
.addContactPoint(cassandra.getContactPoint())
87
.withLocalDatacenter(cassandra.getLocalDatacenter())
88
.withAuthCredentials(cassandra.getUsername(), cassandra.getPassword())
89
.build();
90
91
// Execute queries with authentication
92
ResultSet result = session.execute("SELECT * FROM system_auth.roles");
93
session.close();
94
}
95
```
96
97
### DataStax Driver Integration Patterns
98
99
#### DataStax Driver 4.x (Recommended)
100
101
Modern driver integration using CqlSession builder pattern.
102
103
```java
104
import com.datastax.oss.driver.api.core.CqlSession;
105
import com.datastax.oss.driver.api.core.cql.ResultSet;
106
import com.datastax.oss.driver.api.core.cql.Row;
107
108
// Basic connection
109
CqlSession session = CqlSession.builder()
110
.addContactPoint(cassandra.getContactPoint())
111
.withLocalDatacenter(cassandra.getLocalDatacenter())
112
.build();
113
114
// Connection with authentication
115
CqlSession sessionAuth = CqlSession.builder()
116
.addContactPoint(cassandra.getContactPoint())
117
.withLocalDatacenter(cassandra.getLocalDatacenter())
118
.withAuthCredentials(cassandra.getUsername(), cassandra.getPassword())
119
.build();
120
121
// Execute queries
122
ResultSet resultSet = session.execute("SELECT release_version FROM system.local");
123
Row row = resultSet.one();
124
String version = row.getString("release_version");
125
```
126
127
#### Legacy DataStax Driver 3.x (Deprecated)
128
129
The deprecated container class provides methods for creating legacy Cluster objects.
130
131
```java { .api }
132
/**
133
* Get configured Cluster for DataStax driver 3.x
134
* @deprecated For Cassandra driver 3.x, use getHost() and getMappedPort(int) with
135
* the driver's Cluster.Builder addContactPoint(String) and withPort(int) methods.
136
* For Cassandra driver 4.x, use getContactPoint() and getLocalDatacenter() with
137
* the driver's CqlSession.builder() methods.
138
* @return Configured Cluster object
139
*/
140
@Deprecated
141
public Cluster getCluster();
142
143
/**
144
* Static method for creating Cluster with custom JMX reporting setting
145
* @param containerState Container state for connection info
146
* @param enableJmxReporting Whether to enable JMX reporting
147
* @return Configured Cluster object
148
*/
149
@Deprecated
150
public static Cluster getCluster(ContainerState containerState, boolean enableJmxReporting);
151
```
152
153
### Connection Helper Methods
154
155
For manual driver configuration when needed.
156
157
```java
158
// Get individual connection components
159
String host = cassandra.getHost(); // Container host
160
Integer port = cassandra.getMappedPort(9042); // Mapped CQL port
161
String datacenter = cassandra.getLocalDatacenter(); // Datacenter name
162
163
// Manual session creation
164
CqlSession session = CqlSession.builder()
165
.addContactPoint(new InetSocketAddress(host, port))
166
.withLocalDatacenter(datacenter)
167
.build();
168
```
169
170
### Connection Testing Patterns
171
172
#### Basic Connection Test
173
174
```java
175
@Test
176
public void testCassandraConnection() {
177
try (CassandraContainer cassandra = new CassandraContainer("cassandra:3.11.2")) {
178
cassandra.start();
179
180
CqlSession session = CqlSession.builder()
181
.addContactPoint(cassandra.getContactPoint())
182
.withLocalDatacenter(cassandra.getLocalDatacenter())
183
.build();
184
185
ResultSet result = session.execute("SELECT release_version FROM system.local");
186
assertThat(result.wasApplied()).isTrue();
187
assertThat(result.one().getString(0)).isNotNull();
188
189
session.close();
190
}
191
}
192
```
193
194
#### Connection with Schema Operations
195
196
```java
197
@Test
198
public void testSchemaOperations() {
199
try (CassandraContainer cassandra = new CassandraContainer("cassandra:3.11.2")) {
200
cassandra.start();
201
202
CqlSession session = CqlSession.builder()
203
.addContactPoint(cassandra.getContactPoint())
204
.withLocalDatacenter(cassandra.getLocalDatacenter())
205
.build();
206
207
// Create keyspace
208
session.execute("CREATE KEYSPACE test WITH replication = " +
209
"{'class': 'SimpleStrategy', 'replication_factor': 1}");
210
211
// Create table
212
session.execute("CREATE TABLE test.users (id uuid PRIMARY KEY, name text)");
213
214
// Insert data
215
session.execute("INSERT INTO test.users (id, name) VALUES (uuid(), 'John')");
216
217
// Query data
218
ResultSet result = session.execute("SELECT name FROM test.users");
219
assertThat(result.one().getString("name")).isEqualTo("John");
220
221
session.close();
222
}
223
}
224
```
225
226
### Error Handling
227
228
Common connection-related exceptions and handling patterns:
229
230
```java
231
import com.datastax.oss.driver.api.core.AllNodesFailedException;
232
import com.datastax.oss.driver.api.core.DriverException;
233
234
try {
235
CqlSession session = CqlSession.builder()
236
.addContactPoint(cassandra.getContactPoint())
237
.withLocalDatacenter(cassandra.getLocalDatacenter())
238
.build();
239
} catch (AllNodesFailedException e) {
240
// No nodes available - container may not be ready
241
logger.error("Failed to connect to Cassandra", e);
242
} catch (DriverException e) {
243
// General driver error
244
logger.error("Cassandra driver error", e);
245
}
246
```