signature:
public class CatalogEndpoint { /** * Retrieves all services for a given datacenter with { @ link io . advantageous . consul . domain . option . RequestOptions } .
 * GET / v1 / catalog / services ? dc = { datacenter }
 * @ param datacenter datacenter
 * @ param tag tag
 * @ param requestOptions The Query Options to use .
 * @ return A { @ link io . advantageous . consul . domain . ConsulResponse } containing a map of service name to list of tags . */
public ConsulResponse < Map < String , List < String > > > getServices ( @ SuppressWarnings ( "SameParameterValue" ) final String datacenter , @ SuppressWarnings ( "SameParameterValue" ) final String tag , final RequestOptions requestOptions ) { } }

implementation:
final URI uri = createURI ( "/services" ) ; final HttpRequestBuilder httpRequestBuilder = RequestUtils . getHttpRequestBuilder ( datacenter , tag , requestOptions , "/" ) ; HTTP . Response httpResponse = HTTP . getResponse ( uri . toString ( ) + "?" + httpRequestBuilder . paramString ( ) ) ; if ( httpResponse . code ( ) != 200 ) { die ( "Unable to retrieve the datacenters" , uri , httpResponse . code ( ) , httpResponse . body ( ) ) ; } // noinspection unchecked
return ( ConsulResponse < Map < String , List < String > > > ) ( Object ) RequestUtils . consulResponse ( Map . class , httpResponse ) ;


signature:
public class CatalogEndpoint { /** * Retrieves a single service .
 * GET / v1 / catalog / service / { service }
 * @ param serviceName service name
 * @ return A { @ link io . advantageous . consul . domain . ConsulResponse } containing
 * { @ link io . advantageous . consul . domain . CatalogService } objects . */
public ConsulResponse < List < CatalogService > > getService ( @ SuppressWarnings ( "SameParameterValue" ) final String serviceName ) { } }

implementation: return getService ( serviceName , null , null , RequestOptions . BLANK ) ;


signature:
public class CatalogEndpoint { /** * Retrieves a single service for a given datacenter .
 * GET / v1 / catalog / service / { service } ? dc = { datacenter }
 * @ param serviceName service name
 * @ param datacenter datacenter
 * @ param tag tag
 * @ return A { @ link io . advantageous . consul . domain . ConsulResponse } containing
 * { @ link io . advantageous . consul . domain . CatalogService } objects . */
public ConsulResponse < List < CatalogService > > getService ( final String serviceName , final String datacenter , final String tag ) { } }

implementation: return getService ( serviceName , datacenter , tag , RequestOptions . BLANK ) ;


signature:
public class CatalogEndpoint { /** * Retrieves a single service with { @ link io . advantageous . consul . domain . option . RequestOptions } .
 * GET / v1 / catalog / service / { service }
 * @ param serviceName service name
 * @ param requestOptions The Query Options to use .
 * @ return A { @ link io . advantageous . consul . domain . ConsulResponse } containing
 * { @ link io . advantageous . consul . domain . CatalogService } objects . */
public ConsulResponse < List < CatalogService > > getService ( String serviceName , RequestOptions requestOptions ) { } }

implementation: return getService ( serviceName , null , null , requestOptions ) ;


signature:
public class CatalogEndpoint { /** * Retrieves a single node .
 * GET / v1 / catalog / node / { node }
 * @ param node node
 * @ return A list of matching { @ link io . advantageous . consul . domain . CatalogService } objects . */
public ConsulResponse < CatalogNode > getNode ( final String node ) { } }

implementation: return getNode ( node , null , null , RequestOptions . BLANK ) ;


signature:
public class CatalogEndpoint { /** * Retrieves a single node for a given datacenter .
 * GET / v1 / catalog / node / { node } ? dc = { datacenter }
 * @ param node node
 * @ param datacenter dc
 * @ param tag tag
 * @ return A list of matching { @ link io . advantageous . consul . domain . CatalogService } objects . */
public ConsulResponse < CatalogNode > getNode ( final String node , final String datacenter , final String tag ) { } }

implementation: return getNode ( node , datacenter , tag , RequestOptions . BLANK ) ;


signature:
public class CatalogEndpoint { /** * Retrieves a single node with { @ link io . advantageous . consul . domain . option . RequestOptions } .
 * GET / v1 / catalog / node / { node }
 * @ param node node
 * @ param requestOptions The Query Options to use .
 * @ return A list of matching { @ link io . advantageous . consul . domain . CatalogService } objects . */
public ConsulResponse < CatalogNode > getNode ( final String node , final RequestOptions requestOptions ) { } }

implementation: return getNode ( node , null , null , requestOptions ) ;


signature:
public class CatalogEndpoint { /** * Retrieves a single node for a given datacenter with { @ link io . advantageous . consul . domain . option . RequestOptions } .
 * GET / v1 / catalog / node / { node } ? dc = { datacenter }
 * @ param node node
 * @ param datacenter dc
 * @ param tag tag
 * @ param requestOptions The Query Options to use .
 * @ return A list of matching { @ link io . advantageous . consul . domain . CatalogService } objects . */
public ConsulResponse < CatalogNode > getNode ( final String node , final String datacenter , final String tag , final RequestOptions requestOptions ) { } }

implementation: final URI uri = createURI ( "/node/" + node ) ; final HttpRequestBuilder httpRequestBuilder = RequestUtils . getHttpRequestBuilder ( datacenter , tag , requestOptions , "" ) ; final HTTP . Response httpResponse = HTTP . getResponse ( uri + "?" + httpRequestBuilder . paramString ( ) ) ; if ( httpResponse . code ( ) != 200 ) { die ( "Unable to retrieve the node" , uri , httpResponse . code ( ) , httpResponse . body ( ) ) ; } return RequestUtils . consulResponse ( CatalogNode . class , httpResponse ) ;


signature:
public class ProxyBuilder { /** * Build the impl .
 * @ return returns an instance of the impl . */
public ProxyService build ( ) { } }

implementation: return new ProxyServiceImpl ( getReactor ( ) , getTimer ( ) , getHttpClientBuilder ( ) , getBeforeSend ( ) , getErrorHandler ( ) , getHttpClientRequestPredicate ( ) , getCheckClientDuration ( ) , pingBuilder == null ? Optional . < HttpRequestBuilder > empty ( ) : Optional . of ( pingBuilder ) , isTrackTimeOuts ( ) , getTimeOutInterval ( ) ) ;


signature:
public class ProxyBuilder { /** * Builds a proxy queue service to the impl .
 * @ return proxy queue service interface to impl . */
public ProxyService buildProxy ( ) { } }

implementation: return getServiceBuilder ( ) . setServiceObject ( build ( ) ) . buildAndStart ( ) . createProxyWithAutoFlush ( ProxyService . class , Duration . HUNDRED_MILLIS ) ;


signature:
public class WebSocketServiceServerHandler { /** * All WebSocket calls come through here .
 * @ param webSocketMessage websocket message */
public void handleWebSocketCall ( final WebSocketMessage webSocketMessage ) { } }

implementation: if ( debug ) logger . debug ( "WebSocket message: " + webSocketMessage ) ; WebSocketDelegate webSocketDelegate = webSocketDelegateMap . get ( webSocketMessage . getRemoteAddress ( ) ) ; if ( webSocketDelegate == null ) { webSocketDelegate = new WebSocketDelegate ( protocolBatchSize , webSocketMessage ) ; webSocketDelegateMap . put ( webSocketMessage . getRemoteAddress ( ) , webSocketDelegate ) ; } protocolParserThreadPool . execute ( ( ) -> { try { final List < MethodCall < Object > > methodCallListToBeParsedFromBody = createMethodCallListToBeParsedFromBody ( webSocketMessage . getRemoteAddress ( ) , webSocketMessage . getMessage ( ) , webSocketMessage ) ; if ( methodCallListToBeParsedFromBody . size ( ) > 0 ) { methodCallSendQueue . sendBatch ( methodCallListToBeParsedFromBody ) ; } } catch ( Exception ex ) { logger . error ( "" , ex ) ; } } ) ;


signature:
public class HttpProxy { /** * Start this . */
public void start ( ) { } }

implementation: server . setHttpRequestConsumer ( proxyService :: handleRequest ) ; server . setHttpRequestsIdleConsumer ( aVoid -> flushServiceProxy ( proxyService ) ) ; server . startServer ( ) ;


signature:
public class ChannelManager { /** * Add an event listener to the channel
 * There can only be one consumer and many listeners .
 * @ param eventListener eventListener */
public void add ( final EventListener < T > eventListener ) { } }

implementation: if ( eventListener . subscriber ( ) ) { if ( debug ) logger . debug ( "subscription to channel <> from <> " , name , eventListener ) ; listeners . add ( eventListener ) ; stats . recordLevel ( eventBusName + "::" + name , listeners . size ( ) ) ; } else { if ( debug ) logger . debug ( "consumer to channel <> from <> " , name , eventListener ) ; consumer = eventListener ; }


signature:
public class ChannelManager { /** * Remove an event listener from the channel .
 * There can only be one consumer and many listeners .
 * @ param eventListener eventListener */
public void remove ( EventListener < T > eventListener ) { } }

implementation: if ( eventListener . subscriber ( ) ) { logger . info ( "remove subscription to channel {} from {} " , name , eventListener ) ; listeners . remove ( eventListener ) ; stats . recordLevel ( eventBusName + "::" + name , listeners . size ( ) ) ; } else { if ( consumer == eventListener ) { logger . info ( "remove consumer to channel {} from {} " , name , eventListener ) ; consumer = new NoOpEventConsumer < > ( ) ; } }


signature:
public class ClusteredStatReplicator { /** * Event handler
 * @ param serviceName service name */
@ Override public void servicePoolChanged ( final String serviceName ) { } }

implementation: if ( this . serviceName . equals ( serviceName ) ) { logger . info ( "ClusteredStatReplicator::servicePoolChanged({})" , serviceName ) ; updateServicePool ( serviceName ) ; } else if ( debug ) { logger . debug ( "ClusteredStatReplicator::servicePoolChanged({})" , "got event for another service" , serviceName ) ; }


signature:
public class DnsUtil { /** * Create service discovery that can talk DNS .
 * @ return ServiceDiscovery */
public static ServiceDiscovery createDnsServiceDiscovery ( ) { } }

implementation: final ServiceDiscoveryBuilder serviceDiscoveryBuilder = ServiceDiscoveryBuilder . serviceDiscoveryBuilder ( ) ; final Vertx vertx = Vertx . vertx ( ) ; final DnsSupportBuilder dnsSupportBuilder = DnsSupportBuilder . dnsSupportBuilder ( vertx ) . setDnsClientSupplier ( new DnsClientFromResolveConfSupplier ( vertx ) ) ; final DnsServiceDiscoveryProviderBuilder dnsServiceDiscoveryProviderBuilder = DnsServiceDiscoveryProviderBuilder . dnsServiceDiscoveryProviderBuilder ( ) . setDnsSupport ( dnsSupportBuilder . build ( ) ) ; return serviceDiscoveryBuilder . setServiceDiscoveryProvider ( dnsServiceDiscoveryProviderBuilder . build ( ) ) . build ( ) ;


signature:
public class BoonJsonMapper { /** * Convert from json string using Class as a suggestion for how to do the parse .
 * @ param json json
 * @ param cls cls
 * @ param < T > Type
 * @ return Java object of Type T */
@ Override public < T > T fromJson ( String json , Class < T > cls ) { } }

implementation: return parser . get ( ) . parse ( cls , json ) ;


signature:
public class BoonJsonMapper { /** * Converts from a json string using componentClass as a guide to a List .
 * @ param json json
 * @ param componentClass componentClass
 * @ param < T > Type
 * @ return List of Java objects of Type T . */
@ Override public < T > List < T > fromJsonArray ( String json , Class < T > componentClass ) { } }

implementation: return parser . get ( ) . parseList ( componentClass , json ) ;


signature:
public class BoonJsonMapper { /** * Converts from Object into JSON string .
 * @ param object object to convert to JSON .
 * @ return json string */
@ Override public String toJson ( Object object ) { } }

implementation: return serializer . get ( ) . serialize ( object ) . toString ( ) ;


