Class SessionBuilder<SelfT extends SessionBuilder,​SessionT>

  • Direct Known Subclasses:
    CqlSessionBuilder, DseSessionBuilder

    @NotThreadSafe
    public abstract class SessionBuilder<SelfT extends SessionBuilder,​SessionT>
    extends Object
    Base implementation to build session instances.

    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.

    • Constructor Detail

      • SessionBuilder

        public SessionBuilder()
    • Method Detail

      • withConfigLoader

        @NonNull
        public SelfT withConfigLoader​(@Nullable
                                      DriverConfigLoader configLoader)
        Sets the configuration loader to use.

        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):

        • system properties
        • 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.
        The resulting configuration is expected to contain a datastax-java-driver section.

        This default loader will honor the reload interval defined by the option basic.config-reload-interval.

        See Also:
        Typesafe config's standard loading behavior
      • addContactPoints

        @NonNull
        public SelfT addContactPoints​(@NonNull
                                      Collection<InetSocketAddress> contactPoints)
        Adds contact points to use for the initial connection to the cluster.

        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).

      • addContactEndPoints

        @NonNull
        public SelfT addContactEndPoints​(@NonNull
                                         Collection<EndPoint> contactPoints)
        Adds contact points to use for the initial connection to the cluster.

        You only need this method if you use a custom EndPoint implementation. Otherwise, use addContactPoints(Collection).

      • addContactEndPoint

        @NonNull
        public SelfT addContactEndPoint​(@NonNull
                                        EndPoint contactPoint)
        Adds a contact point to use for the initial connection to the cluster.

        You only need this method if you use a custom EndPoint implementation. Otherwise, use addContactPoint(InetSocketAddress).

      • addTypeCodecs

        @NonNull
        public SelfT addTypeCodecs​(@NonNull
                                   TypeCodec<?>... typeCodecs)
        Registers additional codecs for custom type mappings.
        Parameters:
        typeCodecs - neither the individual codecs, nor the vararg array itself, can be null.
      • withNodeStateListener

        @NonNull
        public SelfT withNodeStateListener​(@Nullable
                                           NodeStateListener nodeStateListener)
        Registers a node state listener to use with the session.

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

        This method unregisters any previously-registered listener. If you intend to register more than one listener, use addNodeStateListener(NodeStateListener) instead.

      • addNodeStateListener

        @NonNull
        public SelfT addNodeStateListener​(@NonNull
                                          NodeStateListener nodeStateListener)
        Registers a node state listener to use with the session, without removing previously-registered listeners.

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

        Unlike withNodeStateListener(NodeStateListener), this method adds the new listener to the list of already-registered listeners, thus allowing applications to register multiple listeners. When multiple listeners are registered, they are notified in sequence every time a new listener event is triggered.

      • withSchemaChangeListener

        @NonNull
        public SelfT withSchemaChangeListener​(@Nullable
                                              SchemaChangeListener schemaChangeListener)
        Registers a schema change listener to use with the session.

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

        This method unregisters any previously-registered listener. If you intend to register more than one listener, use addSchemaChangeListener(SchemaChangeListener) instead.

      • addSchemaChangeListener

        @NonNull
        public SelfT addSchemaChangeListener​(@NonNull
                                             SchemaChangeListener schemaChangeListener)
        Registers a schema change listener to use with the session, without removing previously-registered listeners.

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

        Unlike withSchemaChangeListener(SchemaChangeListener), this method adds the new listener to the list of already-registered listeners, thus allowing applications to register multiple listeners. When multiple listeners are registered, they are notified in sequence every time a new listener event is triggered.

      • withRequestTracker

        @NonNull
        public SelfT withRequestTracker​(@Nullable
                                        RequestTracker requestTracker)
        Registers a request tracker to use with the session.

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

        This method unregisters any previously-registered tracker. If you intend to register more than one tracker, use addRequestTracker(RequestTracker) instead.

      • addRequestTracker

        @NonNull
        public SelfT addRequestTracker​(@NonNull
                                       RequestTracker requestTracker)
        Registers a request tracker to use with the session, without removing previously-registered trackers.

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

        Unlike withRequestTracker(RequestTracker), this method adds the new tracker to the list of already-registered trackers, thus allowing applications to register multiple trackers. When multiple trackers are registered, they are notified in sequence every time a new tracker event is triggered.

      • withRequestIdGenerator

        @NonNull
        public SelfT withRequestIdGenerator​(@NonNull
                                            RequestIdGenerator requestIdGenerator)
        Registers a request ID generator. The driver will use the generated ID in the logs and optionally add to the custom payload so that users can correlate logs about the same request from the Cassandra side.
      • withAuthProvider

        @NonNull
        public SelfT withAuthProvider​(@Nullable
                                      AuthProvider authProvider)
        Registers an authentication provider to use with the session.

        If the provider is specified programmatically with this method, it overrides the configuration (that is, the advanced.auth-provider.class option will be ignored).

      • withAuthCredentials

        @NonNull
        public SelfT withAuthCredentials​(@NonNull
                                         String username,
                                         @NonNull
                                         String password)
        Configures the session to use plaintext authentication with the given username and 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).

      • withAuthCredentials

        @NonNull
        public SelfT withAuthCredentials​(@NonNull
                                         String username,
                                         @NonNull
                                         String password,
                                         @NonNull
                                         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.

        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).

      • withSslEngineFactory

        @NonNull
        public SelfT withSslEngineFactory​(@Nullable
                                          SslEngineFactory sslEngineFactory)
        Registers an SSL engine factory for the session.

        If the factory is provided programmatically with this method, it overrides the configuration (that is, the advanced.ssl-engine-factory option will be ignored).

        See Also:
        ProgrammaticSslEngineFactory
      • withLocalDatacenter

        public SelfT withLocalDatacenter​(@NonNull
                                         String profileName,
                                         @NonNull
                                         String localDatacenter)
        Specifies the datacenter that is considered "local" by the load balancing policy.

        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.

      • withNodeDistanceEvaluator

        @NonNull
        public SelfT withNodeDistanceEvaluator​(@NonNull
                                               String profileName,
                                               @NonNull
                                               NodeDistanceEvaluator nodeDistanceEvaluator)
        Adds a custom NodeDistanceEvaluator for a particular execution profile. This assumes that you're also using a dedicated load balancing policy for that profile.

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

        If an evaluator is specified programmatically with this method, it overrides the configuration (that is, the load-balancing-policy.evaluator.class option will be ignored).

        See Also:
        withNodeDistanceEvaluator(NodeDistanceEvaluator)
      • withNodeFilter

        @Deprecated
        @NonNull
        public SelfT withNodeFilter​(@NonNull
                                    String profileName,
                                    @NonNull
                                    Predicate<Node> nodeFilter)
        Adds a custom filter to include/exclude nodes for a particular execution profile. This assumes that you're also using a dedicated load balancing policy for that profile.

        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 driver built-in load balancing policies. If you use a custom policy implementation, you'll need to explicitly invoke the filter.

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

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

        
         public class NodeFilterToDistanceEvaluatorAdapter implements NodeDistanceEvaluator {
        
           private final Predicate<Node> nodeFilter;
        
           public NodeFilterToDistanceEvaluatorAdapter(Predicate<Node> nodeFilter) {
             this.nodeFilter = nodeFilter;
           }
        
           public NodeDistance evaluateDistance(Node node, String localDc) {
             return nodeFilter.test(node) ? null : NodeDistance.IGNORED;
           }
         }
         
        The same can be achieved using a lambda + closure:
        
         Predicate<Node> nodeFilter = ...
         NodeDistanceEvaluator evaluator =
           (node, localDc) -> nodeFilter.test(node) ? null : NodeDistance.IGNORED;
         
        See Also:
        withNodeFilter(Predicate)
      • withKeyspace

        @NonNull
        public SelfT withKeyspace​(@Nullable
                                  CqlIdentifier keyspace)
        Sets the keyspace to connect the session to.

        Note that this can also be provided by the configuration; if both are defined, this method takes precedence.

      • withClassLoader

        @NonNull
        public SelfT withClassLoader​(@Nullable
                                     ClassLoader classLoader)
        The 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:

        1. When reflectively loading class names defined in configuration: same class loader that loaded the core driver classes.
        2. When locating application-specific configuration resources: the current thread's context class loader.
        This is generally the right thing to do.

        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.

      • withCloudSecureConnectBundle

        @NonNull
        public SelfT withCloudSecureConnectBundle​(@NonNull
                                                  Path cloudConfigPath)
        Configures this SessionBuilder for Cloud deployments by retrieving connection information from the provided 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.

        Parameters:
        cloudConfigPath - Path to the secure connect bundle zip file.
        See Also:
        withCloudSecureConnectBundle(URL), withCloudSecureConnectBundle(InputStream)
      • withCodecRegistry

        @NonNull
        public SelfT withCodecRegistry​(@Nullable
                                       MutableCodecRegistry codecRegistry)
        Registers a CodecRegistry to use for the session.

        When both this and addTypeCodecs(TypeCodec[]) are called, the added type codecs will be registered on the provided CodecRegistry.

      • withCloudSecureConnectBundle

        @NonNull
        public SelfT withCloudSecureConnectBundle​(@NonNull
                                                  URL cloudConfigUrl)
        Configures this SessionBuilder for Cloud deployments by retrieving connection information from the provided 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.

        Parameters:
        cloudConfigUrl - URL to the secure connect bundle zip file.
        See Also:
        withCloudSecureConnectBundle(Path), withCloudSecureConnectBundle(InputStream)
      • withCloudSecureConnectBundle

        @NonNull
        public SelfT withCloudSecureConnectBundle​(@NonNull
                                                  InputStream cloudConfigInputStream)
        Configures this SessionBuilder for Cloud deployments by retrieving connection information from the provided 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.

        Parameters:
        cloudConfigInputStream - A stream containing the secure connect bundle zip file.
        See Also:
        withCloudSecureConnectBundle(Path), withCloudSecureConnectBundle(URL)
      • withCloudProxyAddress

        @NonNull
        public SelfT withCloudProxyAddress​(@Nullable
                                           InetSocketAddress cloudProxyAddress)
        Configures this SessionBuilder to use the provided Cloud proxy endpoint.

        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.

        Parameters:
        cloudProxyAddress - The address of the Cloud proxy to use.
        See Also:
        Server Name Indication
      • withClientRoutesConfig

        @NonNull
        public SelfT withClientRoutesConfig​(@Nullable
                                            ClientRoutesConfig clientRoutesConfig)
        Configures this session to use client routes for cloud private-endpoint deployments.

        Client routes enable the driver to discover and connect to nodes through a load balancer (such as AWS PrivateLink, Azure Private Link, or GCP Private Service Connect) by reading endpoint mappings from the system.client_routes table. Each endpoint is identified by a connection ID and maps to specific node addresses.

        This configuration is mutually exclusive with a user-provided AddressTranslator. If both are specified, an IllegalStateException is thrown when the session is built.

        Example usage:

        
         ClientRoutesConfig config = ClientRoutesConfig.builder()
             .addEndpoint(new ClientRouteProxy(
                 "12345678-1234-1234-1234-123456789012",
                 "my-cluster-endpoint.example.com"))
             .build();
        
         CqlSession session = CqlSession.builder()
             .withClientRoutesConfig(config)
             .build();
         
        Parameters:
        clientRoutesConfig - the client routes configuration to use, or null to disable client routes.
        See Also:
        ClientRoutesConfig
      • withClientId

        @NonNull
        public SelfT withClientId​(@Nullable
                                  UUID clientId)
        A unique identifier for the created session.

        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().

      • withApplicationName

        @NonNull
        public SelfT withApplicationName​(@Nullable
                                         String applicationName)
        The name of the application using the created session.

        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.

      • withApplicationVersion

        @NonNull
        public SelfT withApplicationVersion​(@Nullable
                                            String applicationVersion)
        The version of the application using the created session.

        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.

      • withMetricRegistry

        @NonNull
        public SelfT withMetricRegistry​(@Nullable
                                        Object metricRegistry)
        The metric registry object for storing driver metrics.

        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):

        • Dropwizard (the default): com.codahale.metrics.MetricRegistry
        • Micrometer: io.micrometer.core.instrument.MeterRegistry
        • MicroProfile: org.eclipse.microprofile.metrics.MetricRegistry
        Only MicroProfile requires an external instance of its registry to be provided. For Micrometer, if no Registry object is provided, Micrometer's globalRegistry will be used. For Dropwizard, if no Registry object is provided, an instance of MetricRegistry will be created and used.
      • buildAsync

        @NonNull
        public CompletionStage<SessionT> buildAsync()
        Creates the session with the options set by this builder.

        The session initialization will happen asynchronously in a driver internal thread pool.

        Returns:
        a completion stage that completes with the session when it is fully initialized.
      • build

        @NonNull
        public SessionT build()
        Convenience method to call 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.

      • buildContext

        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).