public interface

TrapEndpoint

implements TrapSettings
com.ericsson.research.trap.TrapEndpoint
Known Indirect Subclasses

Class Overview

The main interface to Trap, a TrapEndpoint is the shared interface between servers and clients. It provides most of the methods that should be necessary to configure and use a Trap connection.

In general, a TrapEndpoint should be configured either when it has just been created, using a TrapFactory, or when it has just been provided to a TrapListenerDelegate using the callback. Reconfiguring a TrapEndpoint while it is in use can have unintended consequences.

Common tasks on a TrapEndpoint are:

Configuring Transports

Enabling and disabling transports, as well as configuring each transport, is possible from TrapEndpoint. Adding new transports to an existing endpoint is not possible; for that, instead use addTransportClass(Class) before instantiating an endpoint.

Sending and Receiving Messages

To send messages, simply use send(byte[]) to send binary data, or send(TrapObject) to use deferred serialization. When data is received, the appropriate delegate that implements OnData or OnObject is called.

Checking Liveness

Trap provides a simple facility to check if the other endpoint is alive, that is, communication is active and the other application layer is responding. The isAlive(long) method will perform an active check, that is, ping immediately. The isAlive(long, boolean, boolean, long) method on the other hand can be used to check if the endpoint has been alive recently, or a combination of the two.

Configuring Keepalives

By default, Trap will attempt to use a per-transport keepalive policy that strikes a moderate balance between liveness and chattiness. It will take into account traffic only on the current TrapTransport, and without using device integration. This simple implementation can be tweaked to use a static keepalive interval instead (every X milliseconds), or disabled, using the setKeepaliveInterval(int) method. More advanced keepalives can be user-supplied on a transport basis using setKeepalivePredictor(TrapKeepalivePredictor).

Customizing the Message Queue

Trap has a number of buffers it uses, and some (such as the message queue) can impact performance significantly under different usage patterns. The message queue is the first front-end that feeds Trap, and plays a large role. An endpoint can be instructed to either choose the "best" buffer available of a given type (see constants) using setQueueType(String), or it can be told to explicitly use a specific queue using setQueue(MessageQueue). User-supplied queues can be use, as long as they fulfil the requirements.

Summary