signature:
public class BoonJsonMapper { /** * Converts from a json string using componentClassKey and componentClassValue as a guide to a Map .
 * @ param json json string
 * @ param componentClassKey componentClassKey type of Key
 * @ param componentClassValue componentClassValue type of value
 * @ param < K > K type of map key
 * @ param < V > V type of map value
 * @ return Map */
@ Override public < K , V > Map < K , V > fromJsonMap ( String json , Class < K > componentClassKey , Class < V > componentClassValue ) { } }

implementation: Map map = ( Map ) parser . get ( ) . parse ( json ) ; final Mapper mapper = this . mapper . get ( ) ; return extractMap ( componentClassKey , componentClassValue , map , mapper ) ;


signature:
public class BoonJsonMapper { /** * Helper method .
 * Converts a value map into a regular map of Java basic types .
 * @ param valueMap valueMap
 * @ param < V > V
 * @ return regular map */
private < V > V convertToMap ( ValueMap valueMap ) { } }

implementation:
final Map < String , Object > map = new LinkedHashMap < > ( valueMap . size ( ) ) ; valueMap . entrySet ( ) . forEach ( new Consumer < Map . Entry < String , Object > > ( ) { @ Override public void accept ( Map . Entry < String , Object > entry ) { Object value = entry . getValue ( ) ; /* If the value is a value container then grab what is inside . */
if ( value instanceof ValueContainer ) { ValueContainer valueContainer = ( ( ValueContainer ) entry . getValue ( ) ) ; value = valueContainer . toValue ( ) ; } /* If value is a Value then pull the real value . */
if ( value instanceof Value ) { map . put ( entry . getKey ( ) , ( ( Value ) value ) . toValue ( ) ) ; } else if ( value instanceof ValueMap ) { /* If value is a value map then convert it into a regular map . */
map . put ( entry . getKey ( ) , convertToMap ( ( ( ValueMap ) value ) ) ) ; } else if ( value instanceof List ) { map . put ( entry . getKey ( ) , convertList ( value , mapper . get ( ) ) ) ; } else { map . put ( entry . getKey ( ) , value ) ; } } } ) ; return ( V ) map ;


signature:
public class BoonServiceMethodCallHandler { /** * False is unknown , true is no callbacks .
 * @ param name name of method
 * @ return false signifies maybe , true means never . */
public boolean couldHaveCallback ( final String name ) { } }

implementation: final Boolean has = hasHandlerMap . get ( name ) ; if ( has == null ) { return true ; } return has ;


signature:
public class CallbackBuilder { /** * Builder method to add a callback handler .
 * @ param returnType returnType
 * @ param callback callback
 * @ param < T > T
 * @ return this */
public < T > CallbackBuilder setCallback ( final Class < T > returnType , final Callback < T > callback ) { } }

implementation: return withCallback ( returnType , callback ) ;


signature:
public class CallbackBuilder { /** * Builder method to delegate timeout and error handling to other callback .
 * @ param callback callback
 * @ param < T > T
 * @ return this */
public < T > CallbackBuilder delegate ( final Callback < T > callback ) { } }

implementation: this . withErrorHandler ( callback :: onError ) ; this . withTimeoutHandler ( callback :: onTimeout ) ; return this ;


signature:
public class CallbackBuilder { /** * Builder method to wrap and delegate , timeout and error handling and callback itself .
 * @ param callback callback
 * @ param < T > T
 * @ return this */
public < T > CallbackBuilder wrap ( final Callback < T > callback ) { } }

implementation: this . withErrorHandler ( callback :: onError ) ; this . withTimeoutHandler ( callback :: onTimeout ) ; this . withCallback ( callback ) ; return this ;


signature:
public class CallbackBuilder { /** * Builder method to delegate timeout and error handling to other callback .
 * @ param callback callback
 * @ param logger logger
 * @ param operationName method name or thing you are doing .
 * @ param < T > T
 * @ return this , fluent */
public < T > CallbackBuilder delegateWithLogging ( final Callback < T > callback , final Logger logger , final String operationName ) { } }

implementation: this . withErrorHandler ( throwable -> { logger . error ( operationName + " ERROR " , throwable ) ; callback . onError ( throwable ) ; } ) ; this . withTimeoutHandler ( ( ) -> { logger . error ( operationName + " TIMED OUT " ) ; callback . onTimeout ( ) ; } ) ; return this ;


signature:
public class CallbackBuilder { /** * Builder method to set callback handler that takes a list
 * @ param componentClass componentClass
 * @ param callback callback
 * @ param < T > T
 * @ return this */
public < T > CallbackBuilder withListCallback ( final Class < T > componentClass , final Callback < List < T > > callback ) { } }

implementation: this . callback = callback ; return this ;


signature:
public class CallbackBuilder { /** * Builder method to set callback handler that takes a set
 * @ param componentClass componentClass
 * @ param callback callback
 * @ param < T > T
 * @ return this */
public < T > CallbackBuilder withSetCallback ( final Class < T > componentClass , final Callback < Set < T > > callback ) { } }


signature:
public class CallbackBuilder { /** * Builder method to set callback handler that takes a collection
 * @ param componentClass componentClass
 * @ param callback callback
 * @ param < T > T
 * @ return this */
public < T > CallbackBuilder withCollectionCallback ( final Class < T > componentClass , final Callback < Collection < T > > callback ) { } }


signature:
public class CallbackBuilder { /** * Builder method to set callback handler that takes a map
 * @ param keyClass keyClass
 * @ param valueClass valueClass
 * @ param callback callback
 * @ param < K > key type
 * @ param < V > value type
 * @ return this */
public < K , V > CallbackBuilder withMapCallback ( final Class < K > keyClass , final Class < V > valueClass , final Callback < Map < K , V > > callback ) { } }


signature:
public class CallbackBuilder { /** * Builder method to set callback handler that takes an optional string
 * @ param cls class
 * @ param callback callback
 * @ param < T > type of callback
 * @ return this */
public < T > CallbackBuilder withOptionalCallback ( final Class < T > cls , final Callback < Optional < T > > callback ) { } }


signature:
public class HttpResponseBuilder { /** * Add a header
 * @ param name name
 * @ param value value
 * @ return HttpResponseBuilder */
public HttpResponseBuilder addHeader ( final String name , final String value ) { } }

implementation: getHeaders ( ) . put ( name , value ) ; return this ;


signature:
public class AgentEndpoint { /** * Checks to see if a service is registered with the local agent . .
 * @ param serviceId service id
 * @ return < code > true < / code > if a particular service is registered with
 * the local Consul agent , otherwise < code > false < / code > . */
public boolean isServiceRegistered ( final String serviceId ) { } }

implementation: Map < String , Service > serviceIdToService = getServices ( ) ; return serviceIdToService . containsKey ( serviceId ) ;


signature:
public class AgentEndpoint { /** * Pings the Consul Agent . */
public void pingAgent ( ) { } }

implementation: HTTP . Response response = HTTP . getResponse ( createURI ( "/self" ) . toString ( ) ) ; if ( response . status ( ) != 200 ) { die ( "Error pinging Consul" , response . payloadAsString ( ) ) ; }


signature:
public class AgentEndpoint { /** * Registers the client as a service with Consul . Registration enables
 * the use of checks .
 * @ param port The public facing port of the service to register with Consul .
 * @ param ttl Time to live for the Consul dead man ' s switch .
 * @ param serviceName Service name to register .
 * @ param serviceId Service id to register .
 * @ param tags Tags to register with . */
public void registerService ( final int port , final long ttl , final String serviceName , final String serviceId , final String ... tags ) { } }

implementation: registerService ( null , port , ttl , serviceName , serviceId , tags ) ;


signature:
public class AgentEndpoint { /** * Registers the client as a service with Consul . Registration enables
 * the use of checks .
 * @ param host The public facing host of the service to register with Consul .
 * @ param port The public facing port of the service to register with Consul .
 * @ param ttl Time to live for the Consul dead man ' s switch .
 * @ param serviceName Service name to register .
 * @ param serviceId Service id to register .
 * @ param tags Tags to register with . */
public void registerService ( final String host , final int port , final long ttl , final String serviceName , final String serviceId , final String ... tags ) { } }

implementation: RegistrationCheck check = new RegistrationCheck ( ) ; check . setTtl ( "" + ttl + "s" ) ; registerServiceWithRegistrationCheck ( host , port , check , serviceName , serviceId , tags ) ;


signature:
public class AgentEndpoint { /** * Registers the client as a service with Consul .
 * Registration enables
 * the use of check with a script .
 * @ param port The public facing port of the service to register with Consul .
 * @ param script Health script for Consul to use .
 * @ param interval Health script run interval in seconds .
 * @ param serviceName Service name to register .
 * @ param serviceId Service id to register .
 * @ param tags Tags to register with . */
public void registerServiceWithScript ( final int port , final String script , final long interval , final String serviceName , final String serviceId , final String ... tags ) { } }

implementation: registerServiceWithScript ( null , port , script , interval , serviceName , serviceId , tags ) ;


signature:
public class AgentEndpoint { /** * Registers the client as a service with Consul .
 * Registration enables
 * the use of check with a script .
 * @ param host The public facing host of the service to register with Consul .
 * @ param port The public facing port of the service to register with Consul .
 * @ param script Health script for Consul to use .
 * @ param interval Health script run interval in seconds .
 * @ param serviceName Service name to register .
 * @ param serviceId Service id to register .
 * @ param tags Tags to register with . */
public void registerServiceWithScript ( final String host , final int port , final String script , final long interval , final String serviceName , final String serviceId , final String ... tags ) { } }

implementation: RegistrationCheck check = new RegistrationCheck ( ) ; check . setScript ( script ) ; check . setInterval ( "" + interval + "s" ) ; registerServiceWithRegistrationCheck ( host , port , check , serviceName , serviceId , tags ) ;


signature:
public class AgentEndpoint { /** * Registers the client as a service with Consul . Registration enables
 * the use of checks .
 * @ param port The public facing port of the service to register with Consul .
 * @ param check The health check to run periodically . Can be null .
 * @ param name Service name to register .
 * @ param id Service id to register .
 * @ param tags Tags to register with . */
public void registerServiceWithRegistrationCheck ( String host , int port , RegistrationCheck check , String name , String id , String ... tags ) { } }

implementation: Registration registration = new Registration ( ) ; registration . setHost ( host ) ; registration . setPort ( port ) ; registration . setCheck ( check ) ; registration . setName ( name ) ; registration . setId ( id ) ; registration . setTags ( tags ) ; register ( registration ) ;


signature:
public class AgentEndpoint { /** * Register a service with Consul .
 * @ param registration The registration payload . */
public void register ( final Registration registration ) { } }

implementation: final URI uri = createURI ( "/service/register" ) ; HTTP . Response response = HTTP . jsonRestCallViaPUT ( uri . toString ( ) , toJson ( registration ) ) ; if ( response . status ( ) != 200 ) { die ( "Error registering service with Consul" , uri , registration , response . payloadAsString ( ) ) ; }


signature:
public class AgentEndpoint { /** * Remove registration of a particular service .
 * @ param serviceId the service id that you want to remove . */
public void deregister ( final String serviceId ) { } }

implementation: final URI uri = createURI ( "/service/deregister/" + serviceId ) ; HTTP . Response response = HTTP . getResponse ( uri . toString ( ) ) ; if ( response . status ( ) != 200 ) { die ( "Error removing registration of service with Consul" , uri , serviceId , response . status ( ) , response . payloadAsString ( ) ) ; }


signature:
public class AgentEndpoint { /** * Registers a Health Check with the Agent .
 * @ param checkId The Check ID to use . Must be unique for the Agent .
 * @ param name The Check Name .
 * @ param script Health script for Consul to use .
 * @ param interval Health script run interval in seconds . */
public void registerCheck ( String checkId , String name , String script , long interval ) { } }

implementation: registerCheckWithNotes ( checkId , name , script , interval , null ) ;


signature:
public class AgentEndpoint { /** * Registers a Health Check with the Agent .
 * @ param checkId The Check ID to use . Must be unique for the Agent .
 * @ param name The Check Name .
 * @ param script Health script for Consul to use .
 * @ param interval Health script run interval in seconds .
 * @ param notes Human readable notes . Not used by Consul . */
public void registerCheckWithNotes ( String checkId , String name , String script , long interval , @ SuppressWarnings ( "SameParameterValue" ) String notes ) { } }

implementation: Check check = new Check ( ) ; check . setId ( checkId ) ; check . setName ( name ) ; check . setScript ( script ) ; check . setInterval ( String . format ( "%ss" , interval ) ) ; check . setNotes ( notes ) ; registerCheck ( check ) ;


