Interface SessionFactory
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 Summary
Modifier and TypeMethodDescriptionconnectionTimeout
(int timeout) Sets the connection timeout.credentials
(Credentials credentials) Set credentials.customCredentials
(byte[] bytes) Set credentials of typeCredentials.Type.CUSTOM
.errorHandler
(Session.ErrorHandler errorHandler) Nominates an error handler for a session.Set the address of the HTTP Proxy that should be used to make connections to the server.httpProxy
(String host, int port, HTTPProxyAuthentication authentication) A variant ofhttpProxy(String, int)
that provides authentication details to the HTTP proxy.initialRetryStrategy
(RetryStrategy strategy) Sets the initial retry strategy.inputBufferSize
(int size) Sets the input buffer size for socket connection buffers and message receiving buffers.listener
(Session.Listener listener) Nominates a listener for session events from a session.localSocketAddress
(SocketAddress address) Set the optional local socket address, used prior to connection.maximumMessageSize
(int size) Set the maximum message size.maximumQueueSize
(int size) Sets the maximum size of the outbound message queue for the connection.Set credentials toCredentials.Type.NONE
.Disable reconnection.open()
Open a connection to a server and request a new session.Open a connection to a server and request a new client session.Open a connection to a server and request a new session.Open a connection to a server and request a new session.outputBufferSize
(int size) Sets the output buffer size for socket connection buffers and message sending buffers.Set credentials of typeCredentials.Type.PLAIN_PASSWORD
.Sets the security principal.properties
(Map<String, String> properties) Sets user-defined session property values.Sets a user-defined session property value.reconnectionStrategy
(ReconnectionStrategy strategy) Sets the reconnection strategy.reconnectionTimeout
(int timeout) Sets the reconnection timeout.recoveryBufferSize
(int size) Set the recovery buffer size.requestPath
(String requestPath) Set the path used for HTTP requests.secureTransport
(boolean secureTransport) Set if a secure transport should be used.serverHost
(String host) Set the host name of the server to connect the session to.serverPort
(int port) Set the port of the server to connect the session to.sslContext
(SSLContext context) Sets the SSL Context if a secure connection is required.transports
(SessionAttributes.Transport... transports) Set the transports to use to connect the session to the server.writeTimeout
(int timeout) Sets the write timeout value for blocking writes.
-
Method Details
-
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
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
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 toCredentials.Type.NONE
.This is the default.
- Returns:
- a new immutable instance of the factory with the credentials changed
-
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
Set credentials of typeCredentials.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
Set credentials of typeCredentials.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
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 of0
.- Returns:
- a new immutable instance of the factory with reconnection disabled
- Since:
- 5.5
-
initialRetryStrategy
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
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 callingnoReconnection()
.- 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
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
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 thanSessionAttributes.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
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
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
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
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
- iftimeout
is invalid
-
maximumMessageSize
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 thanSessionAttributes.MAXIMUM_MESSAGE_SIZE_MIN
- Returns:
- a new immutable instance of the factory with the maximum message size changed
- Throws:
IllegalArgumentException
- if the specifiedsize
is invalid
-
httpProxy
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 proxyport
- 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 specifiedhost
orport
are invalid- See Also:
-
httpProxy
SessionFactory httpProxy(String host, int port, HTTPProxyAuthentication authentication) throws IllegalArgumentException A variant ofhttpProxy(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()
andProxyAuthenticationFactory
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)
andcredentials(Credentials)
methods control authentication with the server and do not affect proxy authentication.- Parameters:
host
- the host name of the HTTP proxyport
- the port of the HTTP proxyauthentication
- 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 specifiedhost
orport
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 specifiedhost
is invalid- Since:
- 5.8
-
serverPort
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 specifiedport
is invalid- Since:
- 5.8
-
transports
SessionFactory transports(SessionAttributes.Transport... transports) throws IllegalArgumentException 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 specifiedtransports
are invalid- Since:
- 5.8
-
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 usingsslContext(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
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 specifiedrequestPath
is invalid- Since:
- 5.8
-
recoveryBufferSize
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 specifiedsize
is negative- Since:
- 5.8
-
maximumQueueSize
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
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 keyvalue
- 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
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
CompletableFuture<Session> 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)
andrequestPath(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 thecause
, 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
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 theserverHost
andserverPort
,requestPath
,secureTransport
andtransports
session factory attributes.- Parameters:
url
- the server location, see theclass 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 thecause
, include:IllegalArgumentException
– ifurl
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.
- Since:
- 6.0
-
open
Session open(String url) throws IllegalArgumentException, IllegalStateException, SessionEstablishmentException, AuthenticationException 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 theclass documentation
- Returns:
- a new session
- Throws:
IllegalArgumentException
- ifurl
is invalidIllegalStateException
- 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 establishedAuthenticationException
- 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 establishedAuthenticationException
- if the client is insufficiently authorized to start the session, based on the supplied client credentials- Since:
- 5.8
-