@NotThreadSafe public abstract class SessionBuilder<SelfT extends SessionBuilder,SessionT> extends Object
You only need to deal with this directly if you use custom driver extensions. For the default
session implementation, see CqlSession.builder()
.
This class is mutable and not thread-safe.
Modifier and Type | Field and Description |
---|---|
protected Callable<InputStream> |
cloudConfigInputStream |
protected DriverConfigLoader |
configLoader |
protected CqlIdentifier |
keyspace |
protected ProgrammaticArguments.Builder |
programmaticArgumentsBuilder |
protected Set<EndPoint> |
programmaticContactPoints |
protected SelfT |
self |
Constructor and Description |
---|
SessionBuilder() |
Modifier and Type | Method and Description |
---|---|
SelfT |
addContactEndPoint(EndPoint contactPoint)
Adds a contact point to use for the initial connection to the cluster.
|
SelfT |
addContactEndPoints(Collection<EndPoint> contactPoints)
Adds contact points to use for the initial connection to the cluster.
|
SelfT |
addContactPoint(InetSocketAddress contactPoint)
Adds a contact point to use for the initial connection to the cluster.
|
SelfT |
addContactPoints(Collection<InetSocketAddress> contactPoints)
Adds contact points to use for the initial connection to the cluster.
|
SelfT |
addTypeCodecs(TypeCodec<?>... typeCodecs)
Registers additional codecs for custom type mappings.
|
SessionT |
build()
Convenience method to call
buildAsync() and block on the result. |
CompletionStage<SessionT> |
buildAsync()
Creates the session with the options set by this builder.
|
protected DriverContext |
buildContext(DriverConfigLoader configLoader,
List<TypeCodec<?>> typeCodecs,
NodeStateListener nodeStateListener,
SchemaChangeListener schemaChangeListener,
RequestTracker requestTracker,
Map<String,String> localDatacenters,
Map<String,Predicate<Node>> nodeFilters,
ClassLoader classLoader)
Deprecated.
this method only exists for backward compatibility (if a subclass written for
driver 4.1.0 returns a non-null result, that value will be used). Please override
buildContext(DriverConfigLoader, ProgrammaticArguments) instead. |
protected DriverContext |
buildContext(DriverConfigLoader configLoader,
ProgrammaticArguments programmaticArguments)
This must return an instance of
InternalDriverContext (it's not expressed
directly in the signature to avoid leaking that type through the protected API). |
protected CompletionStage<CqlSession> |
buildDefaultSessionAsync() |
protected DriverConfigLoader |
defaultConfigLoader()
Deprecated.
|
protected DriverConfigLoader |
defaultConfigLoader(ClassLoader classLoader) |
SelfT |
withApplicationName(String applicationName)
The name of the application using the created session.
|
SelfT |
withApplicationVersion(String applicationVersion)
The version of the application using the created session.
|
SelfT |
withAuthCredentials(String username,
String password)
Configures the session to use plaintext authentication with the given username and password.
|
SelfT |
withAuthCredentials(String username,
String password,
String authorizationId)
Configures the session to use DSE plaintext authentication with the given username and
password, and perform proxy authentication with the given authorization id.
|
SelfT |
withAuthProvider(AuthProvider authProvider)
Registers an authentication provider to use with the session.
|
SelfT |
withClassLoader(ClassLoader classLoader)
The
ClassLoader to use to reflectively load class names defined in configuration. |
SelfT |
withClientId(UUID clientId)
A unique identifier for the created session.
|
SelfT |
withCloudProxyAddress(InetSocketAddress cloudProxyAddress)
Configures this SessionBuilder to use the provided Cloud proxy endpoint.
|
SelfT |
withCloudSecureConnectBundle(InputStream cloudConfigInputStream)
Configures this SessionBuilder for Cloud deployments by retrieving connection information from
the provided
InputStream . |
SelfT |
withCloudSecureConnectBundle(Path cloudConfigPath)
Configures this SessionBuilder for Cloud deployments by retrieving connection information from
the provided
Path . |
SelfT |
withCloudSecureConnectBundle(URL cloudConfigUrl)
Configures this SessionBuilder for Cloud deployments by retrieving connection information from
the provided
URL . |
SelfT |
withCodecRegistry(MutableCodecRegistry codecRegistry)
Registers a CodecRegistry to use for the session.
|
SelfT |
withConfigLoader(DriverConfigLoader configLoader)
Sets the configuration loader to use.
|
SelfT |
withCredentials(String username,
String password)
Deprecated.
this method only exists to ease the transition from driver 3, it is an alias for
withAuthCredentials(String, String) . |
SelfT |
withCredentials(String username,
String password,
String authorizationId)
Deprecated.
this method only exists to ease the transition from driver 3, it is an alias for
withAuthCredentials(String, String,String) . |
SelfT |
withKeyspace(CqlIdentifier keyspace)
Sets the keyspace to connect the session to.
|
SelfT |
withKeyspace(String keyspaceName)
Shortcut for
setKeyspace(CqlIdentifier.fromCql(keyspaceName)) |
SelfT |
withLocalDatacenter(String localDatacenter)
Alias to
withLocalDatacenter(String, String) for the default profile. |
SelfT |
withLocalDatacenter(String profileName,
String localDatacenter)
Specifies the datacenter that is considered "local" by the load balancing policy.
|
SelfT |
withMetricRegistry(Object metricRegistry)
The metric registry object for storing driver metrics.
|
SelfT |
withNodeFilter(Predicate<Node> nodeFilter)
Alias to
withNodeFilter(String, Predicate) for the default profile. |
SelfT |
withNodeFilter(String profileName,
Predicate<Node> nodeFilter)
Adds a custom filter to include/exclude nodes for a particular execution profile.
|
SelfT |
withNodeStateListener(NodeStateListener nodeStateListener)
Registers a node state listener to use with the session.
|
SelfT |
withRequestTracker(RequestTracker requestTracker)
Registers a request tracker to use with the session.
|
SelfT |
withSchemaChangeListener(SchemaChangeListener schemaChangeListener)
Registers a schema change listener to use with the session.
|
SelfT |
withSslContext(SSLContext sslContext)
Configures the session to use SSL with the given context.
|
SelfT |
withSslEngineFactory(SslEngineFactory sslEngineFactory)
Registers an SSL engine factory for the session.
|
protected abstract SessionT |
wrap(CqlSession defaultSession) |
protected final SelfT extends SessionBuilder self
protected DriverConfigLoader configLoader
protected CqlIdentifier keyspace
protected Callable<InputStream> cloudConfigInputStream
protected ProgrammaticArguments.Builder programmaticArgumentsBuilder
@NonNull public SelfT withConfigLoader(@Nullable DriverConfigLoader configLoader)
If you don't call this method, the builder will use the default implementation, based on the Typesafe config library. More precisely, configuration properties are loaded and merged from the following (first-listed are higher priority):
application.conf
(all resources on classpath with this name)
application.json
(all resources on classpath with this name)
application.properties
(all resources on classpath with this name)
reference.conf
(all resources on classpath with this name). In particular, this
will load the reference.conf
included in the core driver JAR, that defines
default options for all mandatory options.
datastax-java-driver
section.
This default loader will honor the reload interval defined by the option basic.config-reload-interval
.
@NonNull @Deprecated protected DriverConfigLoader defaultConfigLoader()
@NonNull protected DriverConfigLoader defaultConfigLoader(@Nullable ClassLoader classLoader)
@NonNull public SelfT addContactPoints(@NonNull Collection<InetSocketAddress> contactPoints)
These are addresses of Cassandra nodes that the driver uses to discover the cluster topology. Only one contact point is required (the driver will retrieve the address of the other nodes automatically), but it is usually a good idea to provide more than one contact point, because if that single contact point is unavailable, the driver cannot initialize itself correctly.
Contact points can also be provided statically in the configuration. If both are specified, they will be merged. If both are absent, the driver will default to 127.0.0.1:9042.
Contrary to the configuration, DNS names with multiple A-records will not be handled here.
If you need that, extract them manually with InetAddress.getAllByName(String)
before calling this method. Similarly, if you need connect addresses to stay unresolved, make
sure you pass unresolved instances here (see advanced.resolve-contact-points
in the
configuration for more explanations).
@NonNull public SelfT addContactPoint(@NonNull InetSocketAddress contactPoint)
addContactPoints(Collection)
@NonNull public SelfT addContactEndPoints(@NonNull Collection<EndPoint> contactPoints)
You only need this method if you use a custom EndPoint
implementation. Otherwise,
use addContactPoints(Collection)
.
@NonNull public SelfT addContactEndPoint(@NonNull EndPoint contactPoint)
You only need this method if you use a custom EndPoint
implementation. Otherwise,
use addContactPoint(InetSocketAddress)
.
@NonNull public SelfT addTypeCodecs(@NonNull TypeCodec<?>... typeCodecs)
typeCodecs
- neither the individual codecs, nor the vararg array itself, can be null
.@NonNull public SelfT withNodeStateListener(@Nullable NodeStateListener nodeStateListener)
If the listener is specified programmatically with this method, it overrides the
configuration (that is, the metadata.node-state-listener.class
option will be ignored).
@NonNull public SelfT withSchemaChangeListener(@Nullable SchemaChangeListener schemaChangeListener)
If the listener is specified programmatically with this method, it overrides the
configuration (that is, the metadata.schema-change-listener.class
option will be
ignored).
@NonNull public SelfT withRequestTracker(@Nullable RequestTracker requestTracker)
If the tracker is specified programmatically with this method, it overrides the
configuration (that is, the request.tracker.class
option will be ignored).
@NonNull public SelfT withAuthProvider(@Nullable AuthProvider authProvider)
If the provider is specified programmatically with this method, it overrides the
configuration (that is, the advanced.auth-provider.class
option will be ignored).
@NonNull public SelfT withAuthCredentials(@NonNull String username, @NonNull String password)
This methods calls withAuthProvider(AuthProvider)
to register a special provider
implementation. Therefore calling it overrides the configuration (that is, the advanced.auth-provider.class
option will be ignored).
Note that this approach holds the credentials in clear text in memory, which makes them
vulnerable to an attacker who is able to perform memory dumps. If this is not acceptable for
you, consider writing your own AuthProvider
implementation (PlainTextAuthProviderBase
is a good starting point), and providing it either with withAuthProvider(AuthProvider)
or via the configuration (advanced.auth-provider.class
).
@NonNull public SelfT withAuthCredentials(@NonNull String username, @NonNull String password, @NonNull String authorizationId)
This feature is only available in Datastax Enterprise. If connecting to Apache Cassandra,
the authorization id will be ignored; it is recommended to use withAuthCredentials(String, String)
instead.
This methods calls withAuthProvider(AuthProvider)
to register a special provider
implementation. Therefore calling it overrides the configuration (that is, the advanced.auth-provider.class
option will be ignored).
Note that this approach holds the credentials in clear text in memory, which makes them
vulnerable to an attacker who is able to perform memory dumps. If this is not acceptable for
you, consider writing your own AuthProvider
implementation (the internal class PlainTextAuthProviderBase
is a good starting point), and providing it either with withAuthProvider(AuthProvider)
or via the configuration (advanced.auth-provider.class
).
@Deprecated @NonNull public SelfT withCredentials(@NonNull String username, @NonNull String password)
withAuthCredentials(String, String)
.@Deprecated @NonNull public SelfT withCredentials(@NonNull String username, @NonNull String password, @NonNull String authorizationId)
withAuthCredentials(String, String,String)
.@NonNull public SelfT withSslEngineFactory(@Nullable SslEngineFactory sslEngineFactory)
If the factory is provided programmatically with this method, it overrides the configuration
(that is, the advanced.ssl-engine-factory
option will be ignored).
ProgrammaticSslEngineFactory
@NonNull public SelfT withSslContext(@Nullable SSLContext sslContext)
This is a convenience method for clients that already have an SSLContext
instance.
It wraps its argument into a ProgrammaticSslEngineFactory
, and passes it to withSslEngineFactory(SslEngineFactory)
.
If you use this method, there is no way to customize cipher suites, or turn on host name
validation. If you need finer control, use withSslEngineFactory(SslEngineFactory)
directly and pass either your own implementation of SslEngineFactory
, or a ProgrammaticSslEngineFactory
created with custom cipher suites and/or host name validation.
Also, note that SSL engines will be created with advisory peer information (SSLContext.createSSLEngine(String, int)
) whenever possible.
public SelfT withLocalDatacenter(@NonNull String profileName, @NonNull String localDatacenter)
This is a programmatic alternative to the configuration option basic.load-balancing-policy.local-datacenter
. If this method is used, it takes precedence and
overrides the configuration.
Note that this setting may or may not be relevant depending on the load balancing policy
implementation in use. The driver's built-in DefaultLoadBalancingPolicy
relies on it;
if you use a third-party implementation, refer to their documentation.
public SelfT withLocalDatacenter(@NonNull String localDatacenter)
withLocalDatacenter(String, String)
for the default profile.@NonNull public SelfT withNodeFilter(@NonNull String profileName, @NonNull Predicate<Node> nodeFilter)
The predicate's test()
method will be invoked each time the
LoadBalancingPolicy
processes a topology or state change: if it returns false, the
policy will suggest distance IGNORED (meaning the driver won't ever connect to it if all
policies agree), and never included in any query plan.
Note that this behavior is implemented in the default load balancing policy. If you use a custom policy implementation, you'll need to explicitly invoke the filter.
If the filter is specified programmatically with this method, it overrides the configuration
(that is, the load-balancing-policy.filter.class
option will be ignored).
withNodeFilter(Predicate)
@NonNull public SelfT withNodeFilter(@NonNull Predicate<Node> nodeFilter)
withNodeFilter(String, Predicate)
for the default profile.@NonNull public SelfT withKeyspace(@Nullable CqlIdentifier keyspace)
Note that this can also be provided by the configuration; if both are defined, this method takes precedence.
@NonNull public SelfT withKeyspace(@Nullable String keyspaceName)
setKeyspace(CqlIdentifier.fromCql(keyspaceName))
@NonNull public SelfT withClassLoader(@Nullable ClassLoader classLoader)
ClassLoader
to use to reflectively load class names defined in configuration.
Unless you define a custom configLoader
, this class loader will also be used to
locate application-specific configuration resources.
If you do not provide any custom class loader, the driver will attempt to use the following ones:
Defining a different class loader is typically only needed in web or OSGi environments where there are complex class loading requirements.
For example, if the driver jar is loaded by the web server's system class loader (that is,
the driver jar was placed in the "/lib" folder of the web server), but the application tries to
load a custom load balancing policy declared in the web app's "WEB-INF/lib" folder, the system
class loader will not be able to load such class. Instead, you must use the web app's class
loader, that you can obtain by calling Thread.getContextClassLoader()
:
CqlSession.builder()
.addContactEndPoint(...)
.withClassLoader(Thread.currentThread().getContextClassLoader())
.build();
Indeed, in most web environments, Thread.currentThread().getContextClassLoader()
will
return the web app's class loader, which is a child of the web server's system class loader.
This class loader is thus capable of loading both the implemented interface and the
implementing class, in spite of them being declared in different places.
For OSGi deployments, it is usually not necessary to use this method. Even if the
implemented interface and the implementing class are located in different bundles, the right
class loader to use should be the default one (the driver bundle's class loader). In
particular, it is not advised to rely on Thread.currentThread().getContextClassLoader()
in OSGi environments, so you should never pass that class loader to this method. See Using
a custom ClassLoader in our OSGi online docs for more information.
@NonNull public SelfT withCloudSecureConnectBundle(@NonNull Path cloudConfigPath)
Path
.
To connect to a Cloud database, you must first download the secure database bundle from the DataStax Astra console that contains the connection information, then instruct the driver to read its contents using either this method or one if its variants.
For more information, please refer to the DataStax Astra documentation.
cloudConfigPath
- Path to the secure connect bundle zip file.withCloudSecureConnectBundle(URL)
,
withCloudSecureConnectBundle(InputStream)
@NonNull public SelfT withCodecRegistry(@Nullable MutableCodecRegistry codecRegistry)
When both this and addTypeCodecs(TypeCodec[])
are called, the added type codecs
will be registered on the provided CodecRegistry.
@NonNull public SelfT withCloudSecureConnectBundle(@NonNull URL cloudConfigUrl)
URL
.
To connect to a Cloud database, you must first download the secure database bundle from the DataStax Astra console that contains the connection information, then instruct the driver to read its contents using either this method or one if its variants.
For more information, please refer to the DataStax Astra documentation.
cloudConfigUrl
- URL to the secure connect bundle zip file.withCloudSecureConnectBundle(Path)
,
withCloudSecureConnectBundle(InputStream)
@NonNull public SelfT withCloudSecureConnectBundle(@NonNull InputStream cloudConfigInputStream)
InputStream
.
To connect to a Cloud database, you must first download the secure database bundle from the DataStax Astra console that contains the connection information, then instruct the driver to read its contents using either this method or one if its variants.
For more information, please refer to the DataStax Astra documentation.
Note that the provided stream will be consumed and closed when either build()
or buildAsync()
are called; attempting to reuse it afterwards will result in
an error being thrown.
cloudConfigInputStream
- A stream containing the secure connect bundle zip file.withCloudSecureConnectBundle(Path)
,
withCloudSecureConnectBundle(URL)
@NonNull public SelfT withCloudProxyAddress(@Nullable InetSocketAddress cloudProxyAddress)
Normally, this method should not be called directly; the normal and easiest way to configure the driver for Cloud deployments is through a secure connect bundle.
Setting this option to any non-null address will make the driver use a special topology monitor tailored for Cloud deployments. This topology monitor assumes that the target cluster should be contacted through the proxy specified here, using SNI routing.
For more information, please refer to the DataStax Astra documentation.
cloudProxyAddress
- The address of the Cloud proxy to use.@NonNull public SelfT withClientId(@Nullable UUID clientId)
It will be sent in the STARTUP
protocol message, under the key CLIENT_ID
,
for each new connection established by the driver. Currently, this information is used by
Insights monitoring (if the target cluster does not support Insights, the entry will be ignored
by the server).
If you don't call this method, the driver will generate an identifier with Uuids.random()
.
@NonNull public SelfT withApplicationName(@Nullable String applicationName)
It will be sent in the STARTUP
protocol message, under the key APPLICATION_NAME
, for each new connection established by the driver. Currently, this
information is used by Insights monitoring (if the target cluster does not support Insights,
the entry will be ignored by the server).
This can also be defined in the driver configuration with the option basic.application.name
; if you specify both, this method takes precedence and the
configuration option will be ignored. If neither is specified, the entry is not included in the
message.
@NonNull public SelfT withApplicationVersion(@Nullable String applicationVersion)
It will be sent in the STARTUP
protocol message, under the key APPLICATION_VERSION
, for each new connection established by the driver. Currently, this
information is used by Insights monitoring (if the target cluster does not support Insights,
the entry will be ignored by the server).
This can also be defined in the driver configuration with the option basic.application.version
; if you specify both, this method takes precedence and the
configuration option will be ignored. If neither is specified, the entry is not included in the
message.
@NonNull public SelfT withMetricRegistry(@Nullable Object metricRegistry)
The argument should be an instance of the base registry type for the metrics framework you
are using (see advanced.metrics.factory.class
in the configuration):
com.codahale.metrics.MetricRegistry
io.micrometer.core.instrument.MeterRegistry
org.eclipse.microprofile.metrics.MetricRegistry
globalRegistry
will be
used. For Dropwizard, if no Registry object is provided, an instance of MetricRegistry
will be created and used.@NonNull public CompletionStage<SessionT> buildAsync()
The session initialization will happen asynchronously in a driver internal thread pool.
@NonNull public SessionT build()
buildAsync()
and block on the result.
Usage in non-blocking applications: beware that session initialization is a costly
operation. It should only be triggered from a thread that is allowed to block. If that is not
the case, consider using buildAsync()
instead.
This must not be called on a driver thread.
protected abstract SessionT wrap(@NonNull CqlSession defaultSession)
@NonNull protected final CompletionStage<CqlSession> buildDefaultSessionAsync()
protected DriverContext buildContext(DriverConfigLoader configLoader, ProgrammaticArguments programmaticArguments)
InternalDriverContext
(it's not expressed
directly in the signature to avoid leaking that type through the protected API).@Deprecated protected DriverContext buildContext(DriverConfigLoader configLoader, List<TypeCodec<?>> typeCodecs, NodeStateListener nodeStateListener, SchemaChangeListener schemaChangeListener, RequestTracker requestTracker, Map<String,String> localDatacenters, Map<String,Predicate<Node>> nodeFilters, ClassLoader classLoader)
buildContext(DriverConfigLoader, ProgrammaticArguments)
instead.Copyright © 2017–2024. All rights reserved.