MigratoryDataClient

This class implements all the necessary operations for connecting to a cluster of one or more MigratoryData servers, subscribing to one or more subjects, getting real-time messages for the subscribed subjects, and publishing messages.

Public Functions

Name
MigratoryDataClient()
Create a MigratoryDataClient object.
void connect()
Use this method to connect this client to one of the MigratoryData servers you specified with MigratoryDataClient.setServers(), and subscribe to the subjects you specified with MigratoryDataClient.subscribe(), if any.
void setLogListener(MigratoryDataLogListener logListener, MigratoryDataLogLevel logLevel)
Attach a listener for handling log messages outputted by the library.
void setListener(MigratoryDataListener listener)
Attach a listener for handling the received real-time messages as well as the status notifications.
MigratoryDataListener getListener()
Get the listener for handling real-time messages and status notifications.
void setServers(String[] servers)
Specify a cluster of one or more MigratoryData servers to which the client will connect to.
void subscribe(List< String > subjects)
Subscribe to one or more subjects.
void subscribeWithHistory(List< String > subjects, int numberOfHistoricalMessages)
Subscribe to one or more subjects after getting historical messages for those subjects.
void unsubscribe(List< String > subjects)
Unsubscribe from one or more subjects.
void setEncryption(boolean encrypted)
Configure whether to use SSL/TLS encryption when connecting to a MigratoryData server.
void setEntitlementToken(String token)
Assign an entitlement token to the client.
void advertiseInteractiveSubjects(List wildcardSubjects)
Advertise interactive subjects via a list of wildcard subjects.
Collection< String > getSubjects()
Return the list of subscribed subjects.
void notifyAfterFailedConnectionAttempts(int retries)
Define the number of failed attempts to connect to one or more MigratoryData servers before triggering a status notification MigratoryDataClient.NOTIFY_SERVER_DOWN.
void disconnect()
Disconnect from the connected MigratoryData server and dispose the resources used by the connection.
void publish(MigratoryDataMessage message)
Publish a message.
void setQuickReconnectMaxRetries(int retries)
Define the maximum number of retries for the Quick Reconnect fail-over phase.
void setQuickReconnectInitialDelay(int seconds)
Define the number of seconds to wait before attempting to reconnect to the cluster after a connection failure is detected.
void setReconnectPolicy(String policy)
Define the reconnect policy to be used after the Quick Reconnect phase.
void setReconnectTimeInterval(int seconds)
Define the time interval used for the reconnect schedule after the Quick Reconnect phase.
void setReconnectMaxDelay(int seconds)
Define the maximum reconnect delay for the MigratoryDataClient.TRUNCATED_EXPONENTIAL_BACKOFF policy.
void setExternalToken(String externalToken)
Assigns an external token to enable client communication via external services while the client is offline.
void setTransport(String type)
Define the transport type used by the client to communicate with the MigratoryData cluster.
void setHttpHeader(String header, String value)
Allows for the inclusion of custom HTTP headers.
void pause()
Pause the API operation.
void resume()
Resume the API operation.

Public Attributes

