Class EventSource.Builder

java.lang.Object
com.launchdarkly.eventsource.EventSource.Builder
Enclosing class:
EventSource

public static final class EventSource.Builder extends Object
Builder for configuring EventSource.
  • Constructor Details

  • Method Details

    • 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 alternate ErrorStrategy implementations, such as ErrorStrategy.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 to ErrorStrategy.alwaysThrow()
      Returns:
      the builder
      Since:
      4.0.0
    • lastEventId

      public EventSource.Builder lastEventId(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, 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, see DefaultRetryDelayStrategy.

      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 by timeUnit
      timeUnit - the time unit, or TimeUnit.MILLISECONDS if null
      Returns:
      the builder
      See Also:
    • 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 of DefaultRetryDelayStrategy 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 to RetryDelayStrategy.defaultStrategy()
      Returns:
      the builder
      Since:
      4.0.0
      See Also:
    • retryDelayResetThreshold

      public EventSource.Builder retryDelayResetThreshold(long retryDelayResetThreshold, 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 by timeUnit
      timeUnit - the time unit, or TimeUnit.MILLISECONDS if null
      Returns:
      the builder
      Since:
      4.0.0
      See Also:
    • 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 than EventSource.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:
      IllegalArgumentException - if the size is less than or equal to zero
      Since:
      2.4.0
      See Also:
    • 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 - an LDLogger 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 a MessageEvent to the handler as soon as it receives the beginning of the event data, allowing the handler to read the data incrementally with MessageEvent.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 a data field-- setting MessageEvent.getDataReader() to a Reader 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 multiple data: 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 a StreamClosedWithIncompleteMessageException.

      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 a data: field appears, so it will only include fields that appeared before data:. In other words, if the SSE server happens to send data: first and event: second, MessageEvent.getEventName() will not contain the value of event: but will be MessageEvent.DEFAULT_EVENT_NAME instead; similarly, an id: field will be ignored if it appears after data: 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 a StreamClosedWithIncompleteMessageException.
      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

      public EventSource.Builder expectFields(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 if streamEventData(boolean) had not been enabled), to ensure that those fields are not lost if they appear after the data: 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:
    • build

      public EventSource build()
      Constructs an EventSource using the builder's current properties.
      Returns:
      the new EventSource instance