Constants
String BLOCKING_BYTE_QUEUE Constant representing a blocking byte queue.
String BLOCKING_MESSAGE_QUEUE Constant representing a blocking message queue.
String OPTION_AUTO_HOSTNAME Hostname for automatic configuration.
String OPTION_ENABLE_COMPRESSION Configuration parameter to enable/disable compression.
String OPTION_LOGGERPREFIX Configuration parameter representing the prefix to be prepended to all logging out of this endpoint.
String OPTION_MAX_CHUNK_SIZE Configuration parameter for the maximum chunk size.
String REGULAR_BYTE_QUEUE Constant representing a non-blocking byte queue.
String REGULAR_MESSAGE_QUEUE Constant representing a regular message queue.
Public Methods
abstract void close()
Closes this Trap endpoint, terminating any outstanding Trap transports.
abstract TrapAuthentication getAuthentication()
Fetches the authentication instance for this Trap endpoint.
abstract long getBlockingTimeout()
Accessor for the current blocking timeout
abstract TrapChannel getChannel(int channelID)
Fetches the channel object associated with the given channel ID.
abstract int getKeepaliveInterval()
Retreives the current value of keepaliveInterval.
abstract int getMaxActiveTransports()
Gets the amount of maximum simultaneously active transports.
abstract long getReconnectTimeout()
Fetches the reconnect timeout.
abstract TrapState getState()
Accessor for the current endpoint state.
abstract Map<StringMap<StringObject>> getTransportAuthenticationContexts()
Fetches all the available authentication context, for all transports; including, where available, IP numbers, ports, etc.
abstract TrapMessage.Format getTrapFormat()
Fetches the current message serialization format.
abstract Callback<Boolean> isAlive(long within, boolean check, boolean force, long timeout)
Attempts to verify if the endpoint is alive, or has been alive within a certain number of milliseconds.
abstract Callback<Boolean> isAlive(long timeout)
Attempts to verify that the endpoint is alive, with a round trip time of at most timeout milliseconds.
abstract boolean isAsync()
Checks whether this endpoint works in async mode.
abstract long lastAlive()
Fetches the last known liveness timestamp of the endpoint.
abstract void send(TrapObject object)
Alias for send(TrapObject, int, boolean), with the channel ID set to 1.
abstract void send(byte[] data, int channel, boolean useCompression)
Attempts to queue data for sending.
abstract void send(TrapObject object, int channel, boolean useCompression)
Attempts to queue an object for sending.
abstract void send(byte[] data)
Alias for send(byte[], int, boolean), with the channel ID set to 1.
abstract void setAsync(boolean async)
In async mode, the endpoint will automatically schedule incoming messages on a separate thread than the one on which they are received.
abstract void setAuthentication(TrapAuthentication authentication)
Assigns an authentication instance to this TrapEndpoint.
abstract void setBlockingTimeout(long timeout)
Sets the blocking timeout, when using a blocking queue.
abstract void setDelegate(TrapEndpointDelegate delegate, Object context)
This method is deprecated. Since 1.1, the preferred signature is setDelegate(TrapDelegate, boolean). If a context is required, use the explicit setDelegateContext(Object) method.
abstract void setKeepaliveExpiry(long newExpiry)
Sets the keepalive expiry timeout.
abstract void setKeepaliveInterval(int newInterval)
Sets a new keepalive interval for the trap endpoint.
abstract void setMaxActiveTransports(int newMax)
Sets the maximum allowed simultaneous transports.
abstract void setQueue(MessageQueue newQueue)
Assigns a new queue implementation for the outgoing message queue.
abstract void setQueueType(String type)
Like setQueue(MessageQueue), except it instantiates one of the built-in queues based on default parameters.
abstract void setReconnectTimeout(long reconnectTimeout)
Sets the reconnect timeout.
abstract void setTrapFormat(TrapMessage.Format trapFormat)
Sets the Trap message format for this endpoint.
[Expand]
Inherited Methods
From interface com.ericsson.research.trap.TrapSettings

Constants

public static final String BLOCKING_BYTE_QUEUE

Constant representing a blocking byte queue. Properties follow:

  • Low memory overhead
  • Moderate CPU overhead to calculate the bytes in/out
  • Upper limit on the RAM usage.
The regular message queue is good for a generic traffic pattern, that does not have a more specific property, on desktop machines.

When supplied to setQueueType(String), allows Trap to automatically select the specific queue implementation from the built-in ones.

Constant Value: "BLOCKING_BYTE_QUEUE"

public static final String BLOCKING_MESSAGE_QUEUE

Constant representing a blocking message queue. Properties follow:

  • Low memory overhead
  • Upper limit on number of messages; provides rough prevention against out of memory / buffer overruns.
  • No view on how much memory is used by the queue.
The blocking message queue type is a reasonably low-overhead queue that can prevent rudimentary memory issues. It still provides no explicit checks, but is better than nothing.

When supplied to setQueueType(String), allows Trap to automatically select the specific queue implementation from the built-in ones.

Constant Value: "BLOCKING_MESSAGE_QUEUE"

public static final String OPTION_AUTO_HOSTNAME

Hostname for automatic configuration. This option is used by the client to format its Open message, and for the server to ensure the client has the correct transports configured

Constant Value: "trap.auto_hostname"

public static final String OPTION_ENABLE_COMPRESSION

Configuration parameter to enable/disable compression. Set to false to disable compression support on the endpoint.

Constant Value: "trap.enablecompression"

public static final String OPTION_LOGGERPREFIX

Configuration parameter representing the prefix to be prepended to all logging out of this endpoint. This option is useful for integrating this Trap endpoint's logging into a greater structure.

Constant Value: "trap.loggerprefix"

public static final String OPTION_MAX_CHUNK_SIZE

Configuration parameter for the maximum chunk size. Set to [1,Integer.MAX_VALUE] to alter the maximum chunk size of the endpoint. Set to 0 or less to disable chunking entirely.

Constant Value: "trap.maxchunksize"

public static final String REGULAR_BYTE_QUEUE