signature:
public class AgentEndpoint { /** * Registers a Health Check with the Agent .
 * @ param checkId The Check ID to use . Must be unique for the Agent .
 * @ param name The Check Name .
 * @ param ttl Time to live for the Consul dead man ' s switch . */
public void registerCheck ( String checkId , String name , long ttl ) { } }

implementation: registerCheck ( checkId , name , ttl , null ) ;


signature:
public class AgentEndpoint { /** * Registers a Health Check with the Agent .
 * @ param checkId The Check ID to use . Must be unique for the Agent .
 * @ param name The Check Name .
 * @ param ttl Time to live for the Consul dead man ' s switch .
 * @ param notes Human readable notes . Not used by Consul . */
public void registerCheck ( String checkId , String name , long ttl , @ SuppressWarnings ( "SameParameterValue" ) String notes ) { } }

implementation: Check check = new Check ( ) ; check . setId ( checkId ) ; check . setName ( name ) ; check . setTtl ( String . format ( "%ss" , ttl ) ) ; check . setNotes ( notes ) ; registerCheck ( check ) ;


signature:
public class AgentEndpoint { /** * Registers a Health Check with the Agent .
 * @ param check The Check to register . */
public void registerCheck ( Check check ) { } }

implementation: final URI uri = createURI ( "/check/register" ) ; HTTP . Response response = HTTP . jsonRestCallViaPUT ( uri . toString ( ) , toJson ( check ) ) ; if ( response . status ( ) != 200 ) { die ( "Error removing registration of service with Consul" , uri , check , response . status ( ) , response . statusMessageAsString ( ) , response . payloadAsString ( ) ) ; }


signature:
public class AgentEndpoint { /** * De - registers a Health Check with the Agent
 * @ param checkId the id of the Check to deregister */
public void deregisterCheck ( String checkId ) { } }

implementation: final URI uri = createURI ( "/check/deregister/" + checkId ) ; HTTP . Response response = HTTP . getResponse ( uri . toString ( ) ) ; if ( response . status ( ) != 200 ) { die ( "Error removing registration of service with Consul" , uri , checkId , response . status ( ) , response . statusMessageAsString ( ) , response . payloadAsString ( ) ) ; }


signature:
public class AgentEndpoint { /** * Retrieves the Agent ' s configuration and member information .
 * GET / v1 / agent / self
 * @ return The Agent information . */
public AgentInfo getAgentInfo ( ) { } }

implementation: final URI uri = createURI ( "/self" ) ; HTTP . Response response = HTTP . getResponse ( uri . toString ( ) ) ; if ( response . status ( ) != 200 ) { die ( "Error getting info about this agent" , uri , response . status ( ) , response . statusMessageAsString ( ) , response . payloadAsString ( ) ) ; } return fromJson ( response . payloadAsString ( ) , AgentInfo . class ) ;


signature:
public class AgentEndpoint { /** * Retrieves all checks registered with the Agent .
 * GET / v1 / agent / checks
 * @ return Map of Check ID to Checks . */
public Map < String , HealthCheck > getChecks ( ) { } }

implementation: final URI uri = createURI ( "/checks" ) ; final HTTP . Response response = HTTP . getResponse ( uri . toString ( ) ) ; final JsonParserAndMapper jsonParserAndMapper = new JsonParserFactory ( ) . create ( ) ; if ( response . status ( ) == 200 ) { final Map < String , Object > map = jsonParserAndMapper . parseMap ( response . payloadAsString ( ) ) ; final Map < String , HealthCheck > returnMap = new HashMap < > ( map . size ( ) ) ; map . entrySet ( ) . forEach ( entry -> { @ SuppressWarnings ( "unchecked" ) HealthCheck healthCheck = fromMap ( ( Map < String , Object > ) entry . getValue ( ) , HealthCheck . class ) ; returnMap . put ( entry . getKey ( ) , healthCheck ) ; } ) ; return returnMap ; } die ( "Unable to get health checks" , uri , response . status ( ) , response . statusMessageAsString ( ) , response . payloadAsString ( ) ) ; return null ;


signature:
public class AgentEndpoint { /** * Retrieves all members that the Agent can see in the gossip pool .
 * GET / v1 / agent / members
 * @ return List of Members . */
public List < Member > getMembers ( ) { } }

implementation: final URI uri = createURI ( "/members" ) ; final HTTP . Response response = HTTP . getResponse ( uri . toString ( ) ) ; if ( response . code ( ) == 200 ) { return fromJsonArray ( response . body ( ) , Member . class ) ; } die ( "Unable to read members" , uri , response . code ( ) , response . body ( ) ) ; return Collections . emptyList ( ) ;


signature:
public class AgentEndpoint { /** * GET / v1 / agent / force - leave / { node }
 * Instructs the agent to force a node into the " left " state .
 * @ param node node */
public void forceLeave ( String node ) { } }

implementation: final URI uri = createURI ( "/force-leave/" + node ) ; final HTTP . Response httpResponse = HTTP . getResponse ( uri . toString ( ) ) ; if ( httpResponse . code ( ) != 200 ) { die ( "Unable to force leave" , uri , httpResponse . code ( ) , httpResponse . body ( ) ) ; }


signature:
public class AgentEndpoint { /** * Checks in with Consul .
 * @ param checkId The Check ID to check in .
 * @ param status The current state of the Check .
 * @ param note Any note to associate with the Check . */
public void check ( String checkId , Status status , String note ) { } }

implementation: final URI uri = createURI ( "/check/" + status . getUri ( ) + "/" + checkId ) ; final HTTP . Response httpResponse = Str . isEmpty ( note ) ? HTTP . getResponse ( uri . toString ( ) ) : HTTP . getResponse ( uri . toString ( ) + "?note=" + note ) ; if ( httpResponse . code ( ) != 200 ) { notRegistered ( "Unable to perform check" , uri , httpResponse . code ( ) , httpResponse . statusMessageAsString ( ) , httpResponse . body ( ) ) ; }


signature:
public class AgentEndpoint { /** * Prepends the default TTL prefix to the serviceId to produce a check id ,
 * then delegates to check ( String checkId , State state , String note )
 * This method only works with TTL checks that have not been given a custom
 * name .
 * @ param serviceId service id
 * @ param status state
 * @ param note note */
public void checkTtl ( String serviceId , Status status , String note ) { } }

implementation: check ( "service:" + serviceId , status , note ) ;


signature:
public class AgentEndpoint { /** * Sets a TTL check to " passing " state with a note
 * @ param checkId check id
 * @ param note note */
public void pass ( String checkId , @ SuppressWarnings ( "SameParameterValue" ) String note ) throws NotRegisteredException { } }

implementation: checkTtl ( checkId , Status . PASS , note ) ;


signature:
public class AgentEndpoint { /** * Sets a TTL check to " warning " state with a note .
 * @ param checkId check id
 * @ param note note */
public void warn ( String checkId , String note ) throws NotRegisteredException { } }

implementation: checkTtl ( checkId , Status . WARN , note ) ;


signature:
public class AgentEndpoint { /** * Sets a TTL check to " critical " state with a note .
 * @ param checkId check id
 * @ param note note */
public void fail ( String checkId , String note ) throws NotRegisteredException { } }

implementation: checkTtl ( checkId , Status . FAIL , note ) ;


signature:
public class AgentEndpoint { /** * Sets a TTL check to " critical " state with a note .
 * @ param checkId check id
 * @ param note note */
public void critical ( String checkId , String note ) throws NotRegisteredException { } }


signature:
public class BoonClient { /** * Stop client . Stops processing call backs . */
public void stop ( ) { } }

implementation: flush ( ) ; if ( httpServerProxy != null ) { try { httpServerProxy . stop ( ) ; } catch ( Exception ex ) { logger . warn ( "Problem closing httpServerProxy " , ex ) ; } }


signature:
public class BoonClient { /** * Handles WebSocket messages and parses them into responses .
 * This does not handle batching or rather un - batching which we need for performance
 * we do handle batching in the parser / encoder .
 * @ param webSocketText websocket text */
private void handleWebSocketReplyMessage ( final String webSocketText ) { } }

implementation:
final List < Message < Object > > messages = QBit . factory ( ) . createProtocolParser ( ) . parse ( "" , webSocketText ) ; // noinspection Convert2streamapi
for ( Message < Object > message : messages ) { if ( message instanceof Response ) { @ SuppressWarnings ( "unchecked" ) final Response < Object > response = ( ( Response ) message ) ; final String [ ] split = StringScanner . split ( response . returnAddress ( ) , ( char ) PROTOCOL_ARG_SEPARATOR ) ; final HandlerKey key = split . length == 2 ? new HandlerKey ( split [ 1 ] , response . id ( ) ) : new HandlerKey ( split [ 0 ] , response . id ( ) ) ; final Callback < Object > handler = handlers . get ( key ) ; if ( handler != null ) { handleAsyncCallback ( response , handler ) ; handlers . remove ( key ) ; } // else there was no handler , it was a one way method .
} }


signature:
public class BoonClient { /** * Handles an async callbackWithTimeout . */
private void handleAsyncCallback ( final Response < Object > response , final Callback < Object > handler ) { } }

implementation: if ( response . wasErrors ( ) ) { handler . onError ( new Exception ( response . body ( ) . toString ( ) ) ) ; } else { handler . accept ( response . body ( ) ) ; }


signature:
public class BoonClient { /** * Sends a message over websocket .
 * @ param message message to sendText over WebSocket
 * @ param serviceName message to sendText over WebSocket */
private void send ( final String serviceName , final String message , final Consumer < Exception > exceptionConsumer ) { } }

implementation: if ( webSocket == null ) { String webSocketURI ; if ( serviceName . startsWith ( uri ) ) { webSocketURI = serviceName ; } else { webSocketURI = Str . add ( uri , "/" , serviceName ) ; } this . webSocket = httpServerProxy . createWebSocket ( webSocketURI ) ; wireWebSocket ( serviceName , message ) ; } try { if ( webSocket . isClosed ( ) && connected ( ) ) { this . webSocket . openAndNotify ( netSocket -> { connected . set ( true ) ; webSocket . sendText ( message , exceptionConsumer ) ; } , exceptionConsumer ) ; } else { webSocket . sendText ( message ) ; } } catch ( Exception ex ) { this . connected . set ( false ) ; if ( debug ) throw ex ; }


signature:
public class BoonClient { /** * Creates a new client proxy given a client interface .
 * @ param serviceInterface client interface
 * @ param serviceName client name
 * @ param < T > class type of interface
 * @ return new client proxy . . calling methods on this proxy marshals method calls to httpServerProxy . */
public < T > T createProxy ( final Class < T > serviceInterface , final String serviceName ) { } }

implementation: return createProxy ( serviceInterface , serviceName , Str . join ( '-' , uri , serviceName , UUID . randomUUID ( ) . toString ( ) ) ) ;


signature:
public class ServiceEndpointServerImpl { /** * Creates the queue listener for method call responses from the client bundle .
 * @ return the response queue listener to handle the responses to method calls . */
private ReceiveQueueListener < Response < Object > > createResponseQueueListener ( ) { } }

implementation: return new ReceiveQueueListener < Response < Object > > ( ) { @ Override public void receive ( final Response < Object > response ) { if ( debug ) { logger . debug ( "createResponseQueueListener() Received a response: " + response ) ; } handleResponseFromServiceBundle ( response , response . request ( ) . originatingRequest ( ) ) ; } @ Override public void limit ( ) { httpRequestServerHandler . checkTimeoutsForRequests ( ) ; webSocketHandler . checkResponseBatchSend ( ) ; } @ Override public void empty ( ) { httpRequestServerHandler . checkTimeoutsForRequests ( ) ; webSocketHandler . checkResponseBatchSend ( ) ; } @ Override public void idle ( ) { httpRequestServerHandler . checkTimeoutsForRequests ( ) ; webSocketHandler . checkResponseBatchSend ( ) ; } } ;


signature:
public class JsonQueue { /** * Create a JsonQueue that can send a Map of values
 * @ param mapKeyClass mapKey class
 * @ param valueKeyClass valueKey class
 * @ param queue queue
 * @ param jsonMapper jsonMapper
 * @ param < K > K
 * @ param < V > V
 * @ return new JsonQueue that works with maps . */
public static < K , V > JsonQueue < Map < K , V > > createMapQueueWithMapper ( final Class < K > mapKeyClass , final Class < V > valueKeyClass , final Queue < String > queue , final JsonMapper jsonMapper ) { } }

