Class EventSource.Builder
- java.lang.Object
-
- com.launchdarkly.eventsource.EventSource.Builder
-
- Enclosing class:
- EventSource
public static final class EventSource.Builder extends java.lang.Object
Builder for configuringEventSource
.
-
-
Constructor Summary
Constructors Constructor Description Builder(ConnectStrategy connectStrategy)
Creates a new builder, specifying how it will connect to a stream.Builder(java.net.URI uri)
Creates a new builder that connects via HTTP, specifying only the stream URI.Builder(java.net.URL url)
Creates a new builder that connects via HTTP, specifying only the stream URI.Builder(okhttp3.HttpUrl url)
Creates a new builder that connects via HTTP, specifying only the stream URI.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description EventSource
build()
Constructs anEventSource
using the builder's current properties.EventSource.Builder
errorStrategy(ErrorStrategy errorStrategy)
Specifies a strategy for determining whether to handle errors transparently or throw them as exceptions.EventSource.Builder
expectFields(java.lang.String... fieldNames)
Specifies that the application expects the server to send certain fields in every event.EventSource.Builder
lastEventId(java.lang.String lastEventId)
Sets the ID value of the last event received.EventSource.Builder
logger(LDLogger logger)
Specifies a custom logger to receive EventSource logging.EventSource.Builder
readBufferSize(int readBufferSize)
Specifies the fixed size of the buffer that EventSource uses to parse incoming data.EventSource.Builder
retryDelay(long retryDelay, java.util.concurrent.TimeUnit timeUnit)
Sets the base delay between connection attempts.EventSource.Builder
retryDelayResetThreshold(long retryDelayResetThreshold, java.util.concurrent.TimeUnit timeUnit)
Sets the minimum amount of time that a connection must stay open before the EventSource resets its delay strategy.EventSource.Builder
retryDelayStrategy(RetryDelayStrategy retryDelayStrategy)
Specifies a strategy for determining the retry delay after an error.EventSource.Builder
streamEventData(boolean streamEventData)
Specifies whether EventSource should send aMessageEvent
to the handler as soon as it receives the beginning of the event data, allowing the handler to read the data incrementally withMessageEvent.getDataReader()
.
-
-
-
Constructor Detail
-
Builder
public Builder(ConnectStrategy connectStrategy)
Creates a new builder, specifying how it will connect to a stream.The
ConnectStrategy
will handle all details of how to obtain an input stream for the EventSource to consume. By default, this isHttpConnectStrategy
, which makes HTTP requests. To customize the HTTP behavior, you can use methods ofHttpConnectStrategy
:EventSource.Builder builder = new EventSource.Builder( ConnectStrategy.http(myStreamUri) .headers(myCustomHeaders) .connectTimeout(10, TimeUnit.SECONDS) );
Or, if you want to consume an input stream from some other source, you can create your own subclass of
ConnectStrategy
.- Parameters:
connectStrategy
- the object that will manage the input stream; must not be null- Throws:
java.lang.IllegalArgumentException
- if the argument is null- Since:
- 4.0.0
- See Also:
Builder(URI)
,Builder(HttpUrl)
-
Builder
public Builder(java.net.URI uri)
Creates a new builder that connects via HTTP, specifying only the stream URI.Use this method if you do not need to configure any HTTP-related properties besides the URI. To specify a custom HTTP configuration instead, use
Builder(ConnectStrategy)
withConnectStrategy.http(URI)
.- Parameters:
uri
- the stream URI- Throws:
java.lang.IllegalArgumentException
- if the argument is null, or if the endpoint is not HTTP or HTTPS- See Also:
Builder(ConnectStrategy)
,Builder(URL)
,Builder(HttpUrl)
-
Builder
public Builder(java.net.URL url)
Creates a new builder that connects via HTTP, specifying only the stream URI.This is the same as
Builder(URI)
, but using theURL
type.- Parameters:
url
- the stream URL- Throws:
java.lang.IllegalArgumentException
- if the argument is null, or if the endpoint is not HTTP or HTTPS- See Also:
Builder(ConnectStrategy)
,Builder(URI)
,Builder(HttpUrl)
-
Builder
public Builder(okhttp3.HttpUrl url)
Creates a new builder that connects via HTTP, specifying only the stream URI.This is the same as
Builder(URI)
, but using the OkHttp typeHttpUrl
.- Parameters:
url
- the stream URL- Throws:
java.lang.IllegalArgumentException
- if the argument is null, or if the endpoint is not HTTP or HTTPS- Since:
- 1.9.0
- See Also:
Builder(ConnectStrategy)
,Builder(URI)
,Builder(URL)
-
-
Method Detail
-
errorStrategy
public EventSource.Builder errorStrategy(ErrorStrategy errorStrategy)
Specifies a strategy for determining whether to handle errors transparently or throw them as exceptions.By default, any failed connection attempt, or failure of an existing connection, will be thrown as a
StreamException
when you try to use the stream. You may instead use alternateErrorStrategy
implementations, such asErrorStrategy.alwaysContinue()
, or a custom implementation, to allow EventSource to continue after an error.- Parameters:
errorStrategy
- the object that will control error handling; if null, defaults toErrorStrategy.alwaysThrow()
- Returns:
- the builder
- Since:
- 4.0.0
-
lastEventId
public EventSource.Builder lastEventId(java.lang.String lastEventId)
Sets the ID value of the last event received.This will be sent to the remote server on the initial connection request, allowing the server to skip past previously sent events if it supports this behavior. Once the connection is established, this value will be updated whenever an event is received that has an ID. Whether event IDs are supported depends on the server; it may ignore this value.
- Parameters:
lastEventId
- the last event identifier- Returns:
- the builder
- Since:
- 2.0.0
-
retryDelay
public EventSource.Builder retryDelay(long retryDelay, java.util.concurrent.TimeUnit timeUnit)
Sets the base delay between connection attempts.The actual delay may be slightly less or greater, depending on the strategy specified by
retryDelayStrategy(RetryDelayStrategy)
. The default behavior is to increase the delay exponentially from this base value on each attempt, up to a configured maximum, substracting a random jitter; for more details, seeDefaultRetryDelayStrategy
.If you set the base delay to zero, the backoff logic will not apply-- multiplying by zero gives zero every time. Therefore, use a zero delay with caution since it could cause a reconnect storm during a service interruption.
- Parameters:
retryDelay
- the base delay, in whatever time unit is specified bytimeUnit
timeUnit
- the time unit, orTimeUnit.MILLISECONDS
if null- Returns:
- the builder
- See Also:
EventSource.DEFAULT_RETRY_DELAY_MILLIS
,retryDelayStrategy(RetryDelayStrategy)
,retryDelayResetThreshold(long, TimeUnit)
-
retryDelayStrategy
public EventSource.Builder retryDelayStrategy(RetryDelayStrategy retryDelayStrategy)
Specifies a strategy for determining the retry delay after an error.Whenever EventSource tries to start a new connection after a stream failure, it delays for an amount of time that is determined by two parameters: the base retry delay (
retryDelay(long, TimeUnit)
), and the retry delay strategy which transforms the base retry delay in some way. The default behavior is to apply an exponential backoff and jitter. You may instead use a modified version ofDefaultRetryDelayStrategy
to customize the backoff and jitter, or a custom implementation with any other logic.- Parameters:
retryDelayStrategy
- the object that will control retry delays; if null, defaults toRetryDelayStrategy.defaultStrategy()
- Returns:
- the builder
- Since:
- 4.0.0
- See Also:
retryDelay(long, TimeUnit)
,retryDelayResetThreshold(long, TimeUnit)
-
retryDelayResetThreshold
public EventSource.Builder retryDelayResetThreshold(long retryDelayResetThreshold, java.util.concurrent.TimeUnit timeUnit)
Sets the minimum amount of time that a connection must stay open before the EventSource resets its delay strategy.When using the default strategy (
RetryDelayStrategy.defaultStrategy()
), this means that the delay before each reconnect attempt will be greater than the last delay unless the current connection lasted longer than the threshold, in which case the delay will start over at the initial minimum value. This prevents long delays from occurring on connections that are only rarely restarted.- Parameters:
retryDelayResetThreshold
- the minimum time that a connection must stay open to avoid resetting the delay, in whatever time unit is specified bytimeUnit
timeUnit
- the time unit, orTimeUnit.MILLISECONDS
if null- Returns:
- the builder
- Since:
- 4.0.0
- See Also:
EventSource.DEFAULT_RETRY_DELAY_RESET_THRESHOLD_MILLIS
-
readBufferSize
public EventSource.Builder readBufferSize(int readBufferSize)
Specifies the fixed size of the buffer that EventSource uses to parse incoming data.EventSource allocates a single buffer to hold data from the stream as it scans for line breaks. If no lines of data from the stream exceed this size, it will keep reusing the same space; if a line is longer than this size, it creates a temporary
ByteArrayOutputStream
to accumulate data for that line, which is less efficient. Therefore, if an application expects to see many lines in the stream that are longer thanEventSource.DEFAULT_READ_BUFFER_SIZE
, it can specify a larger buffer size to avoid unnecessary heap allocations.- Parameters:
readBufferSize
- the buffer size- Returns:
- the builder
- Throws:
java.lang.IllegalArgumentException
- if the size is less than or equal to zero- Since:
- 2.4.0
- See Also:
EventSource.DEFAULT_READ_BUFFER_SIZE
-
logger
public EventSource.Builder logger(LDLogger logger)
Specifies a custom logger to receive EventSource logging.This method uses the
LDLogger
type from com.launchdarkly.logging, a facade that provides several logging implementations as well as the option to forward log output to SLF4J or another framework. Here is an example of configuring it to use the basic console logging implementation, and to tag the output with the name "logname":// import com.launchdarkly.logging.*; builder.logger( LDLogger.withAdapter(Logs.basic(), "logname") );
If you do not provide a logger, the default is there is no log output.
- Parameters:
logger
- anLDLogger
implementation, or null for no logging- Returns:
- the builder
- Since:
- 2.7.0
-
streamEventData
public EventSource.Builder streamEventData(boolean streamEventData)
Specifies whether EventSource should send aMessageEvent
to the handler as soon as it receives the beginning of the event data, allowing the handler to read the data incrementally withMessageEvent.getDataReader()
.The default for this property is
false
, meaning that EventSource will always read the entire event into memory before dispatching it to the handler.If you set it to
true
, it will instead call the handler as soon as it sees adata
field-- settingMessageEvent.getDataReader()
to aReader
that reads directly from the data as it arrives. The EventSource will perform any necessary parsing under the covers, so that for instance if there are multipledata:
lines in the event, the Reader will emit a newline character between each and will not see the "data:" field names. The Reader will report "end of stream" as soon as the event is terminated normally by a blank line. If the stream is closed before normal termination of the event, the Reader will throw aStreamClosedWithIncompleteMessageException
.This mode is designed for applications that expect very large data items to be delivered over SSE. Use it with caution, since there are several limitations:
- The
MessageEvent
is constructed as soon as adata:
field appears, so it will only include fields that appeared beforedata:
. In other words, if the SSE server happens to senddata:
first andevent:
second,MessageEvent.getEventName()
will not contain the value ofevent:
but will beMessageEvent.DEFAULT_EVENT_NAME
instead; similarly, anid:
field will be ignored if it appears afterdata:
in this mode. Therefore, you should only use this mode if the server's behavior is predictable in this regard. - The SSE protocol specifies that an event should be processed only if it is terminated by a blank line, but
in this mode the handler will receive the event as soon as a
data:
field appears-- so, if the stream happens to cut off abnormally without a trailing blank line, technically you will be receiving an incomplete event that should have been ignored. You will know this has happened ifbecause reading from the Reader throws aStreamClosedWithIncompleteMessageException
.
- Parameters:
streamEventData
- true if events should be dispatched immediately with asynchronous data rather than read fully before dispatch- Returns:
- the builder
- Since:
- 2.6.0
- See Also:
expectFields(String...)
- The
-
expectFields
public EventSource.Builder expectFields(java.lang.String... fieldNames)
Specifies that the application expects the server to send certain fields in every event.This setting makes no difference unless you have enabled
streamEventData(boolean)
mode. In that case, it causes EventSource to only use the streaming data mode for an event if the specified fields have already been received; otherwise, it will buffer the whole event (as ifstreamEventData(boolean)
had not been enabled), to ensure that those fields are not lost if they appear after thedata:
field.For instance, if you had called
expectFields("event")
, then EventSource would be able to use streaming data mode for the following SSE response--event: hello data: here is some very long streaming data
--but it would buffer the full event if the server used the opposite order:
data: here is some very long streaming data event: hello
Such behavior is not automatic because in some applications, there might never be an
event:
field, and EventSource has no way to anticipate this.- Parameters:
fieldNames
- a list of SSE field names (case-sensitive; any names other than "event" and "id" are ignored)- Returns:
- the builder
- Since:
- 2.6.0
- See Also:
streamEventData(boolean)
-
build
public EventSource build()
Constructs anEventSource
using the builder's current properties.- Returns:
- the new EventSource instance
-
-