Constant representing a non-blocking byte queue. Properties follow:

  • Low memory overhead
  • Moderate CPU overhead to calculate the bytes in/out
  • No upper limit on number of messages.
  • Can inspect how much memory is used
The regular message queue is good for a generic traffic pattern, that does not have a more specific property, on desktop machines.

When supplied to setQueueType(String), allows Trap to automatically select the specific queue implementation from the built-in ones.

Constant Value: "REGULAR_BYTE_QUEUE"

public static final String REGULAR_MESSAGE_QUEUE

Constant representing a regular message queue. Properties follow:

  • Lowest memory overhead of any kind of queue.
  • No upper limit on number of messages.
  • No view on how much memory is used by the queue.
The regular message queue is good for a generic traffic pattern, that does not have a more specific property, on desktop machines.

When supplied to setQueueType(String), allows Trap to automatically select the specific queue implementation from the built-in ones.

Constant Value: "REGULAR_MESSAGE_QUEUE"

Public Methods

public abstract void close ()

Closes this Trap endpoint, terminating any outstanding Trap transports. Does nothing if the endpoint is already closed, is closing, or is in an error state.

public abstract TrapAuthentication getAuthentication ()

Fetches the authentication instance for this Trap endpoint. Can be used by individual transports to challenge and/or authenticate incoming messages, if the transport requires more authentication than the default Trap security policy.

Returns
  • The TrapAuthentication instance used by the endpoint.

public abstract long getBlockingTimeout ()

Accessor for the current blocking timeout

Returns
  • The current blocking timeout.

public abstract TrapChannel getChannel (int channelID)

Fetches the channel object associated with the given channel ID. If the channel was not created, creates it, allocating all required buffers.

Parameters
channelID The channel ID to get the object for.
Returns
  • The object responsible for maintaining the channel's state.

public abstract int getKeepaliveInterval ()

Retreives the current value of keepaliveInterval. See setKeepaliveInterval(int) for information about what the different values mean.

Returns
  • The number of seconds between keepalives.

public abstract int getMaxActiveTransports ()

Gets the amount of maximum simultaneously active transports.

The number of max simultaneously active transports governs the behaviour of Trap Endpoints (both client and server). If the number of active transports equals the number of maximum simultaneous transports, recovery will only take place for transports with higher priority than the currently active transport.

If the number of active transports exceeds the maximum, transports will be closed, starting with the lowest priority (largest integer). Note that this is a soft limit. The Trap implementation may exceed the maximum number of transports for a transitional period, in order to ensure a smooth handover.

Returns
  • The current maximum simultaneously active transports

public abstract long getReconnectTimeout ()

Fetches the reconnect timeout. See setReconnectTimeout(long)

Returns
  • The current reconnect timeout, in milliseconds

public abstract TrapState getState ()

Accessor for the current endpoint state.

Returns
  • The state the endpoint is in.

public abstract Map<StringMap<StringObject>> getTransportAuthenticationContexts ()

Fetches all the available authentication context, for all transports; including, where available, IP numbers, ports, etc. This context will be based on TrapContextKeys, among other detail information, and consist of a map for each transport, indexed by transport name. This information will provide detail level information on the connection for each transport.

Typical output for a single-transport scenario may look as follows:

 {
  socket= {
      LastAlive=1407198698446,
      Format=REGULAR, 
      State=AVAILABLE, 
      Transport=socket/1/AVAILABLE/704f459c, 
      LocalIP=127.0.0.1, 
      LocalPort=59277, 
      Configuration=trap.enablecompression = true
      RemotePort=59278, 
      Protocol=tcp, 
      RemoteIP=127.0.0.1, 
      Priority=-100
      }
  }
 
From this information, we can gather all pertinent information about the transport's internal state. This is a socket transport that is not configured to connect, so was provided by a server endpoint. The state is AVAILABLE, and lastAlive specifies when there was traffic seen. We have the TCP 5-tuple information, which can be used to identify a connection that has not changed.

This information is generally available to a TrapAuthentication instance assigned to the endpoint and/or transports. The authentication will be automatically invoked whenever any changes may occur on the underlying connection, such as a new TCP session, unsecure packet, new HTTP request, transport switchover, or a new transport being introduced. If this information is needed to provide security, TrapAuthentication should be used.