Name
final String NOTIFY_SERVER_UP
A constant which indicates that the client successfully connected to a MigratoryData server.
final String NOTIFY_SERVER_DOWN
A constant which indicates that the client failed to connect to a MigratoryData server.
final String NOTIFY_DATA_SYNC
A constant which indicates that after a failover reconnection, the client successfully synchronized a subscribed subject with the latest retained message available for that subject, as well as with all messages made available during the failover period for that subject.
final String NOTIFY_DATA_RESYNC
A constant which indicates that after a failover reconnection, the client successfully synchronized a subscribed subject with the latest retained message available for that subject, but not with the potential messages made available during the failover period, therefore behaving as a new client.
final String NOTIFY_CONNECT_OK
A constant which indicates that the client was authorized to connect using the entitlement token defined on the client side.
This notification applies when using a Custom authorization extension built with Auth API. For the entitlement methods None, Basic, or Custom authorization extension built with the previous version of the MigratoryData Extensions API, this notification is always sent no matter the entitlement token is valid or not, the verification of the entitlement token being made only during subscribe and publish operations.
final String NOTIFY_CONNECT_DENY
A constant which indicates that the client was denied to connect using the entitlement token defined on the client side.
This notification applies when using a Custom authorization extension built with Auth API. For the entitlement methods None, Basic, or Custom authorization extension built with the previous version of the MigratoryData Extensions API, this notification is never sent no matter the entitlement token is valid or not, the verification of the entitlement token being made only during subscribe and publish operations.
final String NOTIFY_SUBSCRIBE_ALLOW
A constant which indicates that the client was authorized to subscribe to a subject.
final String NOTIFY_SUBSCRIBE_DENY
A constant which indicates that the client was not authorized to subscribe to a subject.
final String NOTIFY_PUBLISH_OK
A constant which indicates that the client successfully published a message.
final String NOTIFY_PUBLISH_FAILED
A constant which indicates that the client was unable to publish a message.
final String NOTIFY_MESSAGE_SIZE_LIMIT_EXCEEDED
A constant which indicates that the client was unable to publish a message because the size of the message exceeds the message size limit allowed by the server (see the server parameter MaxMessageSize).
final String NOTIFY_PUBLISH_DENIED
A constant which indicates that the client was unable to publish a message because it is not allowed by the entitlement system.
final String CONSTANT_WINDOW_BACKOFF
A constant used to define the reconnect policy.
final String TRUNCATED_EXPONENTIAL_BACKOFF
A constant used to define the reconnect policy.
String TRANSPORT_HTTP
A constant used to define the transport type.
String TRANSPORT_WEBSOCKET
A constant used to define the transport type.

Public Functions Documentation

function MigratoryDataClient

inline MigratoryDataClient()

Create a MigratoryDataClient object.

function connect

inline void connect()

Use this method to connect this client to one of the MigratoryData servers you specified with MigratoryDataClient.setServers(), and subscribe to the subjects you specified with MigratoryDataClient.subscribe(), if any.

function setLogListener

inline void setLogListener(
    MigratoryDataLogListener logListener,
    MigratoryDataLogLevel logLevel
)

Attach a listener for handling log messages outputted by the library.

Parameters:

It is advisable to configure this listener first to log as much as possible. If no log listener is set then, by default the client will log to the console.

function setListener

inline void setListener(
    MigratoryDataListener listener
)

Attach a listener for handling the received real-time messages as well as the status notifications.

Parameters:

function getListener

inline MigratoryDataListener getListener()

Get the listener for handling real-time messages and status notifications.

Return: the listener for handling real-time messages and status notifications

This is the listener set with MigratoryDataClient.setListener().

function setServers

inline void setServers(
    String[] servers
)

Specify a cluster of one or more MigratoryData servers to which the client will connect to.

Parameters:

  • servers an array of strings where each string represents the network address (IP address or DNS domain name and its corresponding port) of a MigratoryData server, optionally prefixed by a weight ranging from 0 to 100; if the weight prefix is not provided to an address, then the API will automatically assign to that address a default weight 100

For example, to connect to a cluster formed of two MigratoryData servers installed at the addresses p1.example.com and p2.example.com, and configured to accept clients on the standard HTTP port 80, the following code can be used:

client.setServers(new String[] {"p1.example.com:80", "p2.example.com:80"});

To achieve load-balancing, the API connects the client to a MigratoryData server chosen randomly from the servers list. In this way, the load is balanced among all the members of the cluster.

Moreover, the API supports weighted load-balancing. This feature is especially useful if the MigratoryData servers of the cluster are installed on machines with different capacities. You can assign to each member of the cluster a weight ranging from 0 to 100. This weight assignment is a hint provided to the API to select with a higher probability a MigratoryData server with a higher weight either initially when the client connects to the cluster or later during a failover reconnection.

Supposing the address p1.example.com corresponds to a machine that is twice more powerful than the machine having the address p2.example.com, then you can assign to p1.example.com a weight 100 and to p2.example.com a weight 50 by prefixing each address with the assigned weight as follows:

client.setServers(new String[] {"100 p1.example.com:80", "50 p2.example.com:80"});

The API assigns a default weight 100 to the addresses not prefixed with a specific weight.

