Class EventSource.Builder
- java.lang.Object
-
- com.launchdarkly.eventsource.EventSource.Builder
-
- Enclosing class:
- EventSource
public static final class EventSource.Builder extends java.lang.ObjectBuilder forEventSource.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interfaceEventSource.Builder.ClientConfigurerAn interface for use withclientBuilderActions(ClientConfigurer).
-
Constructor Summary
Constructors Constructor Description Builder(EventHandler handler, java.net.URI uri)Creates a new builder.Builder(EventHandler handler, okhttp3.HttpUrl url)Creates a new builder.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description EventSource.BuilderbackoffResetThreshold(long backoffResetThreshold, java.util.concurrent.TimeUnit timeUnit)Sets the minimum amount of time that a connection must stay open before the EventSource resets its backoff delay.EventSource.Builderbody(okhttp3.RequestBody body)Sets the request body to be used for this EventSource client to use for requests to establish the EventSource.EventSourcebuild()Constructs anEventSourceusing the builder's current properties.EventSource.Builderclient(okhttp3.OkHttpClient client)Set a custom HTTP client that will be used to make the EventSource connection.EventSource.BuilderclientBuilderActions(EventSource.Builder.ClientConfigurer configurer)Specifies any type of configuration actions you want to perform on the OkHttpClient builder.EventSource.BuilderconnectionErrorHandler(ConnectionErrorHandler handler)Sets theConnectionErrorHandlerthat should process connection errors.EventSource.BuilderconnectTimeout(long connectTimeout, java.util.concurrent.TimeUnit timeUnit)Sets the connection timeout.EventSource.BuilderexpectFields(java.lang.String... fieldNames)Specifies that the application expects the server to send certain fields in every event.protected okhttp3.OkHttpClient.BuildergetClientBuilder()EventSource.Builderheaders(okhttp3.Headers headers)Set the headers to be sent when establishing the EventSource connection.EventSource.BuilderlastEventId(java.lang.String lastEventId)Sets the ID value of the last event received.EventSource.Builderlogger(LDLogger logger)Specifies a custom logger to receive EventSource logging.EventSource.BuildermaxEventTasksInFlight(int maxEventTasksInFlight)Specifies the maximum number of tasks that can be "in-flight" for the thread executingEventHandler.EventSource.BuildermaxReconnectTime(long maxReconnectTime, java.util.concurrent.TimeUnit timeUnit)Sets the maximum delay between connection attempts.EventSource.Buildermethod(java.lang.String method)Set the HTTP method used for this EventSource client to use for requests to establish the EventSource.EventSource.Buildername(java.lang.String name)Set the name for this EventSource client to be used when naming thread pools.EventSource.Builderproxy(java.lang.String proxyHost, int proxyPort)Set the HTTP proxy address to be used to make the EventSource connectionEventSource.Builderproxy(java.net.Proxy proxy)Set theProxyto be used to make the EventSource connection.EventSource.BuilderproxyAuthenticator(okhttp3.Authenticator proxyAuthenticator)Sets the Proxy Authentication mechanism if needed.EventSource.BuilderreadBufferSize(int readBufferSize)Specifies the fixed size of the buffer that EventSource uses to parse incoming data.EventSource.BuilderreadTimeout(long readTimeout, java.util.concurrent.TimeUnit timeUnit)Sets the read timeout.EventSource.BuilderreconnectTime(long reconnectTime, java.util.concurrent.TimeUnit timeUnit)Sets the minimum delay between connection attempts.EventSource.BuilderrequestTransformer(EventSource.RequestTransformer requestTransformer)Specifies an object that will be used to customize outgoing requests.EventSource.BuilderstreamEventData(boolean streamEventData)Specifies whether EventSource should send aMessageEventto the handler as soon as it receives the beginning of the event data, allowing the handler to read the data incrementally withMessageEvent.getDataReader().EventSource.BuilderthreadPriority(java.lang.Integer threadPriority)Specifies the priority for threads created byEventSource.EventSource.BuilderwriteTimeout(long writeTimeout, java.util.concurrent.TimeUnit timeUnit)Sets the write timeout.
-
-
-
Constructor Detail
-
Builder
public Builder(EventHandler handler, java.net.URI uri)
Creates a new builder.- Parameters:
handler- the event handleruri- the endpoint as a java.net.URI- Throws:
java.lang.IllegalArgumentException- if either argument is null, or if the endpoint is not HTTP or HTTPS
-
Builder
public Builder(EventHandler handler, okhttp3.HttpUrl url)
Creates a new builder.- Parameters:
handler- the event handlerurl- the endpoint as an OkHttp HttpUrl- Throws:
java.lang.IllegalArgumentException- if either argument is null, or if the endpoint is not HTTP or HTTPS- Since:
- 1.9.0
-
-
Method Detail
-
method
public EventSource.Builder method(java.lang.String method)
Set the HTTP method used for this EventSource client to use for requests to establish the EventSource.Defaults to "GET".
- Parameters:
method- the HTTP method name; if null or empty, "GET" is used as the default- Returns:
- the builder
-
body
public EventSource.Builder body(okhttp3.RequestBody body)
Sets the request body to be used for this EventSource client to use for requests to establish the EventSource.- Parameters:
body- the body to use in HTTP requests- Returns:
- the builder
-
requestTransformer
public EventSource.Builder requestTransformer(EventSource.RequestTransformer requestTransformer)
Specifies an object that will be used to customize outgoing requests. SeeEventSource.RequestTransformerfor details.- Parameters:
requestTransformer- the transformer object- Returns:
- the builder
- Since:
- 1.9.0
-
name
public EventSource.Builder name(java.lang.String name)
Set the name for this EventSource client to be used when naming thread pools. This is mainly useful when multiple EventSource clients exist within the same process.- Parameters:
name- the name (without any whitespaces)- Returns:
- the builder
-
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
-
reconnectTime
public EventSource.Builder reconnectTime(long reconnectTime, java.util.concurrent.TimeUnit timeUnit)
Sets the minimum delay between connection attempts. The actual delay may be slightly less or greater, since there is a random jitter. When there is a connection failure, the delay will start at this value and will increase exponentially up to themaxReconnectTime(long, TimeUnit)value with each subsequent failure, unless it is reset as described inbackoffResetThreshold(long, TimeUnit).- Parameters:
reconnectTime- the minimum delay, in whatever time unit is specified bytimeUnittimeUnit- the time unit, orTimeUnit.MILLISECONDSif null- Returns:
- the builder
- See Also:
EventSource.DEFAULT_RECONNECT_TIME_MILLIS
-
maxReconnectTime
public EventSource.Builder maxReconnectTime(long maxReconnectTime, java.util.concurrent.TimeUnit timeUnit)
Sets the maximum delay between connection attempts. SeereconnectTime(long, TimeUnit). The default value is 30 seconds.- Parameters:
maxReconnectTime- the maximum delay, in whatever time unit is specified bytimeUnittimeUnit- the time unit, orTimeUnit.MILLISECONDSif null- Returns:
- the builder
- See Also:
EventSource.DEFAULT_MAX_RECONNECT_TIME_MILLIS
-
backoffResetThreshold
public EventSource.Builder backoffResetThreshold(long backoffResetThreshold, java.util.concurrent.TimeUnit timeUnit)
Sets the minimum amount of time that a connection must stay open before the EventSource resets its backoff delay. If a connection fails before the threshold has elapsed, the delay before reconnecting will be greater than the last delay; if it fails after the threshold, the delay will start over at the initial minimum value. This prevents long delays from occurring on connections that are only rarely restarted.- Parameters:
backoffResetThreshold- the minimum time that a connection must stay open to avoid resetting the delay, in whatever time unit is specified bytimeUnittimeUnit- the time unit, orTimeUnit.MILLISECONDSif null- Returns:
- the builder
- See Also:
EventSource.DEFAULT_BACKOFF_RESET_THRESHOLD_MILLIS
-
headers
public EventSource.Builder headers(okhttp3.Headers headers)
Set the headers to be sent when establishing the EventSource connection.- Parameters:
headers- headers to be sent with the EventSource request- Returns:
- the builder
-
client
public EventSource.Builder client(okhttp3.OkHttpClient client)
Set a custom HTTP client that will be used to make the EventSource connection. If you're setting this along with other connection-related items (ie timeouts, proxy), you should do this first to avoid overwriting values.- Parameters:
client- the HTTP client- Returns:
- the builder
-
proxy
public EventSource.Builder proxy(java.lang.String proxyHost, int proxyPort)
Set the HTTP proxy address to be used to make the EventSource connection- Parameters:
proxyHost- the proxy hostnameproxyPort- the proxy port- Returns:
- the builder
-
proxy
public EventSource.Builder proxy(java.net.Proxy proxy)
Set theProxyto be used to make the EventSource connection.- Parameters:
proxy- the proxy- Returns:
- the builder
-
proxyAuthenticator
public EventSource.Builder proxyAuthenticator(okhttp3.Authenticator proxyAuthenticator)
Sets the Proxy Authentication mechanism if needed. Defaults to no auth.- Parameters:
proxyAuthenticator- the authentication mechanism- Returns:
- the builder
-
connectTimeout
public EventSource.Builder connectTimeout(long connectTimeout, java.util.concurrent.TimeUnit timeUnit)
Sets the connection timeout.- Parameters:
connectTimeout- the connection timeout, in whatever time unit is specified bytimeUnittimeUnit- the time unit, orTimeUnit.MILLISECONDSif null- Returns:
- the builder
- See Also:
EventSource.DEFAULT_CONNECT_TIMEOUT_MILLIS
-
writeTimeout
public EventSource.Builder writeTimeout(long writeTimeout, java.util.concurrent.TimeUnit timeUnit)
Sets the write timeout.- Parameters:
writeTimeout- the write timeout, in whatever time unit is specified bytimeUnittimeUnit- the time unit, orTimeUnit.MILLISECONDSif null- Returns:
- the builder
- See Also:
EventSource.DEFAULT_WRITE_TIMEOUT_MILLIS
-
readTimeout
public EventSource.Builder readTimeout(long readTimeout, java.util.concurrent.TimeUnit timeUnit)
Sets the read timeout. If a read timeout happens, theEventSourcewill restart the connection.- Parameters:
readTimeout- the read timeout, in whatever time unit is specified bytimeUnittimeUnit- the time unit, orTimeUnit.MILLISECONDSif null- Returns:
- the builder
- See Also:
EventSource.DEFAULT_READ_TIMEOUT_MILLIS
-
connectionErrorHandler
public EventSource.Builder connectionErrorHandler(ConnectionErrorHandler handler)
Sets theConnectionErrorHandlerthat should process connection errors.- Parameters:
handler- the error handler- Returns:
- the builder
-
threadPriority
public EventSource.Builder threadPriority(java.lang.Integer threadPriority)
Specifies the priority for threads created byEventSource.If this is left unset, or set to
null, threads will inherit the default priority provided byExecutors.defaultThreadFactory().- Parameters:
threadPriority- the thread priority, or null to ue the default- Returns:
- the builder
- Since:
- 2.2.0
-
clientBuilderActions
public EventSource.Builder clientBuilderActions(EventSource.Builder.ClientConfigurer configurer)
Specifies any type of configuration actions you want to perform on the OkHttpClient builder.EventSource.Builder.ClientConfigureris an interface with a single method,EventSource.Builder.ClientConfigurer.configure(okhttp3.OkHttpClient.Builder), that will be called with theOkHttpClient.Builderinstance being used by EventSource. In Java 8, this can be a lambda.It is not guaranteed to be called in any particular order relative to other configuration actions specified by this Builder, so if you are using more than one method, do not attempt to overwrite the same setting in two ways.
// Java 8 example (lambda) eventSourceBuilder.clientBuilderActions(b -> { b.sslSocketFactory(mySocketFactory, myTrustManager); }); // Java 7 example (anonymous class) eventSourceBuilder.clientBuilderActions(new EventSource.Builder.ClientConfigurer() { public void configure(OkHttpClient.Builder v) { b.sslSocketFactory(mySocketFactory, myTrustManager); } });- Parameters:
configurer- a ClientConfigurer (or lambda) that will act on the HTTP client builder- Returns:
- the builder
- Since:
- 1.10.0
-
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
ByteArrayOutputStreamto 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
LDLoggertype 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- anLDLoggerimplementation, or null for no logging- Returns:
- the builder
- Since:
- 2.7.0
-
maxEventTasksInFlight
public EventSource.Builder maxEventTasksInFlight(int maxEventTasksInFlight)
Specifies the maximum number of tasks that can be "in-flight" for the thread executingEventHandler. A semaphore will be used to artificially constrain the number of tasks sitting in the queue fronting the event handler thread. When this limit is reached the stream thread will block until the backpressure passes.For backward compatibility reasons the default is "unbounded".
- Parameters:
maxEventTasksInFlight- the maximum number of tasks/messages that can be in-flight for theEventHandler- Returns:
- the builder
- Since:
- 2.5.0
-
streamEventData
public EventSource.Builder streamEventData(boolean streamEventData)
Specifies whether EventSource should send aMessageEventto 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 adatafield-- settingMessageEvent.getDataReader()to aReaderthat 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, theReaderwill emit a newline character between each and will not see the "data:" field names. TheReaderwill report "end of stream" as soon as the event is terminated normally by a blank line.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:
- EventSource cannot continue processing further events on the stream until the handler's
EventHandler.onMessage(String, MessageEvent)method has returned. - The
MessageEventis 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_NAMEinstead; 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.
- 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...)
- EventSource cannot continue processing further events on the stream until the handler's
-
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: helloSuch 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 anEventSourceusing the builder's current properties.- Returns:
- the new EventSource instance
-
getClientBuilder
protected okhttp3.OkHttpClient.Builder getClientBuilder()
-
-