Class BayeuxClient
- All Implemented Interfaces:
Bayeux
,ClientSession
,Session
,org.eclipse.jetty.util.component.Dumpable
- Direct Known Subclasses:
OortComet
public class BayeuxClient extends AbstractClientSession implements Bayeux
BayeuxClient is the implementation of a client for the Bayeux protocol.
A BayeuxClient can receive/publish messages from/to a Bayeux server, and it is the counterpart in Java of the JavaScript library used in browsers (and as such it is ideal for Swing applications, load testing tools, etc.).
A BayeuxClient handshakes with a Bayeux server
and then subscribes ClientSessionChannel.MessageListener
to channels in order
to receive messages, and may also publish messages to the Bayeux server.
BayeuxClient relies on pluggable transports for communication with the Bayeux
server, and the most common transport is LongPollingTransport
, which uses
HTTP to transport Bayeux messages and it is based on
Jetty's HTTP client.
When the communication with the server is finished, the BayeuxClient can be disconnected from the Bayeux server.
Typical usage:
// Handshake String url = "http://localhost:8080/cometd"; BayeuxClient client = new BayeuxClient(url, LongPollingTransport.create(null)); client.handshake(); client.waitFor(1000, BayeuxClient.State.CONNECTED); // Subscription to channels ClientSessionChannel channel = client.getChannel("/foo"); channel.subscribe(new ClientSessionChannel.MessageListener() { public void onMessage(ClientSessionChannel channel, Message message) { // Handle the message } }); // Publishing to channels Map<String, Object> data = new HashMap<String, Object>(); data.put("bar", "baz"); channel.publish(data); // Disconnecting client.disconnect(); client.waitFor(1000, BayeuxClient.State.DISCONNECTED);
-
Nested Class Summary
Nested Classes Modifier and Type Class Description protected class
BayeuxClient.BayeuxClientChannel
A channel scoped to this BayeuxClient.static class
BayeuxClient.State
The states that a BayeuxClient may assumeNested classes/interfaces inherited from class org.cometd.common.AbstractClientSession
AbstractClientSession.AbstractSessionChannel
Nested classes/interfaces inherited from interface org.cometd.bayeux.client.ClientSession
ClientSession.Extension, ClientSession.MessageListener
-
Field Summary
Fields Modifier and Type Field Description static String
BACKOFF_INCREMENT_OPTION
static String
BAYEUX_VERSION
protected org.slf4j.Logger
logger
static String
MAX_BACKOFF_OPTION
-
Constructor Summary
Constructors Constructor Description BayeuxClient(String url, ScheduledExecutorService scheduler, ClientTransport transport, ClientTransport... transports)
Creates a BayeuxClient that will connect to the Bayeux server at the given URL, with the given scheduler and with the given transport(s).BayeuxClient(String url, ClientTransport transport, ClientTransport... transports)
Creates a BayeuxClient that will connect to the Bayeux server at the given URL and with the given transport(s). -
Method Summary
Modifier and Type Method Description void
abort()
Interrupts abruptly the communication with the Bayeux server.void
disconnect()
Disconnects this session, ending the link between the client and the server peers.boolean
disconnect(long timeout)
Performs adisconnect
and uses the giventimeout
to wait for the disconnect to complete.void
disconnect(ClientSessionChannel.MessageListener callback)
Disconnects this session, ending the link between the client and the server peers.protected void
enqueueSend(Message.Mutable message)
List<String>
getAllowedTransports()
long
getBackoff()
long
getBackoffIncrement()
HttpCookie
getCookie(String name)
Retrieves the first cookie with the given name, if available.CookieStore
getCookieStore()
String
getId()
The clientId of the session.Set<String>
getKnownTransportNames()
long
getMaxBackoff()
Object
getOption(String qualifiedName)
Set<String>
getOptionNames()
Map<String,Object>
getOptions()
protected BayeuxClient.State
getState()
ClientTransport
getTransport()
ClientTransport
getTransport(String transport)
String
getURL()
void
handshake()
Equivalent tohandshake(null)
.BayeuxClient.State
handshake(long waitMs)
Performs the handshake and waits at most the given time for the handshake to complete.void
handshake(Map<String,Object> handshakeFields)
Equivalent tohandshake(template, null)
.BayeuxClient.State
handshake(Map<String,Object> template, long waitMs)
Performs the handshake with the given template and waits at most the given time for the handshake to complete.void
handshake(Map<String,Object> fields, ClientSessionChannel.MessageListener callback)
Initiates the bayeux protocol handshake with the server(s).void
handshake(ClientSessionChannel.MessageListener callback)
protected void
initialize()
boolean
isConnected()
A connected session is a session where the link between the client and the server has been established.boolean
isDisconnected()
boolean
isHandshook()
A handshook session is a session where the handshake has successfully completedprotected void
messagesFailure(Throwable cause, List<? extends Message> messages)
protected AbstractClientSession.AbstractSessionChannel
newChannel(ChannelId channelId)
protected ChannelId
newChannelId(String channelId)
void
onFailure(Throwable failure, List<? extends Message> messages)
Callback method invoked when the given messages have failed to be sent.void
onMessages(List<Message.Mutable> messages)
Callback method invoke when the given messages have just arrived from the Bayeux server.void
onSending(List<? extends Message> messages)
Callback method invoked when the given messages have hit the network towards the Bayeux server.protected void
onTransportFailure(String oldTransportName, String newTransportName, Throwable failure)
protected void
onTransportFailure(Message message, ClientTransport.FailureInfo failureInfo, ClientTransport.FailureHandler handler)
protected void
processConnect(Message.Mutable connect)
protected void
processDisconnect(Message.Mutable disconnect)
protected void
processHandshake(Message.Mutable handshake)
protected void
processMessage(Message.Mutable message)
void
putCookie(HttpCookie cookie)
protected boolean
scheduleConnect(long interval, long backOff)
protected boolean
scheduleHandshake(long interval, long backOff)
protected void
send(Message.Mutable message)
protected void
sendBatch()
protected boolean
sendConnect()
protected boolean
sendHandshake()
protected boolean
sendMessages(List<Message.Mutable> messages)
void
setOption(String qualifiedName, Object value)
protected void
terminate()
String
toString()
boolean
waitFor(long waitMs, BayeuxClient.State state, BayeuxClient.State... states)
Waits for this BayeuxClient to reach the given state(s) within the given time.Methods inherited from class org.cometd.common.AbstractClientSession
addExtension, batch, dump, dump, endBatch, extendRcv, extendSend, getAttribute, getAttributeNames, getChannel, getChannel, getChannels, getExtensions, isBatching, newMessage, newMessageId, notifyListener, notifyListeners, receive, registerCallback, registerSubscriber, remoteCall, removeAttribute, removeExtension, resetSubscriptions, setAttribute, startBatch, unregisterCallback, unregisterSubscriber
-
Field Details
-
BACKOFF_INCREMENT_OPTION
- See Also:
- Constant Field Values
-
MAX_BACKOFF_OPTION
- See Also:
- Constant Field Values
-
BAYEUX_VERSION
- See Also:
- Constant Field Values
-
logger
protected final org.slf4j.Logger logger
-
-
Constructor Details
-
BayeuxClient
Creates a BayeuxClient that will connect to the Bayeux server at the given URL and with the given transport(s).
This constructor allocates a new
scheduler
; it is recommended that when creating a large number of BayeuxClients a shared scheduler is used.- Parameters:
url
- the Bayeux server URL to connect totransport
- the default (mandatory) transport to usetransports
- additional optional transports to use in case the default transport cannot be used- See Also:
BayeuxClient(String, ScheduledExecutorService, ClientTransport, ClientTransport...)
-
BayeuxClient
public BayeuxClient(String url, ScheduledExecutorService scheduler, ClientTransport transport, ClientTransport... transports)Creates a BayeuxClient that will connect to the Bayeux server at the given URL, with the given scheduler and with the given transport(s).
- Parameters:
url
- the Bayeux server URL to connect toscheduler
- the scheduler to use for scheduling timed operationstransport
- the default (mandatory) transport to usetransports
- additional optional transports to use in case the default transport cannot be used
-
-
Method Details
-
getURL
- Returns:
- the URL passed when constructing this instance
-
getBackoff
public long getBackoff()- Returns:
- the current period of time to wait before trying to reconnect
-
getBackoffIncrement
public long getBackoffIncrement()- Returns:
- the period of time that increments the pause to wait before trying to reconnect after each failed attempt to connect to the Bayeux server
- See Also:
getMaxBackoff()
-
getMaxBackoff
public long getMaxBackoff()- Returns:
- the maximum pause to wait before trying to reconnect after each failed attempt to connect to the Bayeux server
- See Also:
getBackoffIncrement()
-
getCookieStore
-
getCookie
Retrieves the first cookie with the given name, if available.
Note that currently only HTTP transports support cookies.
- Parameters:
name
- the cookie name- Returns:
- the cookie, or null if no such cookie is found
- See Also:
putCookie(HttpCookie)
-
putCookie
-
getId
Description copied from interface:Session
The clientId of the session.
This would more correctly be called a "sessionId", but for backwards compatibility with the Bayeux protocol, it is a field called "clientId" that identifies a session.
-
isHandshook
public boolean isHandshook()Description copied from interface:Session
A handshook session is a session where the handshake has successfully completed
- Specified by:
isHandshook
in interfaceSession
- Returns:
- whether the session is handshook
-
isConnected
public boolean isConnected()Description copied from interface:Session
A connected session is a session where the link between the client and the server has been established.
- Specified by:
isConnected
in interfaceSession
- Returns:
- whether the session is connected
- See Also:
Session.disconnect()
-
isDisconnected
public boolean isDisconnected()- Returns:
- whether this BayeuxClient is terminating or disconnected
-
getState
- Returns:
- the current state of this BayeuxClient
-
handshake
public void handshake()Description copied from interface:ClientSession
Equivalent to
handshake(null)
.- Specified by:
handshake
in interfaceClientSession
-
handshake
Description copied from interface:ClientSession
Equivalent to
handshake(template, null)
.- Specified by:
handshake
in interfaceClientSession
- Parameters:
handshakeFields
- additional fields to add to the handshake message.
-
handshake
-
handshake
Description copied from interface:ClientSession
Initiates the bayeux protocol handshake with the server(s).
The handshake initiated by this method is asynchronous and does not wait for the handshake response.
- Specified by:
handshake
in interfaceClientSession
- Parameters:
fields
- additional fields to add to the handshake message.callback
- the message listener to notify of the handshake result
-
handshake
Performs the handshake and waits at most the given time for the handshake to complete.
When this method returns, the handshake may have failed (for example because the Bayeux server denied it), so it is important to check the return value to know whether the handshake completed or not.
- Parameters:
waitMs
- the time to wait for the handshake to complete- Returns:
- the state of this BayeuxClient
- See Also:
handshake(Map, long)
-
handshake
Performs the handshake with the given template and waits at most the given time for the handshake to complete.
When this method returns, the handshake may have failed (for example because the Bayeux server denied it), so it is important to check the return value to know whether the handshake completed or not.
- Parameters:
template
- the template object to be merged with the handshake messagewaitMs
- the time to wait for the handshake to complete- Returns:
- the state of this BayeuxClient
- See Also:
handshake(long)
-
sendHandshake
protected boolean sendHandshake() -
waitFor
Waits for this BayeuxClient to reach the given state(s) within the given time.
- Parameters:
waitMs
- the time to wait to reach the given state(s)state
- the state to reachstates
- additional states to reach in alternative- Returns:
- true if one of the state(s) has been reached within the given time, false otherwise
-
sendConnect
protected boolean sendConnect() -
newChannelId
- Specified by:
newChannelId
in classAbstractClientSession
-
newChannel
- Specified by:
newChannel
in classAbstractClientSession
-
sendBatch
protected void sendBatch()- Specified by:
sendBatch
in classAbstractClientSession
-
sendMessages
-
disconnect
public void disconnect()Description copied from interface:Session
Disconnects this session, ending the link between the client and the server peers.- Specified by:
disconnect
in interfaceSession
- See Also:
disconnect(long)
-
disconnect
Description copied from interface:ClientSession
Disconnects this session, ending the link between the client and the server peers.
- Specified by:
disconnect
in interfaceClientSession
- Parameters:
callback
- the message listener to notify of the disconnect result
-
disconnect
public boolean disconnect(long timeout)Performs a
disconnect
and uses the giventimeout
to wait for the disconnect to complete.When a disconnect is sent to the server, the server also wakes up the long poll that may be outstanding, so that a connect reply message may arrive to the client later than the disconnect reply message.
This method waits for the given
timeout
for the disconnect reply, but also waits the same timeout for the last connect reply; in the worst case the maximum time waited will therefore be twice the giventimeout
parameter.This method returns true if the disconnect reply message arrived within the given
timeout
parameter, no matter if the connect reply message arrived or not.- Parameters:
timeout
- the timeout to wait for the disconnect to complete- Returns:
- true if the disconnect completed within the given timeout
-
abort
public void abort()Interrupts abruptly the communication with the Bayeux server.
This method may be useful to simulate network failures.
- See Also:
disconnect()
-
messagesFailure
-
processHandshake
-
processConnect
-
processDisconnect
-
processMessage
-
scheduleHandshake
protected boolean scheduleHandshake(long interval, long backOff) -
scheduleConnect
protected boolean scheduleConnect(long interval, long backOff) -
getAllowedTransports
- Specified by:
getAllowedTransports
in interfaceBayeux
- Returns:
- the ordered list of transport names that will be used in the negotiation of transports with the other peer.
- See Also:
Bayeux.getKnownTransportNames()
-
getKnownTransportNames
- Specified by:
getKnownTransportNames
in interfaceBayeux
- Returns:
- the set of known transport names of this
Bayeux
object. - See Also:
Bayeux.getAllowedTransports()
-
getTransport
- Specified by:
getTransport
in interfaceBayeux
- Parameters:
transport
- the transport name- Returns:
- the transport with the given name or null if no such transport exist
-
getTransport
-
initialize
protected void initialize() -
terminate
protected void terminate() -
getOption
- Specified by:
getOption
in interfaceBayeux
- Parameters:
qualifiedName
- the configuration option name- Returns:
- the configuration option with the given
qualifiedName
- See Also:
Bayeux.setOption(String, Object)
,Bayeux.getOptionNames()
-
setOption
- Specified by:
setOption
in interfaceBayeux
- Parameters:
qualifiedName
- the configuration option namevalue
- the configuration option value- See Also:
Bayeux.getOption(String)
-
getOptionNames
- Specified by:
getOptionNames
in interfaceBayeux
- Returns:
- the set of configuration options
- See Also:
Bayeux.getOption(String)
-
getOptions
- Returns:
- the options that configure with BayeuxClient.
-
send
- Specified by:
send
in classAbstractClientSession
-
enqueueSend
-
onSending
Callback method invoked when the given messages have hit the network towards the Bayeux server.
The messages may not be modified, and any modification will be useless because the message have already been sent.
- Parameters:
messages
- the messages sent
-
onMessages
Callback method invoke when the given messages have just arrived from the Bayeux server.
The messages may be modified, but it's suggested to use
ClientSession.Extension
s instead.Extensions will be processed after the invocation of this method.
- Parameters:
messages
- the messages arrived
-
onFailure
Callback method invoked when the given messages have failed to be sent.
The default implementation logs the failure at DEBUG level.
- Parameters:
failure
- the exception that caused the failuremessages
- the messages being sent
-
onTransportFailure
protected void onTransportFailure(Message message, ClientTransport.FailureInfo failureInfo, ClientTransport.FailureHandler handler) -
onTransportFailure
-
toString
-