Class EventSource.Builder

  • Enclosing class:
    EventSource

    public static final class EventSource.Builder
    extends java.lang.Object
    Builder for EventSource.
    • Constructor Detail

      • Builder

        public Builder​(EventHandler handler,
                       java.net.URI uri)
        Creates a new builder.
        Parameters:
        handler - the event handler
        uri - 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 handler
        url - 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
      • 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 the maxReconnectTime(long, TimeUnit) value with each subsequent failure, unless it is reset as described in backoffResetThreshold(long, TimeUnit).
        Parameters:
        reconnectTime - the minimum delay, in whatever time unit is specified by timeUnit
        timeUnit - the time unit, or TimeUnit.MILLISECONDS if 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. See reconnectTime(long, TimeUnit). The default value is 30 seconds.
        Parameters:
        maxReconnectTime - the maximum delay, in whatever time unit is specified by timeUnit
        timeUnit - the time unit, or TimeUnit.MILLISECONDS if 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 by timeUnit
        timeUnit - the time unit, or TimeUnit.MILLISECONDS if 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 hostname
        proxyPort - the proxy port
        Returns:
        the builder
      • proxy

        public EventSource.Builder proxy​(java.net.Proxy proxy)
        Set the Proxy to 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 by timeUnit
        timeUnit - the time unit, or TimeUnit.MILLISECONDS if 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 by timeUnit
        timeUnit - the time unit, or TimeUnit.MILLISECONDS if 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, the EventSource will restart the connection.
        Parameters:
        readTimeout - the read timeout, in whatever time unit is specified by timeUnit
        timeUnit - the time unit, or TimeUnit.MILLISECONDS if null
        Returns:
        the builder
        See Also:
        EventSource.DEFAULT_READ_TIMEOUT_MILLIS
      • threadPriority

        public EventSource.Builder threadPriority​(java.lang.Integer threadPriority)
        Specifies the priority for threads created by EventSource.

        If this is left unset, or set to null, threads will inherit the default priority provided by Executors.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.ClientConfigurer is an interface with a single method, EventSource.Builder.ClientConfigurer.configure(okhttp3.OkHttpClient.Builder), that will be called with the OkHttpClient.Builder instance 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 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:
        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 - an LDLogger implementation, 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 executing EventHandler. 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 the EventHandler
        Returns:
        the builder
        Since:
        2.5.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.

        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 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.
        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...)
      • 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 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:
        streamEventData(boolean)
      • build

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

        protected okhttp3.OkHttpClient.Builder getClientBuilder()