implementation: return new JsonQueue < > ( queue , json -> jsonMapper . fromJsonMap ( json , mapKeyClass , valueKeyClass ) , jsonMapper :: toJson ) ;


signature:
public class JsonQueue { /** * Create a JsonQueue that can send a Map of values
 * @ param mapKeyClass mapKey class
 * @ param valueKeyClass valueKey class
 * @ param queue queue
 * @ param < K > K
 * @ param < V > V
 * @ return new JsonQueue that works with maps . */
public static < K , V > JsonQueue < Map < K , V > > createMapQueue ( final Class < K > mapKeyClass , final Class < V > valueKeyClass , final Queue < String > queue ) { } }

implementation: final JsonMapper jsonMapper = QBit . factory ( ) . createJsonMapper ( ) ; return createMapQueueWithMapper ( mapKeyClass , valueKeyClass , queue , jsonMapper ) ;


signature:
public class JsonQueue { /** * Create a wrapper ReceiveQueue that does decoding on the fly .
 * @ return wrapped ReceiveQueue */
@ Override public ReceiveQueue < T > receiveQueue ( ) { } }

implementation: final ReceiveQueue < String > receiveQueue = queue . receiveQueue ( ) ; return new ReceiveQueue < T > ( ) { @ Override public T pollWait ( ) { final String item = receiveQueue . pollWait ( ) ; return getParsedItem ( item ) ; } private T getParsedItem ( String item ) { if ( item != null ) { return fromJsonFunction . apply ( item ) ; } else { return null ; } } @ Override public T poll ( ) { final String item = receiveQueue . pollWait ( ) ; return getParsedItem ( item ) ; } @ Override public T take ( ) { final String item = receiveQueue . take ( ) ; return getParsedItem ( item ) ; } @ Override public Iterable < T > readBatch ( int max ) { final Iterable < String > iterable = receiveQueue . readBatch ( max ) ; return getParsedItems ( iterable ) ; } private Iterable < T > getParsedItems ( Iterable < String > iterable ) { int size = 16 ; if ( iterable instanceof List ) { size = ( ( List ) iterable ) . size ( ) ; } final List < T > items = new ArrayList < > ( size ) ; for ( String item : iterable ) { items . add ( getParsedItem ( item ) ) ; } return items ; } @ Override public Iterable < T > readBatch ( ) { final Iterable < String > iterable = receiveQueue . readBatch ( ) ; return getParsedItems ( iterable ) ; } @ Override public void stop ( ) { receiveQueue . stop ( ) ; } } ;


signature:
public class JsonQueue { /** * Create a wrapper SendQueue that encoders the objects to JSON
 * before putting them into the queue .
 * @ return returns wrapped SendQueue tht does JSON encoding . */
@ Override public SendQueue < T > sendQueue ( ) { } }

implementation: final SendQueue < String > sendQueue = queue . sendQueue ( ) ; return createJsonSendQueue ( sendQueue ) ;


signature:
public class JsonQueue { /** * Helper method to create SendQueue wrappers that do JSON encoding .
 * @ param sendQueue sendQueue
 * @ return sendQueue decorated with JSON encoding . */
private SendQueue < T > createJsonSendQueue ( final SendQueue < String > sendQueue ) { } }

implementation: return new SendQueue < T > ( ) { @ Override public boolean send ( T item ) { sendQueue . send ( toJsonFunction . apply ( item ) ) ; return false ; } @ Override public void sendAndFlush ( T item ) { sendQueue . sendAndFlush ( toJsonFunction . apply ( item ) ) ; } @ Override public void sendMany ( T ... items ) { for ( T item : items ) { sendQueue . send ( toJsonFunction . apply ( item ) ) ; } } @ Override public void sendBatch ( Collection < T > items ) { for ( T item : items ) { sendQueue . send ( toJsonFunction . apply ( item ) ) ; } } @ Override public void sendBatch ( Iterable < T > items ) { for ( T item : items ) { sendQueue . send ( toJsonFunction . apply ( item ) ) ; } } @ Override public boolean shouldBatch ( ) { return sendQueue . shouldBatch ( ) ; } @ Override public void flushSends ( ) { sendQueue . flushSends ( ) ; } @ Override public int size ( ) { return sendQueue . size ( ) ; } @ Override public String name ( ) { return sendQueue . name ( ) ; } @ Override public void stop ( ) { sendQueue . stop ( ) ; } } ;


signature:
public class JsonQueue { /** * Create a wrapper SendQueue that encoders the objects to JSON
 * before putting them into the queue .
 * @ param interval interval
 * @ param timeUnit timeUnit
 * @ return returns wrapped SendQueue tht does JSON encoding . */
@ Override public SendQueue < T > sendQueueWithAutoFlush ( int interval , TimeUnit timeUnit ) { } }

implementation: final SendQueue < String > sendQueue = queue . sendQueueWithAutoFlush ( interval , timeUnit ) ; return createJsonSendQueue ( sendQueue ) ;


signature:
public class JsonQueue { /** * Start a listener .
 * @ param listener listener */
@ Override public void startListener ( final ReceiveQueueListener < T > listener ) { } }

implementation: queue . startListener ( item -> listener . receive ( fromJsonFunction . apply ( item ) ) ) ;


signature:
public class ServiceBuilder { /** * Builds a service .
 * @ return new service queue */
public ServiceQueue build ( ) { } }

implementation: if ( debug ) logger . debug ( "Building a service" ) ; ServiceQueueSizer serviceQueueSizer = null ; if ( statsConfig != null ) { serviceQueueSizer = new ServiceQueueSizer ( ) ; this . addQueueCallbackHandler ( new ServiceStatsListener ( statsConfig . serviceName , statsConfig . statsCollector , getTimer ( ) , statsConfig . flushTimeSeconds , TimeUnit . SECONDS , statsConfig . sampleEvery , serviceQueueSizer ) ) ; } ServiceQueue serviceQueue = new ServiceQueueImpl ( this . getRootAddress ( ) , this . getServiceAddress ( ) , this . getServiceObject ( ) , this . getRequestQueueBuilder ( ) , this . getResponseQueueBuilder ( ) , this . getServiceMethodHandler ( ) , this . getResponseQueue ( ) , this . isAsyncResponse ( ) , this . isHandleCallbacks ( ) , this . getSystemManager ( ) , this . getBeforeMethodCall ( ) , this . getBeforeMethodCallAfterTransform ( ) , this . getAfterMethodCall ( ) , this . getAfterMethodCallAfterTransform ( ) , buildQueueCallBackHandler ( ) , getCallbackManager ( ) , getBeforeMethodSent ( ) , getEventManager ( ) , isJoinEventManager ( ) ) ; if ( serviceQueueSizer != null ) { serviceQueueSizer . setServiceQueue ( serviceQueue ) ; } if ( qBitSystemManager != null ) { qBitSystemManager . registerService ( serviceQueue ) ; } return serviceQueue ;


signature:
public class HealthServiceImpl { /** * Register method to register services / internal nodes .
 * @ param name name
 * @ param ttl ttl
 * @ param timeUnit timeUnit */
@ Override public void register ( final String name , final long ttl , final TimeUnit timeUnit ) { } }

implementation: logger . info ( "HealthService::register() {} {} {}" , name , ttl , timeUnit ) ; final NodeHealthStat nodeHealthStat = new NodeHealthStat ( name , timeUnit . toMillis ( ttl ) ) ; serviceHealthStatMap . put ( name , nodeHealthStat ) ; super . incrementCount ( "nodes" ) ; super . recordLevel ( "nodes" , serviceHealthStatMap . size ( ) ) ;


signature:
public class HealthServiceImpl { /** * Register method to register services / internal nodes .
 * @ param name name */
@ Override public void registerNoTtl ( final String name ) { } }

implementation: logger . info ( "HealthService::register() {} " , name ) ; final NodeHealthStat nodeHealthStat = new NodeHealthStat ( name ) ; nodeHealthStat . setStatus ( HealthStatus . PASS ) ; serviceHealthStatMap . put ( name , nodeHealthStat ) ; super . incrementCount ( "nodes" ) ; super . recordLevel ( "nodes" , serviceHealthStatMap . size ( ) ) ;


signature:
public class HealthServiceImpl { /** * Check in the service .
 * @ param name name */
@ Override public void checkInOk ( final String name ) { } }

implementation: if ( debug ) logger . debug ( "HealthService::checkInOk() {} " , name ) ; final NodeHealthStat nodeHealthStat = getServiceHealthStat ( name ) ; nodeHealthStat . setLastCheckIn ( super . time ) ; nodeHealthStat . setReason ( null ) ; nodeHealthStat . setStatus ( HealthStatus . PASS ) ; super . incrementCount ( "checkin" ) ; onCheckIn . ifPresent ( checkIn -> checkIn . accept ( BeanUtils . copy ( nodeHealthStat ) ) ) ;


signature:
public class HealthServiceImpl { /** * Check in the service with a specific status .
 * @ param name name
 * @ param status status */
@ Override public void checkIn ( final String name , final HealthStatus status ) { } }

implementation: super . incrementCount ( "checkin" ) ; final NodeHealthStat nodeHealthStat = getServiceHealthStat ( name ) ; nodeHealthStat . setStatus ( status ) ; nodeHealthStat . setReason ( null ) ; nodeHealthStat . setLastCheckIn ( super . time ) ; reportStatus ( name , nodeHealthStat ) ;


signature:
public class HealthServiceImpl { /** * Check in the service with a specific status .
 * @ param name name
 * @ param reason reason */
@ Override public void failWithReason ( final String name , final HealthFailReason reason ) { } }

implementation: logger . error ( "HealthService::fail() {}" , name ) ; super . incrementCount ( "fail" ) ; final NodeHealthStat nodeHealthStat = getServiceHealthStat ( name ) ; nodeHealthStat . setStatus ( HealthStatus . FAIL ) ; nodeHealthStat . setReason ( reason ) ; nodeHealthStat . setLastCheckIn ( super . time ) ; onFail . ifPresent ( checkIn -> checkIn . accept ( BeanUtils . copy ( nodeHealthStat ) ) ) ;


signature:
public class HealthServiceImpl { /** * Fail the node for the service with a specific status .
 * @ param name name
 * @ param error error */
@ Override public void failWithError ( final String name , final Throwable error ) { } }

implementation: logger . error ( "HealthService::fail() {}" , name ) ; super . incrementCount ( "fail" ) ; final NodeHealthStat nodeHealthStat = getServiceHealthStat ( name ) ; nodeHealthStat . setStatus ( HealthStatus . FAIL ) ; nodeHealthStat . setReason ( HealthFailReason . ERROR ) ; nodeHealthStat . setLastCheckIn ( super . time ) ; nodeHealthStat . setError ( error ) ; onFail . ifPresent ( checkIn -> checkIn . accept ( BeanUtils . copy ( nodeHealthStat ) ) ) ;


signature:
public class ManagedServiceBuilder { /** * Enable the logging diagnostic context
 * @ param requestHeaders request headers to track in the MDC .
 * @ return this */
public ManagedServiceBuilder enableLoggingMappedDiagnosticContext ( final Set < String > requestHeaders ) { } }

implementation: this . enableRequestChain = true ; this . enableLoggingMappedDiagnosticContext = true ; this . requestHeadersToTrackForMappedDiagnosticContext = Collections . unmodifiableSet ( requestHeaders ) ; return this ;


signature:
public class ManagedServiceBuilder { /** * Get the public port for service meta generation ( Swagger )
 * @ return public port */
public int getPublicPort ( ) { } }

implementation: if ( publicPort == - 1 ) { String sport = System . getenv ( "PUBLIC_WEB_PORT" ) ; if ( ! Str . isEmpty ( sport ) ) { publicPort = Integer . parseInt ( sport ) ; } } if ( publicPort == - 1 ) { publicPort = getPort ( ) ; } return publicPort ;


signature:
public class ManagedServiceBuilder { /** * Enable consul discovery
 * @ param dataCenter name of datacenter we are connecting to .
 * @ return fluent , this */
public ManagedServiceBuilder enableConsulServiceDiscovery ( final String dataCenter ) { } }