This method is intended for informational purposes. The returned values are immediately polled, will include all possible values, and will be requested synchronously; the CPU cost of using this method often is non-negligible. The method is thread safe with no need for synchronization.

Returns
  • A map of all authentication context available.

public abstract TrapMessage.Format getTrapFormat ()

Fetches the current message serialization format.

Returns
  • the current message serialization format.

public abstract Callback<Boolean> isAlive (long within, boolean check, boolean force, long timeout)

Attempts to verify if the endpoint is alive, or has been alive within a certain number of milliseconds. Effectively, this can be used to trigger a keepalive check of the endpoint if used with a within parameter of 0 and a check parameter of true.

This function has a two-part purpose. The first is for the application to be able to check the last known liveness of the endpoint, to reduce the discovery time of a dead connection. The second is to trigger a check for a dead endpoint, when the application needs to know that it has active connectivity.

Note that in normal operation, the endpoint itself will report when it has disconnected; the application does not need to concern itself with this detail unless it specifically needs to know that it has connectivity right now.

Warning: Calling isAlive on a Server Trap Endpoint (i.e. when none of the transports can perform the open() function) may cause a client to lose its connectivity. The client may not have discovered the underlying transport is dead yet, and may require more time to reconnect. A wakeup mechanism can be used to establish liveness, but the server's timeout value should be significantly more generous in order to accommodate the client's reconnect and/or wakeup procedure!

Parameters
within Within how many milliseconds the last activity of the endpoint should have occurred before the endpoint should question whether it is alive.
check Whether the endpoint should attempt to check for liveness, or simply return false if the last known activity of the endpoint is not later than within.
force Whether to attempt to force reconnection if the transports are not available within the given timeout. This will ensure available liveness value reflects what is possible right now, although it may mean disconnecting transports that still may recover.
timeout If check is true, how many milliseconds at most the liveness check should take before returning false anyway. The application can use this value if it has a time constraint on it.
Returns
  • A callback for true if the connection is currently alive (including if this function successfully re-established the connection), false otherwise.

public abstract Callback<Boolean> isAlive (long timeout)

Attempts to verify that the endpoint is alive, with a round trip time of at most timeout milliseconds. This function is primarily intended for when an application requires to know it has connectivity right this instant, and should be used sparingly on power-constrained devices.

isAlive(long) is synonymous to calling isAlive(timeout, true, true, timeout).

Note that isAlive is intended to be used in an asynchronous mode. The callback may be used to request a synchronous answer, but this is strongly discouraged. Further note that isAlive will take longer time to execute than timeout as it will both try to verify transport liveness, and then reconnect the transport if verification fails. Transport reconnection uses a timer longer than timeout, to allow for additional round-trips used when connecting.

Warning: Calling isAlive on a Server Trap Endpoint (i.e. when none of the transports can perform the open() function) may cause an endpoint to close on the server, while the client considers it open. The client may not have discovered the underlying transport is dead yet, and may require more time to reconnect. A wakeup mechanism can be used to establish liveness, but the server's timeout value should be significantly more generous in order to accommodate the client's reconnect and/or wakeup procedure!

Parameters
timeout The timeout (in milliseconds) for the round-trip between the server.
Returns
  • A callback for true if the connection is currently alive (including if this function successfully re-established the connection), false otherwise.

public abstract boolean isAsync ()

Checks whether this endpoint works in async mode. In async mode, the transport thread is disconnected from the Trap thread. Trap ensures only one thread has concurrent calls from trapData, although it may receive data from several.

Returns
  • true if async mode is enabled, false otherwise.

public abstract long lastAlive ()

Fetches the last known liveness timestamp of the endpoint. This is the last time it received a message from the other end. This includes all messages (i.e. also Trap messages such as keepalives, configuration, etc) so must not be confused with the last known activity of the other application. For example, in the case of a JavaScript remote endpoint, this does not guarantee an evaluation error has not rendered the JSApp's main run loop as inoperable.

Returns
  • The timestamp of the last message received from the remote side.

public abstract void send (TrapObject object)

