Interface SessionFactory


public interface SessionFactory
Factory for client sessions.

Each instance is immutable, and has a number of session attributes that determine how sessions should be established. An initial instance of this factory with default values for all attributes can be obtained from Diffusion.sessions(). Methods such as inputBufferSize(int) or maximumMessageSize(int) that allow attributes to be changed do not modify this instance. Each method returns a copy of this factory, with a single changed attribute.

Establishing a session

A new session can be created using openAsync(String) specifying a URL that identifies the server. This is a non-blocking method that returns immediately, and provides the result asynchronously using a CompletableFuture.

open(String) is a blocking alternative to openAsync that waits for a session to be established before returning.

The overloaded methods openAsync() or open() use the session factory attributes to locate a server rather than a URL. The server is identified by the serverHost(String) and serverPort(int), requestPath(String), secureTransport(boolean) attributes. The transports(SessionAttributes.Transport...) attributes allows the configuration of multiple transports for cascading.

If a URL is specified, it takes precedence over the serverHost, serverPort, requestPath, and secureTransport session factory attributes. A URL can only be used to configure a single transport and cannot be used to configure cascading, so the transports attribute is ignored.

URL format

URLs should take the form scheme://host:port, where scheme is chosen from the following table and determines the transport protocol used to send Diffusion messages.

Scheme Transport Protocol
ws WebSocket. See RFC 6455 .
wss WebSocket over TLS.
xhr HTTP polling.
xhrs HTTP polling over TLS.

We recommend using the WebSocket protocol options (ws or wss).

TLS is Transport Layer Security, commonly known as SSL. TLS-based protocols use cryptography to provide transport-level privacy, authentication, and integrity, and protects against network-sniffing and man-in-the-middle attacks. We recommend using the TLS variants for all communication. For a typical application, you should only consider not using TLS for unauthenticated ("anonymous") client sessions.