implementation: final ConsulServiceDiscoveryBuilder consulServiceDiscoveryBuilder = consulServiceDiscoveryBuilder ( ) ; consulServiceDiscoveryBuilder . setDatacenter ( dataCenter ) ; serviceDiscoverySupplier = consulServiceDiscoveryBuilder :: build ; return this ;


signature:
public class ManagedServiceBuilder { /** * Used to get the StatsD replicator builder .
 * You can use this to configure StatsD .
 * You can also use environment variables { @ code STATSD _ PORT } and { @ code STATSD _ HOST } .
 * @ return stats replicator builder . */
public StatsDReplicatorBuilder getStatsDReplicatorBuilder ( ) { } }

implementation: if ( statsDReplicatorBuilder == null ) { statsDReplicatorBuilder = StatsDReplicatorBuilder . statsDReplicatorBuilder ( ) ; final String statsDPort = System . getenv ( "STATSD_PORT" ) ; if ( statsDPort != null && ! statsDPort . isEmpty ( ) ) { statsDReplicatorBuilder . setPort ( Integer . parseInt ( statsDPort ) ) ; } final String statsDHost = System . getenv ( "STATSD_HOST" ) ; if ( statsDHost != null && ! statsDHost . isEmpty ( ) ) { statsDReplicatorBuilder . setHost ( statsDHost ) ; } } return statsDReplicatorBuilder ;


signature:
public class ManagedServiceBuilder { /** * Finds the admin port .
 * Searches under environment variables ,
 * { @ code QBIT _ ADMIN _ PORT } , { @ code ADMIN _ PORT } , { @ code PORT1 } .
 * @ return admin port */
public String findAdminPort ( ) { } }

implementation:
String qbitAdminPort = System . getenv ( "QBIT_ADMIN_PORT" ) ; if ( Str . isEmpty ( qbitAdminPort ) ) { qbitAdminPort = System . getenv ( "ADMIN_PORT" ) ; } /* Uses PORT1 for admin port for Mesosphere / Heroku like environments . */
if ( Str . isEmpty ( qbitAdminPort ) ) { qbitAdminPort = System . getenv ( "PORT1" ) ; } return qbitAdminPort ;


signature:
public class ManagedServiceBuilder { /** * Get the Admin builder .
 * @ return admin builder . */
public AdminBuilder getAdminBuilder ( ) { } }

implementation: if ( adminBuilder == null ) { adminBuilder = AdminBuilder . adminBuilder ( ) ; final String qbitAdminPort = findAdminPort ( ) ; if ( qbitAdminPort != null && ! qbitAdminPort . isEmpty ( ) ) { adminBuilder . setPort ( Integer . parseInt ( qbitAdminPort ) ) ; } adminBuilder . setContextBuilder ( this . getContextMetaBuilder ( ) ) ; adminBuilder . setHealthService ( getHealthService ( ) ) ; adminBuilder . registerJavaVMStatsJob ( getStatServiceBuilder ( ) . buildStatsCollector ( ) ) ; } return adminBuilder ;


signature:
public class ManagedServiceBuilder { /** * Get context meta builder .
 * @ return context meta builder */
public ContextMetaBuilder getContextMetaBuilder ( ) { } }

implementation: if ( contextMetaBuilder == null ) { contextMetaBuilder = ContextMetaBuilder . contextMetaBuilder ( ) ; contextMetaBuilder . setHostAddress ( this . getPublicHost ( ) + ":" + this . getPublicPort ( ) ) . setRootURI ( this . getRootURI ( ) ) ; } return contextMetaBuilder ;


signature:
public class ManagedServiceBuilder { /** * Add an endpoint with a managment bundle
 * @ param endpointService endpoint service
 * @ param serviceManagementBundle management bundle
 * @ return this , fluent */
public ManagedServiceBuilder addEndpointServiceWithServiceManagmentBundle ( final Object endpointService , final ServiceManagementBundle serviceManagementBundle ) { } }

implementation: addEndpointServiceWithAliasAndQueueHandlerCallbacks ( null , endpointService , new QueueCallBackHandler ( ) { @ Override public void queueProcess ( ) { serviceManagementBundle . process ( ) ; } } ) ; return this ;


signature:
public class ManagedServiceBuilder { /** * Add an endpoint with a managment bundle and an alias
 * @ param alias alias
 * @ param endpointService endpoint service
 * @ param serviceManagementBundle management bundle
 * @ return this , fluent */
public ManagedServiceBuilder addEndpointServiceWithAliasAndServiceManagmentBundle ( final String alias , final Object endpointService , final ServiceManagementBundle serviceManagementBundle ) { } }

implementation: addEndpointServiceWithAliasAndQueueHandlerCallbacks ( alias , endpointService , new QueueCallBackHandler ( ) { @ Override public void queueProcess ( ) { serviceManagementBundle . process ( ) ; } } ) ; return this ;


signature:
public class ManagedServiceBuilder { /** * Add an endpoint service
 * @ param endpointService endpoint service
 * @ return this , fluent */
public ManagedServiceBuilder addEndpointService ( final Object endpointService ) { } }

implementation: getContextMetaBuilder ( ) . addService ( endpointService . getClass ( ) ) ; getEndpointServices ( ) . add ( endpointService ) ; return this ;


signature:
public class ManagedServiceBuilder { /** * Add an end point service with queue callback handlers
 * @ param endpointService endpoint Service
 * @ param queueCallBackHandlers queue callback handlers
 * @ return this , fluent */
public ManagedServiceBuilder addEndpointServiceWithQueueHandlerCallbacks ( final Object endpointService , final QueueCallBackHandler ... queueCallBackHandlers ) { } }

implementation: getContextMetaBuilder ( ) . addService ( endpointService . getClass ( ) ) ; getManagedServiceDefinitionList ( ) . add ( new ManagedServiceDefinition ( null , endpointService , queueCallBackHandlers ) ) ; return this ;


signature:
public class ManagedServiceBuilder { /** * Add an end point service with queue callback handlers
 * @ param alias alias
 * @ param endpointService endpoint Service
 * @ param queueCallBackHandlers queue callback handlers
 * @ return this , fluent */
public ManagedServiceBuilder addEndpointServiceWithAliasAndQueueHandlerCallbacks ( final String alias , final Object endpointService , final QueueCallBackHandler ... queueCallBackHandlers ) { } }

implementation: getContextMetaBuilder ( ) . addService ( endpointService . getClass ( ) ) ; getManagedServiceDefinitionList ( ) . add ( new ManagedServiceDefinition ( alias , endpointService , queueCallBackHandlers ) ) ; return this ;


signature:
public class ManagedServiceBuilder { /** * Add endpoint service with alias
 * @ param alias alias
 * @ param endpointService endpoint service
 * @ return this , fluent */
public ManagedServiceBuilder addEndpointService ( final String alias , final Object endpointService ) { } }

implementation: getContextMetaBuilder ( ) . addService ( alias , endpointService . getClass ( ) ) ; getEndpointServiceMapWithAlias ( ) . put ( alias , endpointService ) ; return this ;


signature:
public class ManagedServiceBuilder { /** * Enable statsD using the URI specified .
 * @ param uri uri for stats D
 * @ return this , fluent */
public ManagedServiceBuilder enableStatsD ( final URI uri ) { } }

implementation: this . enableStatsD = true ; this . getStatsDReplicatorBuilder ( ) . setHost ( uri . getHost ( ) ) . setPort ( uri . getPort ( ) ) ; return this ;


signature:
public class ManagedServiceBuilder { /** * Enable statsD using the URI specified .
 * @ param host host for statsD
 * @ param port port for statsD
 * @ return this , fluent */
public ManagedServiceBuilder enableStatsD ( final String host , final int port ) { } }

implementation: this . enableStatsD = true ; this . getStatsDReplicatorBuilder ( ) . setHost ( host ) . setPort ( port ) ; return this ;


signature:
public class ManagedServiceBuilder { /** * Get the ServiceEndpointServer constructed with all of the service endpionts that
 * you registered
 * @ return new ServiceEndpointServer . */
public ServiceEndpointServer getServiceEndpointServer ( ) { } }

implementation: final ServiceEndpointServer serviceEndpointServer = getEndpointServerBuilder ( ) . build ( ) ; if ( managedServiceDefinitionList != null ) { managedServiceDefinitionList . forEach ( serviceDef -> { if ( serviceDef . getAlias ( ) == null ) { serviceEndpointServer . addServiceWithQueueCallBackHandlers ( serviceDef . getServiceObject ( ) , serviceDef . getQueueCallBackHandlers ( ) ) ; } else { serviceEndpointServer . addServiceObjectWithQueueCallBackHandlers ( serviceDef . getAlias ( ) , serviceDef . getServiceObject ( ) , serviceDef . getQueueCallBackHandlers ( ) ) ; } } ) ; } return serviceEndpointServer ;


signature:
public class ManagedServiceBuilder { /** * Configure a list of common interceptors .
 * @ return interceptors . */
private Interceptors configureInterceptors ( ) { } }

implementation: Interceptors interceptors = new Interceptors ( ) ; SetupMdcForHttpRequestInterceptor setupMdcForHttpRequestInterceptor ; if ( enableLoggingMappedDiagnosticContext ) { enableRequestChain = true ; if ( requestHeadersToTrackForMappedDiagnosticContext != null && requestHeadersToTrackForMappedDiagnosticContext . size ( ) > 0 ) { setupMdcForHttpRequestInterceptor = new SetupMdcForHttpRequestInterceptor ( requestHeadersToTrackForMappedDiagnosticContext ) ; } else { setupMdcForHttpRequestInterceptor = new SetupMdcForHttpRequestInterceptor ( Collections . emptySet ( ) ) ; } interceptors . before . add ( setupMdcForHttpRequestInterceptor ) ; interceptors . after . add ( setupMdcForHttpRequestInterceptor ) ; } if ( enableRequestChain ) { final CaptureRequestInterceptor captureRequestInterceptor = new CaptureRequestInterceptor ( ) ; interceptors . before . add ( captureRequestInterceptor ) ; interceptors . after . add ( captureRequestInterceptor ) ; interceptors . beforeSent . add ( new ForwardCallMethodInterceptor ( new RequestContext ( ) ) ) ; } return interceptors ;


signature:
public class SessionEndpoint { /** * The create endpoint is used to initialize a new session .
 * Sessions must be associated with a node and may be associated with any number of checks .
 * The create endpoint expects a JSON request body to be PUT . The request body must look like :
 * < pre >
 * < code >
 * " LockDelay " : " 15s " ,
 * " Name " : " my - service - lock " ,
 * " Node " : " foobar " ,
 * " Checks " : [ " a " , " b " , " c " ] ,
 * " Behavior " : " release " ,
 * " TTL " : " 0s "
 * < / code >
 * < / pre >
 * None of the fields are mandatory , and in fact no body needs to be PUT if the defaults are to be used .
 * By default , the agent ' s local datacenter is used ; another datacenter can be specified using
 * the " ? dc = " query parameter . However , it is not recommended to use cross - datacenter sessions .
 * / v1 / session / create : Creates a new session
 * @ param session session to create
 * @ param datacenter datacenter
 * @ return a session id */
public String create ( Session session , final String datacenter ) { } }

implementation: final URI uri = createURI ( "/create" ) ; final HttpRequestBuilder httpRequestBuilder = RequestUtils . getHttpRequestBuilder ( datacenter , null , null , "" ) ; HTTP . Response httpResponse = HTTP . jsonRestCallViaPUT ( uri . toString ( ) + "?" + httpRequestBuilder . paramString ( ) , toJson ( session ) ) ; if ( httpResponse == null || httpResponse . code ( ) != 200 ) { die ( "Unable to create the session" , uri , httpResponse ) ; } final String id = fromJson ( httpResponse . body ( ) , SessionId . class ) . getId ( ) ; session . setId ( id ) ; return id ;


signature:
public class SessionEndpoint { /** * Destroy the session .
 * @ param sessionId id of session
 * @ param session session
 * @ param datacenter datacenter
 * @ return true if success */
public boolean destroy ( final String sessionId , final Session session , final String datacenter ) { } }

implementation: final URI uri = createURI ( "/destroy/" + sessionId ) ; final HttpRequestBuilder httpRequestBuilder = RequestUtils . getHttpRequestBuilder ( datacenter , null , null , "" ) ; HTTP . Response httpResponse = HTTP . jsonRestCallViaPUT ( uri . toString ( ) + "?" + httpRequestBuilder . paramString ( ) , toJson ( session ) ) ; if ( httpResponse == null || httpResponse . code ( ) != 200 ) { die ( "Unable destroy the session" , sessionId , uri , httpResponse ) ; } return httpResponse . code ( ) == 200 ;