Alias for send(TrapObject, int, boolean), with the channel ID set to 1.

Parameters
object The object to send
Throws
TrapException if the queue length is exceeded, or a timeout occurs on a blocking queue

public abstract void send (byte[] data, int channel, boolean useCompression)

Attempts to queue data for sending. If the queue length is exceeded, it may block or throw an exception, as per the queue type.

Please note that while send will accurately send the data over to the other endpoint, it is advisable to instead use send(TrapObject) if the data being sent is a serialized object. If the other endpoint is locally deployed, the TrapObject will never be serialized, thus saving on large amounts of processing power.

Parameters
data The data to send. This should be UTF-8 readable if it is aimed at a browser, for maximum compatibility. If the remote endpoint is a Java or C client or server, can be any arbitrary data of less than 2^28-1 bytes length (7-bit encoding) or 2^32-1 bytes (8-bit encoding)
channel The channel to send the data on. Recommended in the range [1-63], but will accept ID zero as well.
useCompression True if Trap should apply compression algorithm to this message, false otherwise.
Throws
TrapException if the queue length is exceeded, or a timeout occurs on a blocking queue

public abstract void send (TrapObject object, int channel, boolean useCompression)

Attempts to queue an object for sending. If the queue length is exceeded, it may block or throw an exception, as per the queue type.

Sending a TrapObject will serialize it as late as possible, or never. If the object is sent locally, it will never be serialized. If it is to be sent remotely, it will be serialized when needed. Trap may serialize multiple TrapObjects in parallel, so implementations should not assume any order between eventual getSerializedData() calls.

Note that, since the TrapObject is not necessarily serialized in the caller's thread, exceptions caused by object serialization will most probably not be seen in this way. They will be logged, however.

Parameters
object The object to send.
channel The channel to send the data on. Recommended in the range [1-63], but will accept ID zero as well.
useCompression True if Trap should apply compression algorithm to this message, false otherwise. Compression will be applied in the event that the object has to be serialized.
Throws
TrapException If the object could not be queued for sending, either due to user configuration or because of an invalid state of the endpoint.

public abstract void send (byte[] data)

Alias for send(byte[], int, boolean), with the channel ID set to 1.

Parameters
data The data to send
Throws
TrapException if the queue length is exceeded, or a timeout occurs on a blocking queue

public abstract void setAsync (boolean async)

In async mode, the endpoint will automatically schedule incoming messages on a separate thread than the one on which they are received. Note that this does not imply there will be multiple threads receiving messages from the TrapEndpoint, only that there is a break in the thread.

Async mode is generally preferred over synchronous mode, as it decouples the network layer from the request processing layer. If the application using Trap provides its own thread dispatching with little overhead (computational time) after receiving a message from Trap, it may experience a performance gain from switching off async mode.

Note that Asynchronous mode is required for reordering messages! Specifically, messages in Trap may be reordered by the transports due to race- or network conditions. Reordering these messages – and redispatching them – may cause dropped or disconnected network connections, so Trap will NOT reorder incoming messages if in synchronous mode.

Parameters
async The new mode. True makes the endpoint asynchronous, while false disables it.

public abstract void setAuthentication (TrapAuthentication authentication)

Assigns an authentication instance to this TrapEndpoint. Implicitly, requires that this transport is authenticated from now on, on any incoming connection.

Some transports may require more fine-grained authentication than is afforded (i.e. authenticate every message, outgoing or incoming), and so they must individually access the TrapAuthentication instance using the getter.

Parameters
authentication An instance capable of fulfilling the TrapAuthentication contract.
Throws
TrapException If the authentication was not compatible with the transports.

public abstract void setBlockingTimeout (long timeout)

Sets the blocking timeout, when using a blocking queue. This determines the amount of time send(byte[]) will wait for queue space to open up before throwing an exception.

Parameters
timeout The new timeout, in milliseconds.

public abstract void setDelegate (TrapEndpointDelegate delegate, Object context)

This method is deprecated.
Since 1.1, the preferred signature is setDelegate(TrapDelegate, boolean). If a context is required, use the explicit setDelegateContext(Object) method.