To achieve failover, if the connection between the client and a MigratoryData server is broken, then the API will automatically detect the failure and will select another MigratoryData server from the servers list. If the client fails to connect to the newly selected server, a status notification MigratoryDataClient.NOTIFY_SERVER_DOWN will be triggered, unless this is modified using MigratoryDataClient.notifyAfterFailedConnectionAttempts()), and a new MigratoryData server of the cluster will be selected again and again until the client will be able to connect to one of the MigratoryData servers of the cluster. When successfully connected, the API will trigger MigratoryDataClient.NOTIFY_SERVER_UP.

Furthermore, if the Guaranteed Message Delivery feature is enabled for the MigratoryData cluster, then the messages potentialy published for a subscribed subject during the failover period will be automatically recovered from the cache of the MigratoryData server to which the client reconnects to and a status notification MigratoryDataClient.NOTIFY_DATA_SYNC will be triggered for that subject.

If, for example, the failover period is abnormally long, and the client is not able to recover all the messages made available during the failover period for one of its subscribed subjects, then the API will retrieve only the most recent retained message available for that subject and will trigger a MigratoryDataClient.NOTIFY_DATA_RESYNC status notification for that subject, the client behaving as a new client.

For a complete discussion about load balancing, failover, and guaranteed message delivery features see the Architecture Guide.

function subscribe

inline void subscribe(
    List< String > subjects
)

Subscribe to one or more subjects.

Parameters:

  • subjects An array of strings representing subjects.

The MigratoryData subjects are strings having a particular syntax. See the Chapter “Concepts” of the Architecture Guide to learn about the syntax of the subjects.

As an example, supposing messages are market data updates having as subjects stock names. Then, to subscribe for the messages having as subjects /stocks/NYSE/IBM and /stocks/Nasdaq/MSFT use:

client.subscribe(Arrays.asList("/stocks/NYSE/IBM", "/stocks/Nasdaq/MSFT"));

function subscribeWithHistory

inline void subscribeWithHistory(
    List< String > subjects,
    int numberOfHistoricalMessages
)

Subscribe to one or more subjects after getting historical messages for those subjects.

Parameters:

  • subjects An array of strings representing subjects.
  • numberOfHistoricalMessages the number of historical messages to be retrieved from the cache of the server

The MigratoryData subjects are strings having a particular syntax. See the Chapter “Concepts” of the Architecture Guide to learn about the syntax of the subjects.

Attempt to get the number of historical messages as defined by the argument numberOfHistoricalMessages, for each subject in the argument subjects, then subscribe for real-time messages having as subjects the strings provided in the subjects parameter.

When Guaranteed Message Delivery is enabled, each MigratoryData server in the cluster maintains an in-memory cache with historical messages for each subject. The cache of each subject is available in all servers of the cluster. The maximum number of messages held in cache is defined by the parameter MaxCachedMessagesPerSubject of the MigratoryData server which defaults to 1,000 messages. The historical messages are continuously removed from the cache, but it is guaranteed that they are available in the cache at least the number of seconds defined by the parameter CacheExpireTime which defaults to 180 seconds.

If the value of numberOfHistoricalMessages is higher than the number of historical messages available in the cache, then the client will receive only the messages available in the cache. As a consequence, if you use a value higher than the value of the parameter MaxCachedMessagesPerSubject of the MigratoryData server (which defaults to 1000), then you will get the entire cache before subscribing for real-time messages for the subjects specified with the API call.

If the value of numberOfHistoricalMessages is 0, then no historical messages have to be retrieved from the cache and, in this case, this API method is equivalent to the API method MigratoryDataClient.subscribe().

function unsubscribe

inline void unsubscribe(
    List< String > subjects
)

Unsubscribe from one or more subjects.

Parameters:

  • subjects subjects to unsubscribe

function setEncryption

inline void setEncryption(
    boolean encrypted
)

Configure whether to use SSL/TLS encryption when connecting to a MigratoryData server.

Parameters:

  • encrypted indicate whether or not to use an encrypted SSL/TLS connection to communicate with the server

When using encryption you should connect to the ports of the MigratoryData server that are configured with the parameter ListenEncrypted to listen for encrypted connections.

function advertiseInteractiveSubjects

inline void advertiseInteractiveSubjects(
    List<String> wildcardSubjects
)

Advertise interactive subjects via a list of wildcard subjects.

Parameters:

  • token a list of wildcard subjects