signature:
public class SessionEndpoint { /** * / v1 / session / renew : Renews a TTL - based session
 * @ param sessionId session id
 * @ param datacenter datacenter
 * @ return session */
public Session renew ( final String sessionId , final String datacenter ) { } }

implementation: final URI uri = createURI ( "/renew/" + sessionId ) ; final HttpRequestBuilder httpRequestBuilder = RequestUtils . getHttpRequestBuilder ( datacenter , null , null , "" ) ; HTTP . Response httpResponse = HTTP . jsonRestCallViaPUT ( uri . toString ( ) + "?" + httpRequestBuilder . paramString ( ) , "" ) ; if ( httpResponse == null || httpResponse . code ( ) != 200 ) { die ( "Unable to renew the session" , uri , httpResponse ) ; } return fromJsonArray ( httpResponse . body ( ) , Session . class ) . get ( 0 ) ;


signature:
public class SessionEndpoint { /** * This endpoint is hit with a GET and returns the requested session information
 * within a given datacenter . By default , the datacenter of the agent is queried ; however ,
 * the dc can be provided using the " ? dc = " query parameter .
 * The session being queried must be provided on the path .
 * It returns a JSON body like this :
 * < pre >
 * < code >
 * " LockDelay " : 1.5e + 10,
 * " Checks " : [
 * " serfHealth "
 * " Node " : " foobar " ,
 * " ID " : " adf4238a - 882b - 9ddc - 4a9d - 5b6758e4159e " ,
 * " CreateIndex " : 1086449
 * < / code >
 * < / pre >
 * If the session is not found , null is returned instead of a JSON list .
 * This endpoint supports blocking queries and all consistency modes .
 * / v1 / session / info / session : Queries a given session
 * @ param sessionId id of a session
 * @ param requestOptions request options
 * @ return Session for this session id . */
public Optional < Session > info ( final String sessionId , RequestOptions requestOptions ) { } }

implementation: return info ( sessionId , null , requestOptions ) ;


signature:
public class SessionEndpoint { /** * / v1 / session / info / session :
 * Queries a given session
 * @ param sessionId id of a session
 * @ param requestOptions request options
 * @ param datacenter datacenter
 * @ return Session for this session id . */
public Optional < Session > info ( final String sessionId , final String datacenter , final RequestOptions requestOptions ) { } }

implementation: final URI uri = createURI ( "/info/" + sessionId ) ; final HttpRequestBuilder httpRequestBuilder = RequestUtils . getHttpRequestBuilder ( datacenter , null , null , "" ) ; HTTP . Response httpResponse = HTTP . getResponse ( uri . toString ( ) + "?" + httpRequestBuilder . paramString ( ) ) ; if ( httpResponse == null || httpResponse . code ( ) != 200 ) { die ( "Unable to get the sessions" , uri , httpResponse ) ; } final List < Session > sessions = fromJsonArray ( httpResponse . body ( ) , Session . class ) ; if ( sessions == null || sessions . size ( ) == 0 ) { return Optional . empty ( ) ; } return Optional . of ( sessions . get ( 0 ) ) ;


signature:
public class SessionEndpoint { /** * This endpoint is hit with a GET and returns the active sessions for a given node and datacenter .
 * By default , the datacenter of the agent is queried ; however ,
 * the dc can be provided using the " ? dc = " query parameter .
 * The node being queried must be provided on the path .
 * / v1 / session / node / node :
 * Lists sessions belonging to a node
 * @ param node node
 * @ param requestOptions request options for consistency and long poll
 * @ return list of sessions for this node */
public List < Session > getSessionsForNode ( final String node , final RequestOptions requestOptions ) { } }

implementation: return getSessionsForNode ( node , null , requestOptions ) ;


signature:
public class DnsServiceDiscoveryProvider { /** * Load the services .
 * @ param serviceName serviceName
 * @ return list of EndpointDefinition */
@ Override public List < EndpointDefinition > loadServices ( final String serviceName ) { } }

implementation: if ( debug ) logger . debug ( "Loading Service {}" , serviceName ) ; final CountDownLatch countDownLatch = new CountDownLatch ( 1 ) ; final AtomicReference < List < EndpointDefinition > > endPointsRef = new AtomicReference < > ( ) ; final AtomicReference < Throwable > exceptionAtomicReference = new AtomicReference < > ( ) ; dnsSupport . loadServiceEndpointsByServiceName ( CallbackBuilder . newCallbackBuilder ( ) . withListCallback ( EndpointDefinition . class , endpointDefinitions -> { endPointsRef . set ( endpointDefinitions ) ; countDownLatch . countDown ( ) ; } ) . withErrorHandler ( exceptionAtomicReference :: set ) . build ( ) , serviceName ) ; try { if ( debug ) logger . debug ( "Waiting for load services {} {}" , timeout , timeUnit ) ; countDownLatch . await ( timeout , timeUnit ) ; } catch ( InterruptedException e ) { throw new IllegalStateException ( "DNS Timeout" , e ) ; } if ( exceptionAtomicReference . get ( ) != null ) { logger . error ( "DnsServiceDiscoveryProvider.loadServices EXCEPTION" , exceptionAtomicReference . get ( ) ) ; throw new IllegalStateException ( "Unable to read from DNS" , exceptionAtomicReference . get ( ) ) ; } else { if ( debug ) logger . debug ( "DnsServiceDiscoveryProvider.loadServices SUCCESS" ) ; return endPointsRef . get ( ) ; }


signature:
public class KeyValueStoreEndpoint { /** * Retrieves a { @ link io . advantageous . consul . domain . KeyValue } for a specific key
 * from the key / value store .
 * GET / v1 / keyValueStore / { key }
 * @ param key The key to retrieve .
 * @ param requestOptions The query options .
 * @ return An { @ link Optional } containing the value or { @ link java . util . Optional # empty ( ) } */
public Optional < KeyValue > getValue ( final String key , RequestOptions requestOptions ) { } }

implementation: final URI uri = createURI ( "/" + key ) ; final HttpRequestBuilder httpRequestBuilder = RequestUtils . getHttpRequestBuilder ( null , null , requestOptions , "" ) ; final HTTP . Response httpResponse = HTTP . getResponse ( uri . toString ( ) + "?" + httpRequestBuilder . paramString ( ) ) ; if ( httpResponse . code ( ) == 404 ) { return Optional . empty ( ) ; } if ( httpResponse . code ( ) != 200 ) { die ( "Unable to retrieve the key" , key , uri , httpResponse . code ( ) , httpResponse . body ( ) ) ; } return getKeyValueOptional ( httpResponse ) ;


signature:
public class KeyValueStoreEndpoint { /** * Retrieves a string value for a specific key from the key / value store .
 * GET / v1 / keyValueStore / { key }
 * @ param key The key to retrieve .
 * @ return An { @ link Optional } containing the value as a string or
 * { @ link java . util . Optional # empty ( ) } */
public Optional < String > getValueAsString ( String key ) { } }

implementation: Optional < KeyValue > value = getValue ( key ) ; return value . isPresent ( ) ? Optional . of ( RequestUtils . decodeBase64 ( value . get ( ) . getValue ( ) ) ) : Optional . < String > empty ( ) ;


signature:
public class KeyValueStoreEndpoint { /** * Retrieves a list of string values for a specific key from the key / value
 * store .
 * GET / v1 / keyValueStore / { key } ? recurse
 * @ param key The key to retrieve .
 * @ return A list of zero to many string values . */
public List < String > getValuesAsString ( String key ) { } }

implementation: @ SuppressWarnings ( "UnnecessaryLocalVariable" ) List < String > result = getValues ( key ) . stream ( ) . map ( keyValue -> RequestUtils . decodeBase64 ( keyValue . getValue ( ) ) ) . collect ( Collectors . toList ( ) ) ; return result ;


signature:
public class KeyValueStoreEndpoint { /** * Puts a value into the key / value store .
 * @ param key The key to use as index .
 * @ param value The value to index .
 * @ return < code > true < / code > if the value was successfully indexed . */
public boolean putValue ( String key , String value ) { } }

implementation: return putValue ( key , value , 0L , KeyValuePutOptions . BLANK ) ;


signature:
public class KeyValueStoreEndpoint { /** * Puts a value into the key / value store .
 * @ param key The key to use as index .
 * @ param value The value to index .
 * @ param putOptions PUT options ( e . g . wait , acquire ) .
 * @ param flags flags
 * @ return < code > true < / code > if the value was successfully indexed . */
public boolean putValue ( final String key , final String value , final long flags , final KeyValuePutOptions putOptions ) { } }

implementation:
Integer cas = putOptions . getCas ( ) ; String release = putOptions . getRelease ( ) ; String acquire = putOptions . getAcquire ( ) ; final URI uri = createURI ( "/" + key ) ; final HttpRequestBuilder httpRequestBuilder = RequestUtils . getHttpRequestBuilder ( null , null , RequestOptions . BLANK , "" ) ; // httpRequestBuilder . addParam ( " recurse " , " true " ) ;
if ( cas != null ) { httpRequestBuilder . addParam ( "cas" , cas . toString ( ) ) ; } if ( ! Str . isEmpty ( release ) ) { httpRequestBuilder . addParam ( "release" , release ) ; } if ( ! Str . isEmpty ( acquire ) ) { httpRequestBuilder . addParam ( "acquire" , acquire ) ; } if ( flags != 0 ) { httpRequestBuilder . addParam ( "flags" , String . valueOf ( flags ) ) ; } httpRequestBuilder . setBody ( value ) ; httpRequestBuilder . setMethodPut ( ) ; final HTTP . Response httpResponse = HTTP . jsonRestCallViaPUT ( uri . toString ( ) + "?" + httpRequestBuilder . paramString ( ) , value ) ; if ( httpResponse . code ( ) == 200 ) { return Boolean . parseBoolean ( httpResponse . body ( ) ) ; } else { die ( "Unable to put value" , uri , putOptions , httpResponse . code ( ) , httpResponse . body ( ) ) ; return false ; }


signature:
public class KeyValueStoreEndpoint { /** * Retrieves a list of matching keys for the given key .
 * GET / v1 / keyValueStore / { key } ? keys
 * @ param key The key to retrieve .
 * @ return A list of zero to many keys . */
public List < String > getKeys ( String key ) { } }

implementation: final URI uri = createURI ( "/" + key ) ; final HttpRequestBuilder httpRequestBuilder = RequestUtils . getHttpRequestBuilder ( null , null , RequestOptions . BLANK , "" ) ; httpRequestBuilder . addParam ( "keys" , "true" ) ; final HTTP . Response httpResponse = HTTP . getResponse ( uri . toString ( ) + "?" + httpRequestBuilder . paramString ( ) ) ; if ( httpResponse . code ( ) == 200 ) { return fromJsonArray ( httpResponse . body ( ) , String . class ) ; } else { die ( "Unable to get nested keys" , uri , key , httpResponse . code ( ) , httpResponse . body ( ) ) ; return Collections . emptyList ( ) ; }


signature:
public class KeyValueStoreEndpoint { /** * Deletes a specified key .
 * @ param key The key to delete .
 * @ param params Map of parameters , e . g . recurse . */
private void delete ( String key , Map < String , String > params ) { } }

implementation: final URI uri = createURI ( "/" + key ) ; final HttpRequestBuilder httpRequestBuilder = RequestUtils . getHttpRequestBuilder ( null , null , RequestOptions . BLANK , "" ) ; final Set < Map . Entry < String , String > > entries = params . entrySet ( ) ; for ( Map . Entry < String , String > entry : entries ) { httpRequestBuilder . addParam ( entry . getKey ( ) , entry . getValue ( ) ) ; } httpRequestBuilder . setMethodDelete ( ) ; final HTTP . Response httpResponse = HTTP . deleteResponse ( uri . toString ( ) + "?" + httpRequestBuilder . paramString ( ) ) ; if ( httpResponse . code ( ) != 200 ) { die ( "Unable to delete key" , uri , key , httpResponse . code ( ) , httpResponse . body ( ) ) ; }