Since:
5.0
Author:
DiffusionData Limited
  • Method Details

    • listener

      SessionFactory listener(Session.Listener listener)
      Nominates a listener for session events from a session.

      If not specified, there will be no session listener.

      Parameters:
      listener - specifies a listener to be used for subsequent sessions that are created. Null may be specified to remove any previously specified listener
      Returns:
      a new immutable instance of the factory with the listener changed
    • errorHandler

      SessionFactory errorHandler(Session.ErrorHandler errorHandler)
      Nominates an error handler for a session.

      If not specified, an instance of Session.ErrorHandler.Default will be used.

      Parameters:
      errorHandler - specifies the error handler to use for subsequent sessions that are created. Null may be specified to remove any previously specified handler and effectively revert to using the default handler
      Returns:
      a new immutable instance of the factory with the error handler changed
    • principal

      SessionFactory principal(String principal)
      Sets the security principal.

      By default this will be Session.ANONYMOUS.

      Parameters:
      principal - the principal
      Returns:
      a new immutable instance of the factory with the principal changed
    • noCredentials

      SessionFactory noCredentials()
      Set credentials to Credentials.Type.NONE.

      This is the default.

      Returns:
      a new immutable instance of the factory with the credentials changed
    • credentials

      SessionFactory credentials(Credentials credentials)
      Set credentials.

      The default is Credentials.Type.NONE.

      Parameters:
      credentials - the credentials
      Returns:
      a new immutable instance of the factory with the credentials changed
    • password

      SessionFactory password(String password)
      Set credentials of type Credentials.Type.PLAIN_PASSWORD.

      The default is Credentials.Type.NONE.

      Parameters:
      password - the password
      Returns:
      a new immutable instance of the factory with the credentials changed
    • customCredentials

      SessionFactory customCredentials(byte[] bytes)
      Set credentials of type Credentials.Type.CUSTOM.

      The default is Credentials.Type.NONE.

      Parameters:
      bytes - the credentials
      Returns:
      a new immutable instance of the factory with the credentials changed
    • connectionTimeout

      SessionFactory connectionTimeout(int timeout) throws IllegalArgumentException
      Sets the connection timeout.

      This constrains the time taken to establish an initial connection to the server. The write timeout constrains the time to send the connection request. The server is responsible for limiting the overall time taken to complete a connection once it has received the request.

      The default is SessionAttributes.DEFAULT_CONNECTION_TIMEOUT.

      Parameters:
      timeout - the default connection timeout in milliseconds. If this exceeds one hour (3600000ms) a warning will be logged and the time-out will be set to one hour.
      Returns:
      a new immutable instance of the factory with the connection timeout changed
      Throws:
      IllegalArgumentException - if an illegal timeout value is supplied
    • noReconnection

      SessionFactory noReconnection()
      Disable reconnection. Sessions will not attempt to reconnect in the event of unexpected connection loss.

      This is equivalent to calling reconnectionTimeout(int) with a timeout of 0.

      Returns:
      a new immutable instance of the factory with reconnection disabled
      Since:
      5.5
    • initialRetryStrategy

      SessionFactory initialRetryStrategy(RetryStrategy strategy)
      Sets the initial retry strategy.

      The strategy will determine whether a failure to open a session due to a SessionEstablishmentTransientException should be retried and if so, at what interval and for how many attempts.

      If no initial retry strategy is set there will be no attempt to retry after such a failure.

      Parameters:
      strategy - the retry strategy to use
      Returns:
      a new immutable instance of the factory with the initial retry strategy changed
      Since:
      6.9
    • reconnectionTimeout

      SessionFactory reconnectionTimeout(int timeout) throws IllegalArgumentException
      Sets the reconnection timeout. This determines the duration that sessions will attempt to reconnect for, in the event of unexpected connection loss.

      The default is SessionAttributes.DEFAULT_RECONNECTION_TIMEOUT.

      A timeout value of 0 or less is equivalent to to calling noReconnection().

      Parameters:
      timeout - the timeout duration to use when attempting to reconnect, in milliseconds
      Returns:
      a new immutable instance of the factory with the reconnection timeout changed
      Throws:
      IllegalArgumentException - if an illegal timeout value is supplied
      Since:
      5.5
    • reconnectionStrategy

      SessionFactory reconnectionStrategy(ReconnectionStrategy strategy)
      Sets the reconnection strategy. If reconnection is enabled, this strategy will be called in the event of an unexpected connection loss.

      If the reconnection timeout has been set, but not a strategy, sessions will use a default strategy that attempts to reconnect on a regular basis of 5 seconds until the reconnection timeout is exceeded.

      Parameters:
      strategy - the reconnection strategy to use
      Returns:
      a new immutable instance of the factory with the reconnection strategy changed
      Since:
      5.5
    • inputBufferSize

      SessionFactory inputBufferSize(int size) throws IllegalArgumentException
      Sets the input buffer size for socket connection buffers and message receiving buffers.

      This controls both how much pending data the socket can accommodate and how much available data will be read by the input tasks. In general setting both this and outputBufferSize(int) to the same reasonable size will result in higher network throughput. The cost of the receiving buffer is only incurred when actually reading data for processing. The cost of the socket buffer is always incurred and may be modified by the operating system.

      The default is SessionAttributes.DEFAULT_INPUT_BUFFER_SIZE.

      Parameters:
      size - input buffer size in bytes. This may not be less than SessionAttributes.MAXIMUM_MESSAGE_SIZE_MIN.
      Returns:
      a new immutable instance of the factory with the input buffer size changed
      Throws:
      IllegalArgumentException - if the input buffer size is invalid
    • outputBufferSize

      SessionFactory outputBufferSize(int size) throws IllegalArgumentException
      Sets the output buffer size for socket connection buffers and message sending buffers.

      This controls both how much pending data the socket can accommodate and how much data will be batched by sending messages. In general setting both this and inputBufferSize(int) to the same reasonable size will result in higher network throughput. The cost of the sending buffer is only incurred when actually queuing data for output. The cost of the socket buffer is always incurred and may be modified by the operating system.

      The default is SessionAttributes.DEFAULT_OUTPUT_BUFFER_SIZE.

      Parameters:
      size - output buffer size in bytes.
      Returns:
      a new immutable instance of the factory with the output buffer size changed
      Throws:
      IllegalArgumentException - if the output buffer size is invalid
    • localSocketAddress

      SessionFactory localSocketAddress(SocketAddress address)
      Set the optional local socket address, used prior to connection.

      By default no local socket address is used.

      Parameters:
      address - the local socket address. Setting this to null effectively removes any previous setting
      Returns:
      a new immutable instance of the factory with the local socket address changed
    • sslContext

      SessionFactory sslContext(SSLContext context)
      Sets the SSL Context if a secure connection is required.

      If not explicitly supplied, the default context will be used.

      Setting the SSL Context will not enable transport layer security. It must also be specified by the URL or secureTransport(boolean).

      Parameters:
      context - the SSL Context to use when making the connection
      Returns:
      a new immutable instance of the factory with the SSL context changed
    • writeTimeout

      SessionFactory writeTimeout(int timeout) throws IllegalArgumentException
      Sets the write timeout value for blocking writes.

      Blocking writes are only used for the initial connection request. If it is not possible to complete the write within this time, the connection is closed.

      The default is SessionAttributes.DEFAULT_WRITE_TIMEOUT.

      Parameters:
      timeout - the write timeout in milliseconds. If this exceeds one hour (3600000ms) a warning will be logged and the time-out will be set to one hour.
      Returns:
      a new immutable instance of the factory with the write timeout changed
      Throws:
      IllegalArgumentException - if timeout is invalid
    • maximumMessageSize

      SessionFactory maximumMessageSize(int size) throws IllegalArgumentException
      Set the maximum message size.

      This constrains the size of messages that will be accepted from the server and thus the size of any content that can be received. The limit is simply to protect against unexpectedly large messages.

      By default, the size of received messages is unconstrained – see SessionAttributes.DEFAULT_MAXIMUM_MESSAGE_SIZE.

      Parameters:
      size - the maximum message size in bytes. This must not be less than SessionAttributes.MAXIMUM_MESSAGE_SIZE_MIN
      Returns:
      a new immutable instance of the factory with the maximum message size changed
      Throws:
      IllegalArgumentException - if the specified size is invalid
    • httpProxy

      SessionFactory httpProxy(String host, int port) throws IllegalArgumentException
      Set the address of the HTTP Proxy that should be used to make connections to the server.

      This allows connection to a server using HTTP CONNECT tunnelling through the specified proxy.

      Parameters:
      host - the host name of the HTTP proxy
      port - the port of the HTTP proxy
      Returns:
      a new immutable instance of the factory that will use the provided HTTP proxy
      Throws:
      IllegalArgumentException - if the specified host or port are invalid
      See Also:
    • httpProxy

      SessionFactory httpProxy(String host, int port, HTTPProxyAuthentication authentication) throws IllegalArgumentException
      A variant of httpProxy(String, int) that provides authentication details to the HTTP proxy.

      This allows connection to a server using HTTP CONNECT tunnelling through the specified proxy, with authentication.

      The authentication parameter only affects communication with the proxy, it is not passed on to the server. Diffusion.proxyAuthentication() and ProxyAuthenticationFactory can be used to create a suitable instance. For example, to specify HTTP BASIC authentication with a user name joe and password s3cret:

       HTTPProxyAuthentication authentication =
         Diffusion.proxyAuthentication().basic("joe", "s3cret")
       

      The principal(String) and credentials(Credentials) methods control authentication with the server and do not affect proxy authentication.

      Parameters:
      host - the host name of the HTTP proxy
      port - the port of the HTTP proxy
      authentication - the authentication details
      Returns:
      a new immutable instance of the factory that will use the provided HTTP proxy and proxy authentication details
      Throws:
      IllegalArgumentException - if the specified host or port are invalid
    • serverHost

      Set the host name of the server to connect the session to.

      This value is only used if a URL is not provided when opening a session.

      Parameters:
      host - the host name of the server
      Returns:
      a new immutable instance of the factory that will use the provided host
      Throws:
      IllegalArgumentException - if the specified host is invalid
      Since:
      5.8
    • serverPort

      SessionFactory serverPort(int port) throws IllegalArgumentException
      Set the port of the server to connect the session to.

      This value is only used if a URL is not provided when opening a session. If the port is not set using this method or a URL, the port will be inferred based on the transport and security configuration.

      The provided value must be within the range used for port numbers.

      Parameters:
      port - the port of the server
      Returns:
      a new immutable instance of the factory that will use the provided port
      Throws:
      IllegalArgumentException - if the specified port is invalid
      Since:
      5.8
    • transports

      Set the transports to use to connect the session to the server.

      When a session is opened, it will try to establish a connection with each transport in the list until successful. If a connection cannot be established using any of the transports, the session will be closed.

      This value is only used if a URL is not provided when opening a session.

      The WebSocket transport will be used by default.

      Parameters:
      transports - the transports to use to connect the session to the server. The provided transports may not be null, contain null or be an empty array.
      Returns:
      a new immutable instance of the factory that will use the provided transports
      Throws:
      IllegalArgumentException - if the specified transports are invalid
      Since:
      5.8
    • secureTransport

      SessionFactory secureTransport(boolean secureTransport)
      Set if a secure transport should be used.

      This value is only used if a URL is not provided when opening a session. Enables or disables the use of transport layer security. TLS is disabled by default because in most cases to correctly enable TLS an SSLContext must also be provided using sslContext(SSLContext).

      Parameters:
      secureTransport - If transport layer security is enabled
      Returns:
      a new immutable instance of the factory that will use the provided setting
      Since:
      5.8
    • requestPath

      SessionFactory requestPath(String requestPath) throws IllegalArgumentException
      Set the path used for HTTP requests.

      This value is only used if a URL is not provided when opening a session. The path must start with a '/' and end with '/diffusion'.

      The default is SessionAttributes.DEFAULT_REQUEST_PATH.

      Parameters:
      requestPath - the path used for HTTP requests
      Returns:
      a new immutable instance of the factory that will use the provided path
      Throws:
      IllegalArgumentException - if the specified requestPath is invalid
      Since:
      5.8
    • recoveryBufferSize

      SessionFactory recoveryBufferSize(int size) throws IllegalArgumentException
      Set the recovery buffer size.

      If the server is configured to support reconnection, a session established with a non-zero reconnection time retains a buffer of sent messages. If the session disconnects and reconnects, this buffer is used to re-send messages that the server has not received.

      The default is SessionAttributes.DEFAULT_RECOVERY_BUFFER_SIZE. Higher values increase the chance of successful reconnection, but increase the per-session memory footprint.

      Parameters:
      size - the recovery buffer size in messages; can be 0
      Returns:
      a new immutable instance of the factory that will use the provided recovery buffer size
      Throws:
      IllegalArgumentException - if the specified size is negative
      Since:
      5.8
    • maximumQueueSize

      SessionFactory maximumQueueSize(int size) throws IllegalArgumentException
      Sets the maximum size of the outbound message queue for the connection.

      The outbound message queue should be large enough to accommodate all the messages sent to the server. This would include topic updates, messages sent using Messaging, and service requests such as registering a handler.

      It may be necessary to increase this value for applications that send messages in bursts, or continue to send messages when a session is disconnected and reconnecting. Larger values allow more messages to be queued, and increase the memory footprint of the session.

      If the outbound message queue fills, sending a message will cause the session to close with an error.

      The default is SessionAttributes.DEFAULT_MAXIMUM_QUEUE_SIZE.

      Parameters:
      size - a positive integer indicating the maximum number of messages that may be queued
      Returns:
      a new immutable instance of the factory that will use the provided maximum queue size
      Throws:
      IllegalArgumentException - if the specified size is not a positive integer
      Since:
      5.9
    • property

      SessionFactory property(String key, String value)
      Sets a user-defined session property value.

      Supplied session properties will be provided to the server when a session is created using this session factory. The supplied properties will be validated during authentication and may be discarded or changed.

      The specified property will be added to any existing properties set for this session factory.

      For details of how session properties are used see Session.

      Parameters:
      key - the property key
      value - the property value
      Returns:
      a new immutable instance of the factory with the named property set. If the property was already set it will be overwritten.
      Since:
      6.2
      See Also:
    • properties

      SessionFactory properties(Map<String,String> properties)
      Sets user-defined session property values.

      Supplied session properties will be provided to the server when a session is created using this session factory. The supplied properties will be validated during authentication and may be discarded or changed.

      The specified properties will be added to any existing properties set for this session factory. If any of the keys have been previously declared then they will be overwritten with the new values.

      For details of how session properties are used see Session.

      Parameters:
      properties - a map of user-defined session properties
      Returns:
      a new immutable instance of the factory with the supplied properties set
      Since:
      6.2
      See Also:
    • openAsync

      Open a connection to a server and request a new session.

      The server location is configured using the serverHost(String), serverPort(int), transports(SessionAttributes.Transport...), secureTransport(boolean) and requestPath(String) methods.

      This method is non-blocking. The result is provided asynchronously by the returned CompletableFuture.

      Returns:
      a CompletableFuture that completes when a response is received from the server.

      If a session was established, the CompletableFuture will complete successfully with a Session value.

      Otherwise, the CompletableFuture will complete exceptionally with a CompletionException. Common reasons for failure, listed by the exception reported as the cause, include:

      • IllegalStateException – if any of the session attributes are found to be inconsistent. For example, if the default SSL context could not be loaded;
      • SessionEstablishmentException – if an initial connection could not be established;
      • AuthenticationException –if the client is insufficiently authorized to start the session, based on the supplied client credentials.
      Since:
      6.0
      See Also:
    • openAsync

      CompletableFuture<Session> openAsync(String url)
      Open a connection to a server and request a new session.

      This method is a variant of openAsync() that uses a URL to specify the server location, ignoring the serverHost and serverPort, requestPath, secureTransport and transports session factory attributes.

      Parameters:
      url - the server location, see the class documentation
      Returns:
      a CompletableFuture that completes when a response is received from the server.

      If a session was established, the CompletableFuture will complete successfully with a Session value.

      Otherwise, the CompletableFuture will complete exceptionally with a CompletionException. Common reasons for failure, listed by the exception reported as the cause, include:

      Since:
      6.0
    • open

      Open a connection to a server and request a new client session.

      This is a convenience version of openAsync(String) which blocks until the session has been established.

      Parameters:
      url - the server location, see the class documentation
      Returns:
      a new session
      Throws:
      IllegalArgumentException - if url is invalid
      IllegalStateException - if any of the session attributes are found to be inconsistent. For example, if the default SSL context could not be loaded.
      SessionEstablishmentException - if an initial connection could not be established
      AuthenticationException - if the client is insufficiently authorized to start the session, based on the supplied client credentials
    • open

      Open a connection to a server and request a new session.

      This is a convenience version of openAsync() which blocks until the session has been established.

      Returns:
      a new session
      Throws:
      IllegalStateException - if any of the session attributes are found to be inconsistent. For example, if the default SSL context could not be loaded.
      SessionEstablishmentException - if an initial connection could not be established
      AuthenticationException - if the client is insufficiently authorized to start the session, based on the supplied client credentials
      Since:
      5.8