If the Interactive Publishing extension is enabled in the MigratoryData server, i.e. the parameter Extension.InteractivePublishing of the MigratoryData server is set on true, then you can use this API method to advertise the subjects to be used for interactive publishing as detailed below.

First, a wildcard subject is a MigratoryData subject where the last segment is *. For example, by using the wildcard subject /stocks/ibm/* in the argument of this API method, it will advertise the interactive subjects that start with /stocks/ibm/, e.g. /stocks/ibm/last/bid, /stocks/ibm/level2/price etc. We say that an interactive subject, say /stocks/ibm/last/bid, matches the wildcard subject /stocks/ibm/*.

Currently only wildcard subjects with two segments are supported. For example, the following wildcard subject with two segments /stocks/* is supported. However, the following wildcard subject /quotes/nyse/* is not currently supported as it has three segments. You need to use the broader wildcard subject /quotes/* to advertise interactive subjects matching /quotes/nyse/*. To learn more about the valid syntax of subjects, please check out the Concepts section of the product documentation.

An interactive subject is a subject for which this API triggers subscription events such as the first subscribe event and the last unsubscribe event. These events are triggered via the callbacks MigratoryDataInteractiveListener.onSubscribe(String) and MigratoryDataInteractiveListener.onUnsubscribe(String) of the interface MigratoryDataInteractiveListener.

function setEntitlementToken

inline void setEntitlementToken(
    String token
)

Assign an entitlement token to the client.

Parameters:

  • token a string representing an entitlement token

To define which users of your application have access to which subjects, you will first have to configure the parameter Entitlement, see the Configuration Guide. If you set this parameter on Custom, then you can use the Server Extensions API for Authorization to build an extension for the MigratoryData server to allow or deny certain users to subscribe to or publish on certain subjects.

function getSubjects

inline Collection< String > getSubjects()

Return the list of subscribed subjects.

Return: The list of strings representing the subscribed subjects.

function notifyAfterFailedConnectionAttempts

inline void notifyAfterFailedConnectionAttempts(
    int retries
)

Define the number of failed attempts to connect to one or more MigratoryData servers before triggering a status notification MigratoryDataClient.NOTIFY_SERVER_DOWN.

Parameters:

function disconnect

inline void disconnect()

Disconnect from the connected MigratoryData server and dispose the resources used by the connection.

This method should be called when the connection is no longer necessary.

function publish

inline void publish(
    MigratoryDataMessage message
)

Publish a message.

Parameters:

If the message includes a closure data, then a status notification will be provided via MigratoryDataListener.onStatus() to inform whether the message publication has been successful or failed.

function setQuickReconnectMaxRetries

inline void setQuickReconnectMaxRetries(
    int retries
)

Define the maximum number of retries for the Quick Reconnect fail-over phase.

Parameters:

  • retries the maximum number of quick reconnect retries; the default is 3

See MigratoryDataClient.setQuickReconnectInitialDelay() to learn about the Quick Reconnect phase.

function setQuickReconnectInitialDelay

inline void setQuickReconnectInitialDelay(
    int seconds
)

Define the number of seconds to wait before attempting to reconnect to the cluster after a connection failure is detected.

Parameters:

  • seconds The number of seconds to wait before attempting to reconnect to the cluster; default value is 5 seconds.
Connection Failure Detection

Connection failure is detected immediately for almost all users. For a few users which are subject to temporary, atypical network conditions, connection failure is detected after 30-40 seconds.

Reconnection Phases and Policies

When a connection failure is detected, the API will attempt to reconnect to the servers of the MigratoryData cluster as follows: First, it will attempt to reconnect up to a number of times as defined by MigratoryDataClient.setQuickReconnectMaxRetries() using small delays between retries (Quick Reconnection Phase). If the connection cannot be established after the Quick Reconnection Phase, then the API will attempt to reconnect less frequently according to the policy defined by MigratoryDataClient.setReconnectPolicy().

The delays between retries are computed according to the following algorithm where the values of the variables involved are defined by the API methods having substantially the same names:

Quick Reconnect Phase (retries <= quickReconnectMaxRetries)
-----------------------------------------------------------

   (retries starts with 1 and increment by 1 at each quick reconnect)

   reconnectDelay = quickReconnectInitialDelay * retries - random(0, quickReconnectInitialDelay)

After Quick Reconnect Phase (retries > quickReconnectMaxRetries)
----------------------------------------------------------------

   (reset retries to start with 1 and increment by 1 at each reconnect)

   If reconnectPolicy is CONSTANT_WINDOW_BACKOFF, then

      reconnectDelay = reconnectTimeInterval

   else if reconnectPolicy is TRUNCATED_EXPONENTIAL_BACKOFF, then

      reconnectDelay = min(reconnectTimeInterval * (2 ^ retries) - random(0, reconnectTimeInterval * retries), reconnectMaxDelay)

For a few users which are subject to temporary, atypical network conditions, if reconnectDelay computed with the algorithm above is less than 10 seconds, then it is rounded to 10 seconds.

function setReconnectPolicy

inline void setReconnectPolicy(
    String policy
)

Define the reconnect policy to be used after the Quick Reconnect phase.

Parameters:

See MigratoryDataClient.setQuickReconnectInitialDelay() to learn about the Quick Reconnect phase and the reconnect schedule for the policy defined by this method.

function setReconnectTimeInterval

inline void setReconnectTimeInterval(
    int seconds
)

Define the time interval used for the reconnect schedule after the Quick Reconnect phase.

Parameters:

  • seconds A time interval expressed in seconds used for reconnect schedule; default is 20 seconds.

See MigratoryDataClient.setQuickReconnectInitialDelay() to learn about the Quick Reconnect phase and the reconnect schedule for the policy defined by this method.

function setReconnectMaxDelay

inline void setReconnectMaxDelay(
    int seconds
)

Define the maximum reconnect delay for the MigratoryDataClient.TRUNCATED_EXPONENTIAL_BACKOFF policy.

Parameters:

See MigratoryDataClient.setQuickReconnectInitialDelay() to learn how the value defined by this method is used.

function setExternalToken

inline void setExternalToken(
    String externalToken
)

Assigns an external token to enable client communication via external services while the client is offline.

Parameters:

  • externalToken a token (e.g. FCM token, email address, …)

Presuming a client goes offline and disconnects from the MigratoryData cluster. Then plugins within the MigratoryData server, leveraging MigratoryData’s Presence API, can utilize this external token to communicate with the offline client, via external services like push notifications or email.

For instance, consider a plugin designed for Firebase Cloud Messaging (FCM), which requires an FCM token to send push notifications to a client via FCM. Through this method, the client can provide the necessary FCM token to the plugin.

Similarly, consider a plugin designed for email services. To send emails to clients when they’re offline, the plugin requires their email addresses. Clients can provide their email addresses using this method.

function setTransport

inline void setTransport(
    String type
)

Define the transport type used by the client to communicate with the MigratoryData cluster.

Parameters:

function setHttpHeader

inline void setHttpHeader(
    String header,
    String value
)

This method allows for the inclusion of custom HTTP headers. In the case of the WebSocket transport, the added headers are transmitted during the handshake. For the HTTP transport, the added headers are sent with every client request.

This functionality is particularly useful when an authentication solution is in place between the client and the MigratoryData server, which requires an HTTP header containing an authentication token.

Parameters:

  • header header name
  • value header value

function pause

inline void pause()

Pause the API operation.

If the application built with this API library enters into background, then it is recommended to use this API call. It will disconnect the user from the MigratoryData sever but will preserve the user’s context (including the cluster definition and subscribed subjects) in order to reconnect to the cluster later when the API method MigratoryDataClient.resume is called.

Moreover, if the cluster is configured with guaranteed message delivery, then when the user will reconnect to the cluster using MigratoryDataClient.resume, it will get all messages published since the MigratoryDataClient.pause method was called, provided however that the duration between the time when MigratoryDataClient.pause method was called and the MigratoryDataClient.resume method was called is less than the value defined by the parameter CacheExpireTime of the MigratoryData server configuration.

function resume

inline void resume()

Resume the API operation.

If the application was paused with the MigratoryDataClient.pause method, then this API call will attempt to reconnect the user to the cluster. Also, if guaranteed message delivery is enabled, this method also retrieves all messages published since the MigratoryDataClient.pause has been called provided that the duration between the time when MigratoryDataClient.pause method was called and the MigratoryDataClient.resume method was called is smaller than the value defined by the parameter CacheExpireTime.

This method will be typically used when the application switches to foreground.

Public Attributes Documentation

variable NOTIFY_SERVER_UP

static final String NOTIFY_SERVER_UP = "NOTIFY_SERVER_UP";

A constant which indicates that the client successfully connected to a MigratoryData server.

variable NOTIFY_SERVER_DOWN

static final String NOTIFY_SERVER_DOWN = "NOTIFY_SERVER_DOWN";

A constant which indicates that the client failed to connect to a MigratoryData server.

variable NOTIFY_DATA_SYNC

static final String NOTIFY_DATA_SYNC = "NOTIFY_DATA_SYNC";

A constant which indicates that after a failover reconnection, the client successfully synchronized a subscribed subject with the latest retained message available for that subject, as well as with all messages made available during the failover period for that subject.

variable NOTIFY_DATA_RESYNC

static final String NOTIFY_DATA_RESYNC = "NOTIFY_DATA_RESYNC";

A constant which indicates that after a failover reconnection, the client successfully synchronized a subscribed subject with the latest retained message available for that subject, but not with the potential messages made available during the failover period, therefore behaving as a new client.

variable NOTIFY_CONNECT_OK

static final String NOTIFY_CONNECT_OK = "NOTIFY_CONNECT_OK";

A constant which indicates that the client was authorized to connect using the entitlement token defined on the client side.

variable NOTIFY_CONNECT_DENY

static final String NOTIFY_CONNECT_DENY = "NOTIFY_CONNECT_DENY";

A constant which indicates that the client was denied to connect using the entitlement token defined on the client side.

variable NOTIFY_SUBSCRIBE_ALLOW

static final String NOTIFY_SUBSCRIBE_ALLOW = "NOTIFY_SUBSCRIBE_ALLOW";

A constant which indicates that the client was authorized to subscribe to a subject.

variable NOTIFY_SUBSCRIBE_DENY

static final String NOTIFY_SUBSCRIBE_DENY = "NOTIFY_SUBSCRIBE_DENY";

A constant which indicates that the client was not authorized to subscribe to a subject.

variable NOTIFY_PUBLISH_OK

static final String NOTIFY_PUBLISH_OK = "NOTIFY_PUBLISH_OK";

A constant which indicates that the client successfully published a message.

variable NOTIFY_PUBLISH_FAILED

static final String NOTIFY_PUBLISH_FAILED = "NOTIFY_PUBLISH_FAILED";

A constant which indicates that the client was unable to publish a message.

variable NOTIFY_MESSAGE_SIZE_LIMIT_EXCEEDED

static final String NOTIFY_MESSAGE_SIZE_LIMIT_EXCEEDED = "NOTIFY_MESSAGE_SIZE_LIMIT_EXCEEDED";

A constant which indicates that the client was unable to publish a message because the size of the message exceeds the message size limit allowed by the server (see the server parameter MaxMessageSize).

variable NOTIFY_PUBLISH_DENIED

static final String NOTIFY_PUBLISH_DENIED = "NOTIFY_PUBLISH_DENIED";

A constant which indicates that the client was unable to publish a message because it is not allowed by the entitlement system.

variable CONSTANT_WINDOW_BACKOFF

static final String CONSTANT_WINDOW_BACKOFF = "CONSTANT_WINDOW_BACKOFF";

A constant used to define the reconnect policy.

See MigratoryDataClient.setQuickReconnectInitialDelay() for more details about this policy.

variable TRUNCATED_EXPONENTIAL_BACKOFF

static final String TRUNCATED_EXPONENTIAL_BACKOFF = "TRUNCATED_EXPONENTIAL_BACKOFF";

A constant used to define the reconnect policy.

See MigratoryDataClient.setQuickReconnectInitialDelay() for more details about this policy.

variable TRANSPORT_HTTP

static String TRANSPORT_HTTP = "TRANSPORT_HTTP";

A constant used to define the transport type.

See MigratoryDataClient.setTransport() for more details about this policy.

variable TRANSPORT_WEBSOCKET

static String TRANSPORT_WEBSOCKET = "TRANSPORT_WEBSOCKET";

A constant used to define the transport type.

See MigratoryDataClient.setTransport() for more details about this policy.