signature:
public class StreamToIterator { /** * Returns { @ code true } if the iteration has more elements .
 * ( In other words , returns { @ code true } if { @ link # next } would
 * return an element rather than throwing an exception . )
 * Checks to see if the stream is closed or has sent an error .
 * @ return { @ code true } if the iteration has more elements */
@ Override public boolean hasNext ( ) { } }

implementation:
/* If we are in the completed state let the end user know . */
if ( complete ) { return false ; } /* If we called hasNext twice , do not poll the queue . */
if ( next != null ) { return true ; } /* Get the item from the queue , and block until we do . */
Object item = null ; while ( item == null ) { try { item = blockingQueue . take ( ) ; } catch ( InterruptedException e ) { Thread . interrupted ( ) ; } } /* Check to see if the complete message was sent .
 * If so mark this iterator has completed and set the next item to null . */
if ( item == COMPLETE ) { complete = true ; next = null ; return false ; } else { /* Store the next item . */
next = ( T ) item ; return true ; }


signature:
public class StreamToIterator { /** * Returns the next element in the iteration .
 * This will throw a { @ code StreamException } wrapping the error sent from the stream .
 * @ return the next element in the iteration
 * @ throws NoSuchElementException if the iteration has no more elements */
@ Override public T next ( ) { } }

implementation:
/* If the item is null and we are complete then calling this is a programming error . */
if ( next == null && complete ) { throw new NoSuchElementException ( "The stream has completed. There are no more items." ) ; } /* If the item is an error , throw the error wrapped by a runtime error . */
if ( next == ERROR ) { try { final Object error = blockingQueue . take ( ) ; complete = true ; throw new StreamException ( "Exception from stream" , ( Throwable ) error ) ; } catch ( InterruptedException e ) { Thread . interrupted ( ) ; throw new StreamException ( "Stream sent error but unable to get error from stream" , e ) ; } } else { /* Give them the next item but don ' t store the next item any longer . */
T theNext = next ; next = null ; return theNext ; }


signature:
public class SimpleHttpServer { /** * Main entry point .
 * @ param request request to handle */
public void handleRequest ( final HttpRequest request ) { } }

implementation: if ( debug ) { System . out . println ( "HttpServer::handleRequest " + request ) ; logger . debug ( "HttpServer::handleRequest" + request ) ; } if ( shouldContinueHttpRequest . test ( request ) ) { httpRequestConsumer . accept ( request ) ; }


signature:
public class EventBusQueueAdapter { /** * Process . This can be called periodically and it will check to see if there are messages on the queue . */
public void process ( ) { } }

implementation: if ( ! receiveQueue . isPresent ( ) ) { initQueue ( ) ; } receiveQueue . ifPresent ( receiveQueue -> { T item ; do { try { item = receiveQueue . poll ( ) ; } catch ( Exception ex ) { logger . debug ( "Unable to receive message" , ex ) ; initQueue ( ) ; item = null ; } if ( item != null ) { sendToEventManager ( item ) ; } } while ( item != null ) ; } ) ;


signature:
public class EventBusQueueAdapter { /** * Send the queue item to the event .
 * @ param item item */
private void sendToEventManager ( T item ) { } }

implementation: if ( debug ) { logger . debug ( "EventBusQueueAdapter::sendToEventManager({})" , item ) ; } try { if ( lock . tryLock ( ) ) { eventManager . sendArguments ( channel , item ) ; } else { lock . lock ( ) ; eventManager . sendArguments ( channel , item ) ; } } finally { lock . unlock ( ) ; }


signature:
public class EventBusQueueAdapter { /** * Start listener . Once this is called messages can come in on a foreign thread . */
public void start ( ) { } }

implementation: if ( ! queue . isPresent ( ) ) { initQueue ( ) ; } queue . ifPresent ( actualQueue -> actualQueue . startListener ( EventBusQueueAdapter . this :: sendToEventManager ) ) ;


signature:
public class EndpointDefinition { /** * Creates a EndpointDefinition for a service , i . e . , a serviceDefinition .
 * @ param id id
 * @ param name name
 * @ param host host
 * @ param port port
 * @ param tags tags
 * @ return EndpointDefinition */
public static EndpointDefinition serviceDefinition ( final String id , final String name , final String host , final int port , List < String > tags ) { } }

implementation: return new EndpointDefinition ( HealthStatus . PASS , id , name , host , port , tags ) ;


signature:
public class EndpointDefinition { /** * Creates a EndpointDefinition for a service , i . e . , a serviceDefinition .
 * @ param name name
 * @ param host host
 * @ param port port
 * @ return serviceDefinition */
public static EndpointDefinition serviceDefinition ( final String name , final String host , final int port ) { } }

implementation: return new EndpointDefinition ( HealthStatus . PASS , name + "-" + uniqueString ( port ) , name , host , port ) ;


signature:
public class EndpointDefinition { /** * Creates a EndpointDefinition for a service , i . e . , a serviceDefinition .
 * @ param id id
 * @ param name name
 * @ param host host
 * @ return EndpointDefinition */
public static EndpointDefinition serviceDefinitionWithId ( final String name , final String host , final String id ) { } }

implementation: return new EndpointDefinition ( HealthStatus . PASS , id , name , host , 0 ) ;


signature:
public class HttpContext { /** * Grab the current http request .
 * @ return Optional http request . */
public Optional < HttpRequest > getHttpRequest ( ) { } }

implementation: final Optional < Request < Object > > request = this . getRequest ( ) ; if ( request . isPresent ( ) ) { return findHttpRequest ( request . get ( ) ) ; } else { return Optional . empty ( ) ; }


signature:
public class EventConnectorHub { /** * Remove an event connector
 * @ param eventConnector eventConnector */
public void remove ( final EventConnector eventConnector ) { } }

implementation: if ( eventConnector != null ) { try { if ( eventConnector instanceof RemoteTCPClientProxy ) { final RemoteTCPClientProxy remoteTCPClientProxy = ( RemoteTCPClientProxy ) eventConnector ; logger . info ( Str . sputs ( "Removing event connector host " , remoteTCPClientProxy . host ( ) , " port " , remoteTCPClientProxy . port ( ) , "connected " , remoteTCPClientProxy . connected ( ) ) ) ; remoteTCPClientProxy . silentClose ( ) ; } this . eventConnectors . remove ( eventConnector ) ; } catch ( Exception ex ) { logger . error ( "Unable to remove event connector" , ex ) ; } }


signature:
public class EventConnectorHub { /** * Forwards en event to another event system .
 * @ param event event */
@ Override public void forwardEvent ( final EventTransferObject < Object > event ) { } }

implementation: if ( debug ) logger . debug ( "forwardEvent " + event . channel ( ) + " size " + eventConnectors . size ( ) ) ; for ( int index = 0 ; index < eventConnectors . size ( ) ; index ++ ) { EventConnector eventConnector = null ; try { eventConnector = eventConnectors . get ( index ) ; eventConnector . forwardEvent ( event ) ; } catch ( Exception ex ) { logger . error ( "problem sending event to event connector" , ex ) ; if ( eventConnector instanceof RemoteTCPClientProxy ) { if ( ! ( ( RemoteTCPClientProxy ) eventConnector ) . connected ( ) ) { eventConnectors . remove ( eventConnector ) ; } } } } if ( debug ) logger . debug ( "forwardEvent done " + event . channel ( ) ) ;


signature:
public class EventConnectorHub { /** * Flushes the pool used to optimize flushing of IO operations . */
@ Override public void flush ( ) { } }

implementation: for ( int index = 0 ; index < eventConnectors . size ( ) ; index ++ ) { EventConnector eventConnector = null ; try { eventConnector = eventConnectors . get ( index ) ; if ( eventConnector instanceof ClientProxy ) { ServiceProxyUtils . flushServiceProxy ( eventConnector ) ; } else { eventConnector . flush ( ) ; } } catch ( Exception ex ) { logger . debug ( "problem sending event to event connector" , ex ) ; if ( eventConnector instanceof RemoteTCPClientProxy ) { if ( ! ( ( RemoteTCPClientProxy ) eventConnector ) . connected ( ) ) { eventConnectors . remove ( eventConnector ) ; } } } }


signature:
public class MicroserviceConfig { /** * Reads the readConfig file , which can be a classpath or file system resource .
 * @ param serviceName the name of the service to load
 * @ return service config */
public static MicroserviceConfig readConfig ( final String serviceName ) { } }

implementation: final Logger logger = LoggerFactory . getLogger ( MicroserviceConfig . class ) ; if ( new File ( resourceLocation ) . exists ( ) ) { final String json = IO . read ( resourceLocation ) ; return JsonFactory . fromJson ( json , MicroserviceConfig . class ) ; } else if ( resourceLocationEnv != null && new File ( resourceLocationEnv ) . exists ( ) ) { final String json = IO . read ( resourceLocationEnv ) ; return JsonFactory . fromJson ( json , MicroserviceConfig . class ) ; } else { logger . info ( "Reading config from classpath as it is not found on file system" ) ; final String qbitEnv = System . getenv ( "QBIT_ENV" ) ; final String resourceLocationOnClasspath = qbitEnv != null && ! qbitEnv . isEmpty ( ) ? serviceName + "_" + qbitEnv + ".json" : serviceName + ".json" ; final String json = IO . read ( Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( resourceLocationOnClasspath ) ) ; return JsonFactory . fromJson ( json , MicroserviceConfig . class ) ; }


signature:
public class CallbackManagerWithTimeout { /** * Register a callbackWithTimeout handler
 * @ param methodCall method call
 * @ param handler call back handler to register */
private void registerHandlerCallbackForClient ( final MethodCall < Object > methodCall , final Callback < Object > handler ) { } }

implementation: final HandlerKey handlerKey = new HandlerKey ( methodCall . returnAddress ( ) , methodCall . address ( ) , methodCall . id ( ) , methodCall . timestamp ( ) ) ; if ( debug ) { if ( handlers . containsKey ( handlerKey ) ) { logger . debug ( "DUPLICATE HANDLERS {}" , handlerKey ) ; } } handlers . put ( handlerKey , handler ) ;


signature:
public class CallbackManagerWithTimeout { /** * Handles responses coming back from services .
 * @ param responseQueue response queue */
@ Override public void startReturnHandlerProcessor ( final Queue < Response < Object > > responseQueue ) { } }

implementation:
// noinspection Convert2MethodRef
responseQueue . startListener ( response -> handleResponse ( response ) ) ;


signature:
public class SetupMdcForHttpRequestInterceptor { /** * Gets called before a method gets invoked on a service .
 * This adds request URI , remote address and request headers of the HttpRequest if found .
 * @ param methodCall methodCall
 * @ return true to continue , always true . */
@ Override public boolean before ( final MethodCall methodCall ) { } }

implementation: final Optional < HttpRequest > httpRequest = findHttpRequest ( methodCall ) ; if ( httpRequest . isPresent ( ) ) { extractRequestInfoAndPutItIntoMappedDiagnosticContext ( httpRequest . get ( ) ) ; } return true ;


signature:
public class SetupMdcForHttpRequestInterceptor { /** * Extract request data and put it into the logging Mapped Diagnostic Context .
 * @ param httpRequest httpRequest */
private void extractRequestInfoAndPutItIntoMappedDiagnosticContext ( final HttpRequest httpRequest ) { } }

implementation: MDC . put ( REQUEST_URI , httpRequest . getUri ( ) ) ; MDC . put ( REQUEST_REMOTE_ADDRESS , httpRequest . getRemoteAddress ( ) ) ; MDC . put ( REQUEST_HTTP_METHOD , httpRequest . getMethod ( ) ) ; MDC . put ( REQUEST_ID , Long . toString ( httpRequest . getMessageId ( ) ) ) ; extractHeaders ( httpRequest ) ;


signature:
public class SetupMdcForHttpRequestInterceptor { /** * Extract headersToAddToLoggingMappingDiagnosticsContext data and put them into the logging mapping diagnostics context .
 * @ param httpRequest httpRequest */
private void extractHeaders ( final HttpRequest httpRequest ) { } }

implementation: if ( headersToAddToLoggingMappingDiagnosticsContext . size ( ) > 0 ) { final MultiMap < String , String > headers = httpRequest . getHeaders ( ) ; headersToAddToLoggingMappingDiagnosticsContext . forEach ( header -> { String value = headers . getFirst ( header ) ; if ( ! Str . isEmpty ( value ) ) { MDC . put ( REQUEST_HEADER_PREFIX + header , value ) ; } } ) ; }