Registers an object as a delegate to this endpoint. This delegate MUST implement TrapEndpointDelegate to receive callbacks. Optionally, this delegate may also implement OnObject to receive TrapObjects.

In some cases, Trap can transfer a Java object faster than the serial representation, e.g. when both endpoints are running in the same JVM. In those cases, registering a TrapEndpointObjectDelegate will yield a substantial performance improvement. Note that, depending on how the other side sent the message, there is no guarantee that the object will not be serialised, although if both support TrapObjects (i.e. remote uses .send(TrapObject) and local has a TrapEndpointObjectDelegate), no serialisation will occur.

If the remote endpoint sends a TrapObject, but this delegate is not set on the local endpoint, the TrapObject will be serialised on this end and sent to the TrapEndpointDelegate as usual.

This delegate is redundant for applications that will never run on the same JVM, as Trap cannot deserialise Java objects.

Parameters
delegate The delegate object.
context An optional object that will be supplied to the listener on every callback.

public abstract void setKeepaliveExpiry (long newExpiry)

Sets the keepalive expiry timeout. Alias for setKeepaliveExpiry(long) on the currently set predictor.

Parameters
newExpiry The new keepalive expiry time.

public abstract void setKeepaliveInterval (int newInterval)

Sets a new keepalive interval for the trap endpoint. The keepalive interval has one of three possible meanings:

  • A value of DISABLED will disable the keepalives.
  • A value of DEFAULT will cause each transport to use its internal estimate of what a good keepalive is.
  • A value of 1 <= n <= 999999 will specify the number of seconds between keepalive messages.
Any change on the TrapEndpoint level will affect all transports associated with this endpoint, overwriting any individual configuration the transports may have had. The inverse does not apply.

See the Trap Keepalive documentation for details on the keepalives.

Parameters
newInterval The new keepalive interval or policy.

public abstract void setMaxActiveTransports (int newMax)

Sets the maximum allowed simultaneous transports. See getMaxActiveTransports() for more information.

Parameters
newMax The new maximum number of transports.

Note that 0 (zero) is a permitted value for maximum number of transports. This will not close the Trap connection, but cause a non-deterministic sequence of transport opening and closings, causing an abnormal load on client, server and network, but making it difficult to predict which transport (and thus connection) will be used at any given point in time. This can be used to mitigate suspected MITM attacks, but is not recommended otherwise. This connection sequence is not guaranteed secure. This (zero) functionality is for experimental purposes, and may be removed at any time!

public abstract void setQueue (MessageQueue newQueue)

Assigns a new queue implementation for the outgoing message queue. This method allows the fine-tuning of outgoing message performance. See MessageQueue for a discussion on what the queues affect.

Setting a queue on the TrapEndpoint will only affect channels that have not been created yet. It will not replace the message queue of channels that have been created (i.e. accessed using getChannel(int) or send(byte[], int, boolean)).

Parameters
newQueue The new queue instance to use

public abstract void setQueueType (String type)

Like setQueue(MessageQueue), except it instantiates one of the built-in queues based on default parameters. Accepted arguments are BLOCKING_BYTE_QUEUE, BLOCKING_MESSAGE_QUEUE, REGULAR_BYTE_QUEUE or REGULAR_MESSAGE_QUEUE.

If a specific queue class is not required, this method is recommended, as it will pick up the most efficient built-in queue from the classpath based on the hosting JVM.

Parameters
type The new queue type to instantiate.

public abstract void setReconnectTimeout (long reconnectTimeout)

Sets the reconnect timeout. This timeout is the time that an endpoint is allowed to reside in the SLEEPING state without any transports or way to contact the other endpoint. After this time, the endpoint will be forcibly closed, if no transport or wakeup mechanism is present.

Parameters
reconnectTimeout The max number of milliseconds to sleep for.

public abstract void setTrapFormat (TrapMessage.Format trapFormat)

Sets the Trap message format for this endpoint. This method should only be called on clients, as the server will automatically match the format with the client format.

Trap has two message formats available; the regular one, using 8-bit serialization, and a 7-bit safe representation. The 7-bit one is recommended only for usage with pure JS clients that cannot otherwise handle binary data.

Parameters
trapFormat The new message format for this endpoint.