signature:
public class HttpRequestServiceServerHandlerUsingMetaImpl { /** * MOST IMPORTANT METHOD FOR DEBUGGING WHY SOMETHING IS NOT CALLED . */
@ Override public void handleRestCall ( final HttpRequest request ) { } }

implementation: final List < String > errorList = new ArrayList < > ( 0 ) ; final MethodCall < Object > methodCall = standardRequestTransformer . transform ( request , errorList ) ; if ( methodCall != null && errorList . size ( ) == 0 ) { if ( ! addRequestToCheckForTimeouts ( request ) ) { handleOverflow ( request ) ; return ; } sendMethodToServiceBundle ( methodCall ) ; } else { if ( ! request . isHandled ( ) ) { handleErrorConverting ( request , errorList , methodCall ) ; } return ; } final RequestMetaData requestMetaData = metaDataProviderMap . get ( RequestMethod . valueOf ( request . getMethod ( ) ) ) . get ( request . address ( ) ) ; final ServiceMethodMeta serviceMethod = requestMetaData . getMethod ( ) ; if ( serviceMethod . getMethodAccess ( ) . returnType ( ) == void . class && ! serviceMethod . hasCallBack ( ) ) { request . handled ( ) ; final int responseCode = serviceMethod . getResponseCode ( ) ; writeResponse ( request . getReceiver ( ) , responseCode == - 1 ? HttpStatus . ACCEPTED : responseCode , serviceMethod . getContentType ( ) , "\"success\"" , requestMetaData . getRequest ( ) . getResponseHeaders ( ) ) ; }


signature:
public class HttpRequestServiceServerHandlerUsingMetaImpl { /** * 2nd MOST IMPORTANT METHOD FOR DEBUGGING WHY SOMETHING IS NOT CALLED . */
@ Override public void handleResponseFromServiceToHttpResponse ( final Response < Object > response , final HttpRequest originatingRequest ) { } }

implementation: final String key = Str . add ( "" + originatingRequest . id ( ) , "|" , originatingRequest . returnAddress ( ) ) ; this . outstandingRequestMap . remove ( key ) ; if ( response . wasErrors ( ) ) { handleError ( response , originatingRequest ) ; } else { if ( response . body ( ) instanceof HttpResponse ) { writeHttpResponse ( originatingRequest . getReceiver ( ) , ( ( HttpResponse ) response . body ( ) ) ) ; } else { final RequestMetaData requestMetaData = metaDataProviderMap . get ( RequestMethod . valueOf ( originatingRequest . getMethod ( ) ) ) . get ( originatingRequest . address ( ) ) ; final ServiceMethodMeta serviceMethodMeta = requestMetaData . getMethod ( ) ; final int responseCode = serviceMethodMeta . getResponseCode ( ) ; MultiMap < String , String > headers = response . headers ( ) ; if ( requestMetaData . getRequest ( ) . hasResponseHeaders ( ) ) { if ( response . headers ( ) == MultiMap . EMPTY ) { headers = new MultiMapImpl < > ( ) ; } else { headers = response . headers ( ) ; } headers . putAllCopyLists ( requestMetaData . getRequest ( ) . getResponseHeaders ( ) ) ; } writeResponse ( originatingRequest . getReceiver ( ) , responseCode == - 1 ? HttpStatus . OK : responseCode , serviceMethodMeta . getContentType ( ) , jsonMapper . toJson ( response . body ( ) ) , headers ) ; } }


signature:
public class HttpRequestServiceServerHandlerUsingMetaImpl { /** * Add a request to the timeout queue . Server checks for timeouts when it is idle or when
 * the max outstanding outstandingRequests is met .
 * @ param request request . */
private boolean addRequestToCheckForTimeouts ( final Request < Object > request ) { } }

implementation: String key = Str . add ( "" + request . id ( ) , "|" , request . returnAddress ( ) ) ; this . outstandingRequestMap . put ( key , request ) ; return outstandingRequestMap . size ( ) < numberOfOutstandingRequests ;


signature:
public class StatList { /** * Add a new value to the list .
 * @ param integer new value
 * @ return was able to add . */
@ Override public boolean add ( Long integer ) { } }

implementation: if ( end + 1 >= values . length ) { values = Lng . grow ( values ) ; } values [ end ] = integer ; end ++ ; return true ;


signature:
public class StatList { /** * Add a new value to the list but don ' t employ a wrapper .
 * @ param integer new value
 * @ return was able to add . */
@ SuppressWarnings ( "UnusedReturnValue" ) public StatList add ( int integer ) { } }

implementation: if ( end + 1 >= values . length ) { values = Lng . grow ( values ) ; } values [ end ] = integer ; end ++ ; return this ;


signature:
public class StatList { /** * Add a new array to the list .
 * @ param newValues new values
 * @ return was able to add . */
public boolean addArray ( long ... newValues ) { } }

implementation: if ( end + newValues . length >= values . length ) { values = Lng . grow ( values , ( values . length + newValues . length ) * 2 ) ; } System . arraycopy ( newValues , 0 , values , end , newValues . length ) ; end += newValues . length ; return true ;


signature:
public class StatList { /** * Set a value in the list .
 * @ param index index
 * @ param element new value
 * @ return old value at this index */
@ Override public Long set ( int index , Long element ) { } }

implementation: long oldValue = values [ index ] ; values [ index ] = element ; return oldValue ;


signature:
public class StatList { /** * This would be a good opportunity to reintroduce dynamic invoke
 * @ param function function
 * @ param name name
 * @ return result */
public long reduceBy ( Object function , String name ) { } }

implementation: return Lng . reduceBy ( values , end , function , name ) ;


signature:
public class ForwardCallMethodInterceptor { /** * Intercept the call before it gets sent to the service queue .
 * @ param methodBuilder methodBuilder */
@ Override public void beforeMethodSent ( final MethodCallBuilder methodBuilder ) { } }

implementation: if ( methodBuilder . getOriginatingRequest ( ) == null ) { final Optional < Request < Object > > request = requestContext . getRequest ( ) ; if ( request . isPresent ( ) ) { methodBuilder . setOriginatingRequest ( request . get ( ) ) ; } }


signature:
public class AbstractChangeNotifier { /** * Notify the listener about a change . If this is due to adding a new listener rather than
 * being an update , only notify the listener if this is the first notification sent to it .
 * @ param changeNotification the change notification to send
 * @ param newListener call is triggered by adding a listener rather than an update */
private void notifyListener ( ChangeNotification < T > changeNotification , boolean newListener ) { } }

implementation: lock . lock ( ) ; try { checkNotNull ( changeNotification , "changeNotification" ) ; final Listener < T > listener = listenerRef . get ( ) ; if ( listener != null ) { try { final boolean notified = listenerNotified . getAndSet ( true ) ; if ( ! ( newListener && notified ) ) { listener . onChange ( changeNotification ) ; } } catch ( Throwable e ) { log . error ( "Change notification listener threw exception" , e ) ; } } } finally { lock . unlock ( ) ; }


signature:
public class DnsSrvWatchers { /** * Creates a { @ link DnsSrvWatcherBuilder } using the given { @ link DnsSrvResolver } . The builder
 * can be configured to have the desired behavior .
 * < p > Exactly one of { @ link DnsSrvWatcherBuilder # polling ( long , TimeUnit ) } or
 * { @ link DnsSrvWatcherBuilder # customTrigger ( DnsSrvWatcherFactory ) } must be used .
 * @ param resolver The resolver to use for lookups
 * @ return a builder for further configuring the watcher */
public static DnsSrvWatcherBuilder < LookupResult > newBuilder ( DnsSrvResolver resolver ) { } }

implementation: checkNotNull ( resolver , "resolver" ) ; return new DnsSrvWatcherBuilder < LookupResult > ( resolver , Functions . < LookupResult > identity ( ) ) ;


signature:
public class DnsSrvWatchers { /** * Creates a { @ link DnsSrvWatcherBuilder } using the given { @ link DnsSrvResolver } . The builder
 * can be configured to have the desired behavior .
 * < p > This watcher will use a function that transforms the { @ link LookupResult } s into an
 * arbitrary type that will be used throughout the { @ link DnsSrvWatcher } api .
 * < p > Exactly one of { @ link DnsSrvWatcherBuilder # polling ( long , TimeUnit ) } or
 * { @ link DnsSrvWatcherBuilder # customTrigger ( DnsSrvWatcherFactory ) } must be used .
 * @ param resolver The resolver to use for lookups
 * @ param resultTransformer The transformer function
 * @ return a builder for further configuring the watcher */
public static < T > DnsSrvWatcherBuilder < T > newBuilder ( DnsSrvResolver resolver , Function < LookupResult , T > resultTransformer ) { } }

implementation: checkNotNull ( resolver , "resolver" ) ; checkNotNull ( resultTransformer , "resultTransformer" ) ; return new DnsSrvWatcherBuilder < T > ( resolver , resultTransformer ) ;


signature:
public class ChangeNotifiers { /** * Creates a { @ link ChangeNotifier } that aggregates the records provided by a list of notifiers .
 * < p > A change event on any of the input notifiers will propagate up the the returned notifier .
 * The set of previous and current records contained in the event will be the union of all
 * records in the input notifiers , before and after the change event .
 * @ param notifiers A list of notifiers to aggregate
 * @ param < T > The record type
 * @ return A notifier with the described behaviour */
public static < T > ChangeNotifier < T > aggregate ( ChangeNotifier < T > ... notifiers ) { } }

implementation: return aggregate ( Arrays . asList ( notifiers ) ) ;


signature:
public class ChangeNotifiers { /** * Create a { @ link ChangeNotifier } with a static set of records .
 * < p > This notifier will never generate any change events . Thus any attached
 * { @ link ChangeNotifier . Listener } will at most get one initial call to
 * { @ link ChangeNotifier . Listener # onChange ( ChangeNotifier . ChangeNotification ) }
 * if they are attached with the { @ code fire } argument set to { @ code true } .
 * @ param records The records that the notifier will contain
 * @ param < T > The record type
 * @ return A notifier with a static set of records */
public static < T > ChangeNotifier < T > staticRecords ( T ... records ) { } }

implementation: return staticRecords ( Sets . newHashSet ( records ) ) ;


signature:
public class ChangeNotifiers { /** * Create a { @ link RunnableChangeNotifier } that directly wraps a set of records given by a
 * { @ link Supplier } .
 * < p > Each call to { @ link Runnable # run ( ) } will cause the supplier to be polled and regular
 * change notifications to be triggered .
 * < p > This implementation is useful for testing components that depend on a
 * { @ link ChangeNotifier } .
 * @ param recordsSupplier The supplier of records
 * @ param < T > The record type
 * @ return A runnable notifier */
public static < T > RunnableChangeNotifier < T > direct ( Supplier < Set < T > > recordsSupplier ) { } }

implementation: return new DirectChangeNotifier < T > ( recordsSupplier ) ;


signature:
public class SynchronizedCollectionsSerializer { /** * Creates a new { @ link SynchronizedCollectionsSerializer } and registers its serializer
 * for the several synchronized Collections that can be created via { @ link Collections } ,
 * including { @ link Map } s .
 * @ param kryo the { @ link Kryo } instance to set the serializer on .
 * @ see Collections # synchronizedCollection ( Collection )
 * @ see Collections # synchronizedList ( List )
 * @ see Collections # synchronizedSet ( Set )
 * @ see Collections # synchronizedSortedSet ( SortedSet )
 * @ see Collections # synchronizedMap ( Map )
 * @ see Collections # synchronizedSortedMap ( SortedMap ) */
public static void registerSerializers ( final Kryo kryo ) { } }

implementation: final SynchronizedCollectionsSerializer serializer = new SynchronizedCollectionsSerializer ( ) ; SynchronizedCollection . values ( ) ; for ( final SynchronizedCollection item : SynchronizedCollection . values ( ) ) { kryo . register ( item . type , serializer ) ; }


signature:
public class ImmutableMultimapSerializer { /** * / * kryo . getSerializer ( invoking kryo . getRegistration ) throws an exception if registration is required ,
 * therefore we ' re getting a potentially existing serializer on another way . */
private static Serializer < ? > getSerializer ( Kryo kryo , Class < ? > type ) { } }

implementation: Registration registration = kryo . getClassResolver ( ) . getRegistration ( type ) ; return registration != null ? registration . getSerializer ( ) : null ;