protected void recordTiming(String statKey, long timeSpan) {
        final String longKey = getActualStatKey(statKey);
        statsCollector.recordTiming(longKey, timeSpan);
    }

protected void recordTiming ( String statKey , long timeSpan ) { final String longKey = getActualStatKey ( statKey ) ; statsCollector . recordTiming ( longKey , timeSpan ) ; }

Prefixes the stats key with the stat key prefix, and then calls statsCollector.recordTiming.

@param statKey  statKey
@param timeSpan timeSpan

Prefixes the stats key with the stat key prefix and then calls statsCollector . recordTiming .


private void trackTimeouts() {
        new ArrayList<>(httpRequestHolderList).forEach(httpRequestHolder -> {

            /* If it is handled then remove it from the list. */
            if (httpRequestHolder.request.isHandled()) {
                httpRequestHolderList.remove(httpRequestHolder);
                return;
            }

            /* Get the duration that this request has been around. */
            final long duration = time - httpRequestHolder.startTime;

            /* See if the duration is greater than the timeout time. */
            if (duration > timeOutIntervalMS) {

                /* If we timed out, mark the request as handled, and then notify the client that the
                backend timed out.
                 */
                httpRequestHolder.request.handled();

                /* Tell client that the backend timed out. */
                httpRequestHolder.request.getReceiver().timeoutWithMessage(String.format("\"TIMEOUT %s %s %s\"",
                        httpRequestHolder.request.address(),
                        httpRequestHolder.request.getRemoteAddress(),
                        httpRequestHolder.startTime
                ));

                /* If we timed out then remove this from the list. */
                httpRequestHolderList.remove(httpRequestHolder); //Not very fast if you a lot of outstanding requests
            }
        });
    }

Tracks timeouts periodically if timeout tracking is enabled.

Tracks timeouts periodically if timeout tracking is enabled .


private void checkClient() {

        try {

            /** If the errorCount is greater than 0, make sure we are still connected. */
            if (errorCount.get() > 0) {
                errorCount.set(0);
                if (backendServiceHttpClient == null || backendServiceHttpClient.isClosed()) {

                    if (backendServiceHttpClient != null) {
                        try {
                            backendServiceHttpClient.stop();
                        } catch (Exception ex) {
                            logger.debug("Was unable to stop the client connection", ex);
                        }
                    }
                    backendServiceHttpClient = httpClientBuilder.buildAndStart();
                    lastHttpClientStart = time;
                }
            }

            /** If the ping builder is present, use it to ping the service. */
            if (pingBuilder.isPresent()) {

                if (backendServiceHttpClient != null) {
                    pingBuilder.get().setBinaryReceiver((code, contentType, body) -> {
                        if (code >= 200 && code < 299) {
                            pingCount.incrementAndGet();
                        } else {
                            errorCount.incrementAndGet();
                        }

                    }).setErrorHandler(e -> {
                        logger.error("Error doing ping operation", e);
                        errorCount.incrementAndGet();
                    });

                    final HttpRequest httpRequest = pingBuilder.get().build();

                    backendServiceHttpClient.sendHttpRequest(httpRequest);
                }
            }

        } catch (Exception ex) {
            errorHandler.accept(ex);
            logger.error("Unable to check connection");
        }

    }

Checks client health periodically to see if we are connected. Tries to reconnect if not connected.

Checks client health periodically to see if we are connected . Tries to reconnect if not connected .


@Override
    public void handleRequest(final HttpRequest clientRequest) {

        if (trackTimeOuts) {
            httpRequestHolderList.add(new HttpRequestHolder(clientRequest, time));
        }

        if (httpClientRequestPredicate.test(clientRequest)) {
            createBackEndRequestPopulateAndForward(clientRequest);
        }
    }

@ Override public void handleRequest ( final HttpRequest clientRequest ) { if ( trackTimeOuts ) { httpRequestHolderList . add ( new HttpRequestHolder ( clientRequest , time ) ) ; } if ( httpClientRequestPredicate . test ( clientRequest ) ) { createBackEndRequestPopulateAndForward ( clientRequest ) ; } }

Request coming from the client side.

@param clientRequest clientRequest


private void createBackEndRequestPopulateAndForward(final HttpRequest clientRequest) {
        try {

            if (backendServiceHttpClient == null) {
                handleHttpClientErrorsForBackend(clientRequest, new HttpClientClosedConnectionException("Not connected"));
                long timeSinceLastStart = time - lastHttpClientStart;
                if (timeSinceLastStart > 10_000) {
                    checkClient();
                }
                return;
            }
    /* forward request to backend client. */
            final HttpRequestBuilder httpRequestBuilder = HttpRequestBuilder.httpRequestBuilder()
                    .copyRequest(clientRequest).setBinaryReceiver(new HttpBinaryReceiver() {
                        @Override
                        public void response(final int code,
                                             final String contentType,
                                             final byte[] body,
                                             final MultiMap<String, String> headers) {
                            handleBackendClientResponses(clientRequest, code, contentType, body, headers);
                        }

                        @Override
                        public void response(int code, String contentType, byte[] body) {
                            response(code, contentType, body, MultiMap.empty());
                        }
                    }).setErrorHandler(e -> handleHttpClientErrorsForBackend(clientRequest, e));

            /** Give user of the lib a chance to populate headers and such. */
            beforeSend.accept(httpRequestBuilder);

            backendServiceHttpClient.sendHttpRequest(httpRequestBuilder.build());
        } catch (HttpClientClosedConnectionException httpClientClosedConnectionException) {

            errorCount.incrementAndGet();
            errorHandler.accept(httpClientClosedConnectionException);
            logger.error("Unable to forward request", httpClientClosedConnectionException);
            handleHttpClientErrorsForBackend(clientRequest, httpClientClosedConnectionException);
            backendServiceHttpClient = null;

            long timeSinceLastStart = time - lastHttpClientStart;
            if (timeSinceLastStart > 10_000) {
                checkClient();
            }

        } catch (Exception ex) {
            errorCount.incrementAndGet();
            errorHandler.accept(ex);
            logger.error("Unable to forward request", ex);
            handleHttpClientErrorsForBackend(clientRequest, ex);

            long timeSinceLastStart = time - lastHttpClientStart;
            if (timeSinceLastStart > 10_000) {
                checkClient();
            }

        }
    }

Creates a backend request from the client request and then forwards it.

@param clientRequest clientRequest

Creates a backend request from the client request and then forwards it .


private void handleHttpClientErrorsForBackend(final HttpRequest clientRequest, final Exception e) {
                /* Notify error handler that we got an error. */
        errorHandler.accept(e);

                /* Increment our error count. */
        errorCount.incrementAndGet();

                /* Create the error message. */
        final String errorMessage = String.format("Unable to make request %s ",
                clientRequest.address());

                        /* Log the error. */
        logger.error(errorMessage, e);

        /* Don't send the error to the client if we already handled this, i.e., timedout already. */
        if (!clientRequest.isHandled()) {
            clientRequest.handled();
            /* Notify the client that there was an error. */
            clientRequest.getReceiver().error(String.format("\"%s\"", errorMessage));
        }

    }

Handle errors.

@param clientRequest clientRequest
@param e             exception


private void handleBackendClientResponses(final HttpRequest clientRequest,
                                              final int code,
                                              final String contentType,
                                              final byte[] body,
                                              final MultiMap<String, String> headers) {

        /** If it is handled like it timed out already or some other error then don't do anything. */
        if (!clientRequest.isHandled()) {

            /* If it was handled, let everyone know so we don't get a timeout. */
            clientRequest.handled();

            /* Send the response out the front end. */
            clientRequest.getReceiver().response(code, contentType, body, headers);
        }
    }

Handle a response from the backend service

@param clientRequest clientRequest (original client request)
@param code          response code from the backend.
@param contentType   contentType from the backend.
@param body          body from the backend.
@param headers       headers from the backend.


@QueueCallback({QueueCallbackType.EMPTY,
            QueueCallbackType.IDLE,
            QueueCallbackType.LIMIT})
    public void process() {
        reactor.process();
        time = timer.time();
    }

@ QueueCallback ( { QueueCallbackType . EMPTY , QueueCallbackType . IDLE , QueueCallbackType . LIMIT } ) public void process ( ) { reactor . process ( ) ; time = timer . time ( ) ; }


public static ServiceDiscovery createLokateServiceDiscovery(final List<URI> configs) {

        return serviceDiscoveryBuilder()
                .setServiceDiscoveryProvider(
                        new LokateServiceDiscoveryProvider(
                                DiscoveryService.create(configs)))
                .build();

    }

public static ServiceDiscovery createLokateServiceDiscovery ( final List < URI > configs ) { return serviceDiscoveryBuilder ( ) . setServiceDiscoveryProvider ( new LokateServiceDiscoveryProvider ( DiscoveryService . create ( configs ) ) ) . build ( ) ; }

Create service discovery that can talk via Lokate.

@param configs configs
@return ServiceDiscovery

Create service discovery that can talk via Lokate .


private void doCall(MethodCall<Object> methodCall) {
        if (debug) {
            logger.debug(ServiceBundleImpl.class.getName(), "::doCall() ",
                    methodCall.name(),
                    methodCall.address(),
                    "\n", methodCall);
        }

        try {
            if (methodCall.hasCallback()) {
                callbackManager.registerCallbacks(methodCall);
            }
            boolean[] continueFlag = new boolean[1];
            methodCall = handleBeforeMethodCall(methodCall, continueFlag);

            if (!continueFlag[0]) {
                if (debug) {
                    logger.debug(ServiceBundleImpl.class.getName() + "::doCall() " +
                            "Flag from before call handling does not want to continue");
                }
            } else {
                final Consumer<MethodCall<Object>> methodDispatcher = getMethodDispatcher(methodCall);
                methodDispatcher.accept(methodCall);

            }

        } catch (Exception ex) {
            Response<Object> response = new ResponseImpl<>(methodCall, ex);
            this.responseQueue.sendQueue().sendAndFlush(response);
        }
    }

Handles calling a method

@param methodCall method call


@Override
    @SuppressWarnings("unchecked")
    public void call(final MethodCall<Object> methodCall) {

        if (debug) {
            logger.debug(ServiceBundleImpl.class.getName() + "::call() " +
                    methodCall.name() + " " + " " +
                    methodCall.address() +
                    "\n" + methodCall);
        }
        methodSendQueue.send(methodCall);
    }

@
Override
@
SuppressWarnings
(
"unchecked"
)
public
void
call
(
final
MethodCall
<
Object
>
methodCall
)
{
if
(
debug
)
{
logger
.
debug
(
ServiceBundleImpl
.
class
.
getName
(
)
+
"::call() "
+
methodCall
.
name
(
)
+
" "
+
" "
+
methodCall
.
address
(
)
+
"\n"
+
methodCall
)
;
}
methodSendQueue
.
send
(
methodCall
)
;
}


@Override
    public <T> T createLocalProxy(final Class<T> serviceInterface, final String myService) {

        final Consumer<MethodCall<Object>> callConsumer = this.serviceMapping.get(myService);

        if (callConsumer == null) {
            logger.error("Service requested does not exist " + myService);
        }

        return factory.createLocalProxy(serviceInterface, myService, this, beforeMethodSent);

    }

@
Override
public
<
T
>
T
createLocalProxy
(
final
Class
<
T
>
serviceInterface
,
final
String
myService
)
{
final
Consumer
<
MethodCall
<
Object
>
>
callConsumer
=
this
.
serviceMapping
.
get
(
myService
)
;
if
(
callConsumer
==
)
{
logger
.
error
(
"Service requested does not exist "
+
myService
)
;
}
return
factory
.
createLocalProxy
(
serviceInterface
,
myService
,
this
,
beforeMethodSent
)
;
}

Creates a proxy interface to a particular client. Given a particular address.

@param serviceInterface client view interface of client
@param myService        address or name of client
@param <T>              type of client
@return proxy client to client

Creates a proxy interface to a particular client . Given a particular address .


private MethodCall<Object> beforeMethodCall(MethodCall<Object> methodCall, boolean[] continueCall) {
        if (this.beforeMethodCall.before(methodCall)) {
            continueCall[0] = true;
            methodCall = transformBeforeMethodCall(methodCall);

            continueCall[0] = this.beforeMethodCallAfterTransform.before(methodCall);
            return methodCall;

        } else {
            continueCall[0] = false;

        }
        return methodCall;
    }

private MethodCall < Object > beforeMethodCall ( MethodCall < Object > methodCall , boolean [ ] continueCall ) { if ( this . beforeMethodCall . before ( methodCall ) ) { continueCall [ 0 ] = true ; methodCall = transformBeforeMethodCall ( methodCall ) ; continueCall [ 0 ] = this . beforeMethodCallAfterTransform . before ( methodCall ) ; return methodCall ; } else { continueCall [ 0 ] = false ; } return methodCall ; }

Handles before call operation

@param methodCall   method call
@param continueCall should we continue the call.
@return call object which could have been transformed


private MethodCall<Object> transformBeforeMethodCall(MethodCall<Object> methodCall) {
        if (argTransformer == null || argTransformer == ServiceConstants.NO_OP_ARG_TRANSFORM) {
            return methodCall;
        }
        Object arg = this.argTransformer.transform(methodCall);
        return MethodCallBuilder.transformed(methodCall, arg);
    }

private MethodCall < Object > transformBeforeMethodCall ( MethodCall < Object > methodCall ) { if ( argTransformer == null || argTransformer == ServiceConstants . NO_OP_ARG_TRANSFORM ) { return methodCall ; } Object arg = this . argTransformer . transform ( methodCall ) ; return MethodCallBuilder . transformed ( methodCall , arg ) ; }

Handles the before argument transformer.

@param methodCall method call that we might transform
@return method call

Handles the before argument transformer .


@SuppressWarnings("Convert2streamapi")
    public void stop() {
        if (debug) {
            logger.debug(ServiceBundleImpl.class.getName(), "::stop()");
        }
        methodQueue.stop();
        for (Stoppable service : servicesToStop) {
            service.stop();
        }

        try {
            responseQueue.stop();
        } catch (Exception ex) {
            logger.debug("", ex);
        }

        try {
            webResponseQueue.stop();
        } catch (Exception ex) {
            logger.debug("", ex);
        }
        if (systemManager != null) systemManager.serviceShutDown();
    }

@ SuppressWarnings ( "Convert2streamapi" ) public void stop ( ) { if ( debug ) { logger . debug ( ServiceBundleImpl . class . getName ( ) , "::stop()" ) ; } methodQueue . stop ( ) ; for ( Stoppable service : servicesToStop ) { service . stop ( ) ; } try { responseQueue . stop ( ) ; } catch ( Exception ex ) { logger . debug ( "" , ex ) ; } try { webResponseQueue . stop ( ) ; } catch ( Exception ex ) { logger . debug ( "" , ex ) ; } if ( systemManager != null ) systemManager . serviceShutDown ( ) ; }


public ServiceBundle startUpCallQueue() {
        methodQueue.startListener(new ReceiveQueueListener<MethodCall<Object>>() {

            long time;

            long lastTimeAutoFlush;

            /**
             * When we receive a method call, we call doCall.
             * @param item item
             */
            @Override
            public void receive(MethodCall<Object> item) {
                doCall(item); //Do call calls forwardEvent but does not flush. Only when the queue is empty do we flush.
            }

            /**
             * If the queue is empty, then go ahead, and flush to each client all incoming requests every 50 milliseconds.
             */
            @Override
            public void empty() {
                time = timer.now();
                if (time > (lastTimeAutoFlush + 50)) {

                    //noinspection Convert2streamapi
                    for (SendQueue<MethodCall<Object>> sendQueue : sendQueues) {
                        sendQueue.flushSends();
                    }
                    lastTimeAutoFlush = time;
                }
            }

        });

        return this;
    }


public String findServiceName(final String dnsServiceName) {
        String serviceName = dnsServiceNameToServiceName.get(dnsServiceName);
        serviceName = serviceName == null ? dnsServiceName : serviceName;

        if (debug) logger.debug("FindServiceName dnsServiceName={} serviceName={}", dnsServiceName, serviceName);

        return serviceName;
    }

Looks up a service name based on its dns service name. The service part of the SRV DNS Record.

@param dnsServiceName dnsServiceName
@return serviceName

Looks up a service name based on its dns service name . The service part of the SRV DNS Record .


public void loadServiceEndpointsByServiceName(final Callback<List<EndpointDefinition>> callback,
                                                  final String serviceName) {

        loadServiceEndpointsByDNSService(callback, findDnsServiceName(serviceName));
    }

public void loadServiceEndpointsByServiceName ( final Callback < List < EndpointDefinition > > callback , final String serviceName ) { loadServiceEndpointsByDNSService ( callback , findDnsServiceName ( serviceName ) ) ; }

Load the service nodes based on the internal service name.
DB, Ingester, RadarAggregator, etc.

@param callback    callback
@param serviceName serviceName

Load the service nodes based on the internal service name . DB Ingester RadarAggregator etc .


private EndpointDefinition convertSrvRecordToEndpointDefinition(final SrvRecord srvRecord) {
        return new EndpointDefinition(findServiceName(srvRecord.service()), srvRecord.target(),
                srvRecord.port());
    }

private EndpointDefinition convertSrvRecordToEndpointDefinition ( final SrvRecord srvRecord ) { return new EndpointDefinition ( findServiceName ( srvRecord . service ( ) ) , srvRecord . target ( ) , srvRecord . port ( ) ) ; }

Convert a single srvRecord into an EndpointDefinition.

@param srvRecord srvRecord
@return EndpointDefinition from srvRecord

Convert a single srvRecord into an EndpointDefinition .


protected CORSRequestType checkRequestType(final HttpRequestHolder request) {
        CORSRequestType requestType = CORSRequestType.INVALID_CORS;
        if (request == null) {
            throw new IllegalArgumentException(CorsSupport.CORS_NULL_REQUEST);
        }
        String originHeader = request.getHeaders().get(REQUEST_HEADER_ORIGIN);
        // Section 6.1.1 and Section 6.2.1
        if (originHeader != null) {
            if (originHeader.isEmpty()) {
                requestType = CORSRequestType.INVALID_CORS;
            } else if (!isValidOrigin(originHeader)) {
                requestType = CORSRequestType.INVALID_CORS;
            } else if (isLocalOrigin(request, originHeader)) {
                return CORSRequestType.NOT_CORS;
            } else {
                String method = request.getMethod();
                if (method != null) {
                    if ("OPTIONS".equals(method)) {
                        String accessControlRequestMethodHeader =
                                request.getHeaders().get(
                                        REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
                        if (accessControlRequestMethodHeader != null &&
                                !accessControlRequestMethodHeader.isEmpty()) {
                            requestType = CORSRequestType.PRE_FLIGHT;
                        } else if (accessControlRequestMethodHeader != null &&
                                accessControlRequestMethodHeader.isEmpty()) {
                            requestType = CORSRequestType.INVALID_CORS;
                        } else {
                            requestType = CORSRequestType.ACTUAL;
                        }
                    } else if ("GET".equals(method) || "HEAD".equals(method)) {
                        requestType = CORSRequestType.SIMPLE;
                    } else if ("POST".equals(method)) {
                        String mediaType = request.getContentType();
                        if (mediaType != null) {
//                                if (SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES
//                                        .contains(mediaType)) {
//                                    requestType = CORSRequestType.SIMPLE;
//                                } else {
//                                    requestType = CORSRequestType.ACTUAL;
//                                }

                            //TODO: Will QBit support non-simple?
                            requestType = CORSRequestType.SIMPLE;
                        }
                    } else {
                        requestType = CORSRequestType.ACTUAL;
                    }
                }
            }
        } else {
            requestType = CORSRequestType.NOT_CORS;
        }

        return requestType;
    }

//                                        .contains(mediaType)) {

//                                } else {

Determines the request type.

@param request request
@return CORs request type.


private void handleHttpRequest(final HttpServerRequest request) {

        if (debug) {
            setupMetrics(request);
            logger.debug("HttpServerVertx::handleHttpRequest::{}:{}", request.method(), request.uri());
        }

        switch (request.method().toString()) {

            case "PUT":
            case "POST":
            case "OPTIONS":
            case "TRACE":
            case "DELETE":
            case "CONNECT":
                handleRequestWithBody(request);
                break;

            case "HEAD":
            case "GET":
                handleRequestWithNoBody(request);
                break;

            default:
                throw new IllegalStateException("method not supported yet " + request.method());

        }

    }

Handle a vertx request by converting it into a QBit request.

@param request request

Handle a vertx request by converting it into a QBit request .


private boolean doHandleMethodCall(MethodCall<Object> methodCall,
                                       final ServiceMethodHandler serviceMethodHandler) {
        if (debug) {
            logger.debug("ServiceImpl::doHandleMethodCall() METHOD CALL" + methodCall);
        }
        if (callbackManager != null) {

            if (methodCall.hasCallback() && serviceMethodHandler.couldHaveCallback(methodCall.name())) {
                callbackManager.registerCallbacks(methodCall);
            }
        }
        //inputQueueListener.receive(methodCall);
        final boolean continueFlag[] = new boolean[1];
        methodCall = beforeMethodProcessing(methodCall, continueFlag);
        if (continueFlag[0]) {
            if (debug) logger.debug("ServiceImpl::doHandleMethodCall() before handling stopped processing");
            return false;
        }
        Response<Object> response = serviceMethodHandler.receiveMethodCall(methodCall);
        if (response != ServiceConstants.VOID) {

            if (!afterMethodCall.after(methodCall, response)) {
                return false;
            }
            //noinspection unchecked
            response = responseObjectTransformer.transform(response);

            if (!afterMethodCallAfterTransform.after(methodCall, response)) {
                return false;
            }

            if (debug) {
                if (response.body() instanceof Throwable) {

                    logger.error("Unable to handle call ", ((Throwable) response.body()));

                }
            }
            if (!responseSendQueue.send(response)) {
                logger.error("Unable to send response {} for method {} for object {}",
                        response,
                        methodCall.name(),
                        methodCall.objectName());
            }

        }

        return false;
    }

This method is where all of the action is.

@param methodCall           methodCall
@param serviceMethodHandler handler

This method is where all of the action is .


public static Consul consul(final String host, final int port) {
        try {
            return new Consul(new URL("http", host, port, "").toString());
        } catch (MalformedURLException e) {
            throw new ConsulException("Bad Consul URL", e);
        }
    }

public
static
Consul
consul
(
final
String
host
,
final
int
port
)
{
try
{
return
new
Consul
(
new
URL
(
"http"
,
host
,
port
,
""
)
.
toString
(
)
)
;
}
catch
(
MalformedURLException
e
)
{
throw
new
ConsulException
(
"Bad Consul URL"
,
e
)
;
}
}

Creates a new client given a host and a port.

@param host The Consul API hostname or IP.
@param port The Consul port.
@return A new client.

Creates a new client given a host and a port .


@Override
    public DnsClient get() {
        final URI uri = addressList.get(index);
        try {
            if (debug) logger.debug("DnsClient.get port {} host {}", uri.getPort(), uri.getHost());
            return vertx.createDnsClient(uri.getPort(), uri.getHost());
        } catch (Exception ex) {
            logger.error("DnsClient.get EXCEPTION ", ex);
            logger.error("DnsClient.get EXCEPTION port {} host {}", uri.getPort(), uri.getHost());
            return getIfErrors();
        }
    }


@Override
    public ReceiveQueue<T> receiveQueue() {
        if (debug) logger.debug("ReceiveQueue requested for {}", name);
        return new BasicReceiveQueue<>(queue, pollTimeWait, pollTimeTimeUnit, limit);
    }

@
Override
public
ReceiveQueue
<
T
>
receiveQueue
(
)
{
if
(
debug
)
logger
.
debug
(
"ReceiveQueue requested for {}"
,
name
)
;
return
new
BasicReceiveQueue
<>
(
queue
,
pollTimeWait
,
pollTimeTimeUnit
,
limit
)
;
}

This returns a new instance of ReceiveQueue every time you call it
so call it only once per thread.

@return received queue

This returns a new instance of ReceiveQueue every time you call it so call it only once per thread .


@Override
    public SendQueue<T> sendQueue() {
        if (debug) logger.debug("SendQueue requested for {}", name);
        return sendQueueSupplier.get();
    }

@
Override
public
SendQueue
<
T
>
sendQueue
(
)
{
if
(
debug
)
logger
.
debug
(
"SendQueue requested for {}"
,
name
)
;
return
sendQueueSupplier
.
get
(
)
;
}

This returns a new instance of SendQueue every time you call it
so call it only once per thread.

@return sendQueue.

This returns a new instance of SendQueue every time you call it so call it only once per thread .


public static <T> Callback<T> convertPromise(final Promise<T> promise) {
        return convertPromiseToCallback(promise, CallbackBuilder.callbackBuilder());
    }

public static < T > Callback < T > convertPromise ( final Promise < T > promise ) { return convertPromiseToCallback ( promise , CallbackBuilder . callbackBuilder ( ) ) ; }

Converts a Reakt promise into a QBit callback.

@param promise reakt promise
@param <T>     type of promise
@return new QBit callback that wraps promise.

Converts a Reakt promise into a QBit callback .


public static <T> Callback<T> convertPromise(final Reactor reactor, final Promise<T> promise) {
        return convertPromiseToCallback(promise, reactor.callbackBuilder());
    }

public static < T > Callback < T > convertPromise ( final Reactor reactor , final Promise < T > promise ) { return convertPromiseToCallback ( promise , reactor . callbackBuilder ( ) ) ; }

Converts a Reakt promise into a QBit callback.
Reactor is used to manage timeouts and ensure callback happens on same thread as caller.

@param reactor QBit reactor
@param promise reakt promise
@param <T>     type of promise
@return new QBit callback that wraps promise.

Converts a Reakt promise into a QBit callback . Reactor is used to manage timeouts and ensure callback happens on same thread as caller .


public <T> Callback<T> callback(final Consumer<Promise<T>> promiseConsumer) {
        Promise<T> promise = Promises.promise();
        promiseConsumer.accept(promise);
        return Reakt.convertPromise(promise);
    }

public < T > Callback < T > callback ( final Consumer < Promise < T > > promiseConsumer ) { Promise < T > promise = Promises . promise ( ) ; promiseConsumer . accept ( promise ) ; return Reakt . convertPromise ( promise ) ; }

Creates a QBit callback based on promise created.

@param promiseConsumer promise consumer
@param <T>             T
@return QBit callback

Creates a QBit callback based on promise created .


private void loadHealthyServices() {

        try {
            String serviceName = doneQueue.poll();

            while (serviceName != null) {

                final String serviceNameToFetch = serviceName;

                /* Don't load the service if it is already being loaded. */
                if (!serviceNamesBeingLoaded.contains(serviceNameToFetch)) {
                    serviceNamesBeingLoaded.add(serviceNameToFetch);
                    executorService.submit(() -> {
                     /*
                       Loading a service pool might take a while so
                       the actual load operation happens in its own thread.
                      */
                        doLoadHealthServices(serviceNameToFetch);
                    });
                }
                serviceName = doneQueue.poll();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

Iterate through the health service queue and load the services.

Iterate through the health service queue and load the services .


private void doFailOverHealthServicesLoad(final String serviceNameToFetch, Exception ex) {

        /* If there is a backup provider, load from there. */
        if (backupProvider != null) {

            if (debug) logger.debug("ServiceDiscoveryImpl::loadHealthyServices " +
                    "Error while loading healthy" +
                    " services for " + serviceNameToFetch, ex);

            final List<EndpointDefinition> healthyServices = backupProvider.loadServices(serviceNameToFetch);
            populateServiceMap(serviceNameToFetch, healthyServices);
            serviceNamesBeingLoaded.remove(serviceNameToFetch);

        } else {

            logger.error("ServiceDiscoveryImpl::loadHealthyServices " +
                    "Error while loading healthy" +
                    " services for " + serviceNameToFetch, ex);
        }

        Sys.sleep(10_000); //primary is down so slow it down so we don't flow the system with updates of service pools.

    }

If the primary load failed, we could have a backup provider registered.

@param serviceNameToFetch service pool to fetch
@param ex

If the primary load failed we could have a backup provider registered .


@Override
    public DnsClient get() {

        if (debug) logger.debug("DnsSingleClientSupplier.get()::host = {}, port = {}", host, port);
        return vertx.createDnsClient(port, host);
    }

Supply an instance of DnsClient.

@return DnsClient.


public void addOneShotAfterTask(final long fireAfter, final TimeUnit timeUnit, final Runnable task) {

        fireOnceAfterTasks.add(new FireOnceTask(task, timeUnit, fireAfter));
    }

public void addOneShotAfterTask ( final long fireAfter , final TimeUnit timeUnit , final Runnable task ) { fireOnceAfterTasks . add ( new FireOnceTask ( task , timeUnit , fireAfter ) ) ; }

Add a task that gets executed once.

@param fireAfter run task after time period
@param timeUnit  unit for fireAfter
@param task      task to perform


public void process() {

        /** Manages lists of coordinators, and callbacks which can come back async. */
        drainQueues();

        currentTime = timer.now();

        /* Check to see if callbacks completed or timed out. */
        monitorCallBacks();

        /* Check to see if coordinators completed or timed out. */
        monitorCallbackCoordinators();

        /* flush services. */
        collaboratingServices.forEach(ServiceProxyUtils::flushServiceProxy);

        processRepeatingTasks();
        processFireOnceTasks();
    }


public <T> AsyncFutureCallback<T> removeFuture(AsyncFutureCallback<T> asyncFutureCallback) {

        this.removeFutureQueue.offer(asyncFutureCallback);
        return asyncFutureCallback;
    }

public < T > AsyncFutureCallback < T > removeFuture ( AsyncFutureCallback < T > asyncFutureCallback ) { this . removeFutureQueue . offer ( asyncFutureCallback ) ; return asyncFutureCallback ; }

Remove a callback from the list of callbacks that we are managing.

@param asyncFutureCallback asyncFutureCallback
@param <T>                 T
@return the callback that we removed.

Remove a callback from the list of callbacks that we are managing .


public CallbackCoordinator coordinateWithTimeout(final CallbackCoordinator coordinator,
                                                     final long startTime,
                                                     final long timeoutDuration,
                                                     final TimeUnit timeUnit,
                                                     final Runnable timeOutHandler,
                                                     final Runnable finishedHandler) {

        final long timeoutDurationMS = timeUnit.toMillis(timeoutDuration);

        final long theStartTime = startTime == -1 ? currentTime : startTime;

        final CallbackCoordinator wrapper = new CallbackCoordinator() {

            AtomicBoolean done = new AtomicBoolean();

            @Override
            public boolean checkComplete() {
                if (done.get()) {
                    return true;
                }

                if (coordinator.checkComplete()) {
                    done.set(true);
                }

                return done.get();

            }

            public boolean timedOut(long now) {

                if (startTime() == -1 || timeOutDuration() == -1) {
                    return false;
                }
                if ((now - startTime()) > timeOutDuration()) {

                    if (!done.get()) {
                        timeOutHandler.run();
                        done.set(true);
                    }
                    return true;
                } else {
                    return false;
                }
            }

            @Override
            public long timeOutDuration() {
                return coordinator.timeOutDuration() == -1 ? timeoutDurationMS : coordinator.timeOutDuration();
            }

            @Override
            public long startTime() {
                return coordinator.startTime() == -1 ? theStartTime : coordinator.startTime();
            }

            public void finished() {
                if (checkComplete()) {
                    removeCoordinator(this);
                }
                if (finishedHandler != null) {
                    finishedHandler.run();
                }
                coordinator.finished();
            }

            public void cancel() {
                done.set(true);
                removeCoordinator(this);
                coordinator.cancel();
            }
        };

        this.coordinatorQueue.add(wrapper);
        return wrapper;
    }

public CallbackCoordinator coordinateWithTimeout ( final CallbackCoordinator coordinator , final long startTime , final long timeoutDuration , final TimeUnit timeUnit , final Runnable timeOutHandler , final Runnable finishedHandler ) { final long timeoutDurationMS = timeUnit . toMillis ( timeoutDuration ) ; final long theStartTime = startTime == - 1 ? currentTime : startTime ; final CallbackCoordinator wrapper = new CallbackCoordinator ( ) { AtomicBoolean done = new AtomicBoolean ( ) ; @ Override public boolean checkComplete ( ) { if ( done . get ( ) ) { return true ; } if ( coordinator . checkComplete ( ) ) { done . set ( true ) ; } return done . get ( ) ; } public boolean timedOut ( long now ) { if ( startTime ( ) == - 1 || timeOutDuration ( ) == - 1 ) { return false ; } if ( ( now - startTime ( ) ) > timeOutDuration ( ) ) { if ( ! done . get ( ) ) { timeOutHandler . run ( ) ; done . set ( true ) ; } return true ; } else { return false ; } } @ Override public long timeOutDuration ( ) { return coordinator . timeOutDuration ( ) == - 1 ? timeoutDurationMS : coordinator . timeOutDuration ( ) ; } @ Override public long startTime ( ) { return coordinator . startTime ( ) == - 1 ? theStartTime : coordinator . startTime ( ) ; } public void finished ( ) { if ( checkComplete ( ) ) { removeCoordinator ( this ) ; } if ( finishedHandler != null ) { finishedHandler . run ( ) ; } coordinator . finished ( ) ; } public void cancel ( ) { done . set ( true ) ; removeCoordinator ( this ) ; coordinator . cancel ( ) ; } } ; this . coordinatorQueue . add ( wrapper ) ; return wrapper ; }

Utility method to create a coordinator.

@param coordinator     coordinator
@param startTime       startTime
@param timeoutDuration timeoutDuration
@param timeUnit        timeUnit
@param timeOutHandler  timeOutHandler
@param finishedHandler finishedHandler
@return callback coordinator

Utility method to create a coordinator .


private void monitorCallBacks() {

        if (futureList.size() > 0) {

            final List<AsyncFutureCallback<?>> removeList = new ArrayList<>(futureList.size());
            long now = currentTime;
            for (AsyncFutureCallback<?> callback : futureList) {
                if (callback.isDone()) {
                    callback.run();
                    removeList.add(callback);
                } else {
                    if (callback.checkTimeOut(now)) {
                        removeList.add(callback);
                    }
                }
            }
            futureList.removeAll(removeList);
        }
    }

private void monitorCallBacks ( ) { if ( futureList . size ( ) > 0 ) { final List < AsyncFutureCallback < ? > > removeList = new ArrayList <> ( futureList . size ( ) ) ; long now = currentTime ; for ( AsyncFutureCallback < ? > callback : futureList ) { if ( callback . isDone ( ) ) { callback . run ( ) ; removeList . add ( callback ) ; } else { if ( callback . checkTimeOut ( now ) ) { removeList . add ( callback ) ; } } } futureList . removeAll ( removeList ) ; } }

Monitors timeouts. If the callback timed-out trigger it, and then remove callback from the list.

Monitors timeouts . If the callback timed - out trigger it and then remove callback from the list .


private void monitorCallbackCoordinators() {

        if (coordinatorList.size() > 0) {
            final List<CallbackCoordinator> removeList = new ArrayList<>(coordinatorList.size());

            for (CallbackCoordinator callable : coordinatorList) {
                if (callable.checkComplete()) {
                    callable.finished();
                    removeList.add(callable);
                } else if (callable.timedOut(currentTime)) {
                    removeList.add(callable);
                }
            }
            coordinatorList.removeAll(removeList);
        }

    }

private void monitorCallbackCoordinators ( ) { if ( coordinatorList . size ( ) > 0 ) { final List < CallbackCoordinator > removeList = new ArrayList <> ( coordinatorList . size ( ) ) ; for ( CallbackCoordinator callable : coordinatorList ) { if ( callable . checkComplete ( ) ) { callable . finished ( ) ; removeList . add ( callable ) ; } else if ( callable . timedOut ( currentTime ) ) { removeList . add ( callable ) ; } } coordinatorList . removeAll ( removeList ) ; } }

Monitors Callback Coordinators.
Trigger timeouts if needed and remove coordinators from list that timed out.

Monitors Callback Coordinators . Trigger timeouts if needed and remove coordinators from list that timed out .


public <T> Callback<T> wrapCallbackWithTimeout(
            final String operationDescription,
            final Callback<T> callback,
            final Logger logger,
            final TimeUnit timeUnit,
            final long timeoutDuration) {
        return callbackBuilder().setCallback(new Callback<T>() {
            @Override
            public void accept(T t) {
                if (logger.isDebugEnabled()) {
                    logger.debug("{} returned {}", operationDescription, t);
                }
                callback.resolve(t);
            }
        }).setOnError(error -> {
            logger.error(String.format("ERROR calling %s", operationDescription), error);
            callback.onError(error);

        }).setOnTimeout(() -> {
            logger.error("TIMEOUT calling {}", operationDescription);
            callback.onTimeout();
        }).setTimeoutTimeUnit(timeUnit).setTimeoutDuration(timeoutDuration)
                .build();
    }

public
<
T
>
Callback
<
T
>
wrapCallbackWithTimeout
(
final
String
operationDescription
,
final
Callback
<
T
>
callback
,
final
Logger
logger
,
final
TimeUnit
timeUnit
,
final
long
timeoutDuration
)
{
return
callbackBuilder
(
)
.
setCallback
(
new
Callback
<
T
>
(
)
{
@
Override
public
void
accept
(
T
t
)
{
if
(
logger
.
isDebugEnabled
(
)
)
{
logger
.
debug
(
"{} returned {}"
,
operationDescription
,
t
)
;
}
callback
.
resolve
(
t
)
;
}
}
)
.
setOnError
(
error
->
{
logger
.
error
(
String
.
format
(
"ERROR calling %s"
,
operationDescription
)
,
error
)
;
callback
.
onError
(
error
)
;
}
)
.
setOnTimeout
(
(
)
->
{
logger
.
error
(
"TIMEOUT calling {}"
,
operationDescription
)
;
callback
.
onTimeout
(
)
;
}
)
.
setTimeoutTimeUnit
(
timeUnit
)
.
setTimeoutDuration
(
timeoutDuration
)
.
build
(
)
;
}

Used for quickly delegating one callback to another.
This allows one liners so you don't have to create a builder for this common case.

@param operationDescription Describe the operation for logging
@param callback             callback to delegate error and timeouts too.
@param logger               logger to log errors and timeouts.
@param <T>                  Generic type
@param timeoutDuration      time out duration
@param timeUnit             Time Unit
@return wrapped callback that is tied to this reactor.

Used for quickly delegating one callback to another . This allows one liners so you don t have to create a builder for this common case .


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

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

Build the impl.

@return returns an instance of the impl.


public ProxyService buildProxy() {
        return getServiceBuilder().setServiceObject(build()).buildAndStart().createProxyWithAutoFlush(ProxyService.class,
                Duration.HUNDRED_MILLIS);
    }

public ProxyService buildProxy ( ) { return getServiceBuilder ( ) . setServiceObject ( build ( ) ) . buildAndStart ( ) . createProxyWithAutoFlush ( ProxyService . class , Duration . HUNDRED_MILLIS ) ; }

Builds a proxy queue service to the impl.

@return proxy queue service interface to impl.

Builds a proxy queue service to the impl .


public void handleWebSocketCall(final WebSocketMessage webSocketMessage) {

        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);
            }

        });

    }

public
void
handleWebSocketCall
(
final
WebSocketMessage
webSocketMessage
)
{
if
(
debug
)
logger
.
debug
(
"WebSocket message: "
+
webSocketMessage
)
;
WebSocketDelegate
webSocketDelegate
=
webSocketDelegateMap
.
get
(
webSocketMessage
.
getRemoteAddress
(
)
)
;
if
(
webSocketDelegate
==
)
{
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
)
;
}
}
)
;
}

All WebSocket calls come through here.

@param webSocketMessage websocket message


public void start() {
        server.setHttpRequestConsumer(proxyService::handleRequest);
        server.setHttpRequestsIdleConsumer(aVoid -> flushServiceProxy(proxyService));
        server.startServer();
    }

public void start ( ) { server . setHttpRequestConsumer ( proxyService :: handleRequest ) ; server . setHttpRequestsIdleConsumer ( aVoid -> flushServiceProxy ( proxyService ) ) ; server . startServer ( ) ; }


public void add(final EventListener<T> eventListener) {
        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;
        }
    }

public
void
add
(
final
EventListener
<
T
>
eventListener
)
{
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
;
}
}

Add an event listener to the channel
There can only be one consumer and many listeners.

@param eventListener eventListener

Add an event listener to the channel There can only be one consumer and many listeners .


public static ServiceDiscovery createDnsServiceDiscovery() {

        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();
    }

public static ServiceDiscovery createDnsServiceDiscovery ( ) { 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 ( ) ; }

Create service discovery that can talk DNS.
@return ServiceDiscovery

Create service discovery that can talk DNS .


@Override
    public <T> T fromJson(String json, Class<T> cls) {
        return parser.get().parse(cls, json);
    }

@ Override public < T > T fromJson ( String json , Class < T > cls ) { return parser . get ( ) . parse ( cls , json ) ; }

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

Convert from json string using Class as a suggestion for how to do the parse .


@Override
    public <T> List<T> fromJsonArray(String json, Class<T> componentClass) {
        return parser.get().parseList(componentClass, json);
    }

@ Override public < T > List < T > fromJsonArray ( String json , Class < T > componentClass ) { return parser . get ( ) . parseList ( componentClass , json ) ; }

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.

Converts from a json string using componentClass as a guide to a List .


@Override
    public String toJson(Object object) {
        return serializer.get().serialize(object).toString();
    }

@ Override public String toJson ( Object object ) { return serializer . get ( ) . serialize ( object ) . toString ( ) ; }

Converts from Object into JSON string.

@param object object to convert to JSON.
@return json string


@Override
    public <K, V> Map<K, V> fromJsonMap(String json, Class<K> componentClassKey, Class<V> componentClassValue) {
        Map map = (Map) parser.get().parse(json);
        final Mapper mapper = this.mapper.get();
        return extractMap(componentClassKey, componentClassValue, map, mapper);
    }

@ Override public < K , V > Map < K , V > fromJsonMap ( String json , Class < K > componentClassKey , Class < V > componentClassValue ) { Map map = ( Map ) parser . get ( ) . parse ( json ) ; final Mapper mapper = this . mapper . get ( ) ; return extractMap ( componentClassKey , componentClassValue , map , mapper ) ; }

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

Converts from a json string using componentClassKey and componentClassValue as a guide to a Map .


private <V> V convertToMap(ValueMap valueMap) {
        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;
    }

Helper method.
Converts a value map into a regular map of Java basic types.

@param valueMap valueMap
@param <V>      V
@return regular map

Helper method . Converts a value map into a regular map of Java basic types .


public boolean couldHaveCallback(final String name) {

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

        return has;
    }

public boolean couldHaveCallback ( final String name ) { final Boolean has = hasHandlerMap . get ( name ) ; if ( has == null ) { return true ; } return has ; }

False is unknown, true is no callbacks.

@param name name of method
@return false signifies maybe, true means never.


public <T> CallbackBuilder setCallback(final Class<T> returnType, final Callback<T> callback) {
        return withCallback(returnType, callback);
    }

public < T > CallbackBuilder setCallback ( final Class < T > returnType , final Callback < T > callback ) { return withCallback ( returnType , callback ) ; }

Builder method to add a callback handler.

@param returnType returnType
@param callback   callback
@param <T>        T
@return this

Builder method to add a callback handler .


public <T> CallbackBuilder wrap(final Callback<T> callback) {

        this.withErrorHandler(callback::onError);

        this.withTimeoutHandler(callback::onTimeout);

        this.withCallback(callback);

        return this;
    }

public < T > CallbackBuilder wrap ( final Callback < T > callback ) { this . withErrorHandler ( callback :: onError ) ; this . withTimeoutHandler ( callback :: onTimeout ) ; this . withCallback ( callback ) ; return this ; }

Builder method to wrap and delegate, timeout and error handling and callback itself.

@param callback callback
@param <T>      T
@return this

Builder method to wrap and delegate timeout and error handling and callback itself .


public <T> CallbackBuilder withListCallback(final Class<T> componentClass,
                                                final Callback<List<T>> callback) {
        this.callback = callback;
        return this;
    }

public < T > CallbackBuilder withListCallback ( final Class < T > componentClass , final Callback < List < T > > callback ) { this . callback = callback ; return this ; }

Builder method to set callback handler that takes a list

@param componentClass componentClass
@param callback       callback
@param <T>            T
@return this


public <T> CallbackBuilder withSetCallback(final Class<T> componentClass,
                                               final Callback<Set<T>> callback) {
        this.callback = callback;
        return this;
    }

public < T > CallbackBuilder withSetCallback ( final Class < T > componentClass , final Callback < Set < T > > callback ) { this . callback = callback ; return this ; }

Builder method to set callback handler that takes a set

@param componentClass componentClass
@param callback       callback
@param <T>            T
@return this


public <T> CallbackBuilder withCollectionCallback(final Class<T> componentClass,
                                                      final Callback<Collection<T>> callback) {
        this.callback = callback;
        return this;
    }

public < T > CallbackBuilder withCollectionCallback ( final Class < T > componentClass , final Callback < Collection < T > > callback ) { this . callback = callback ; return this ; }

Builder method to set callback handler that takes a collection

@param componentClass componentClass
@param callback       callback
@param <T>            T
@return this


public <K, V> CallbackBuilder withMapCallback(final Class<K> keyClass,
                                                  final Class<V> valueClass,
                                                  final Callback<Map<K, V>> callback) {
        this.callback = callback;
        return this;
    }

public < K , V > CallbackBuilder withMapCallback ( final Class < K > keyClass , final Class < V > valueClass , final Callback < Map < K , V > > callback ) { this . callback = callback ; return this ; }

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 <T> CallbackBuilder withOptionalCallback(final Class<T> cls, final Callback<Optional<T>> callback) {
        this.callback = callback;
        return this;
    }

public < T > CallbackBuilder withOptionalCallback ( final Class < T > cls , final Callback < Optional < T > > callback ) { this . callback = callback ; return this ; }

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 HttpResponseBuilder addHeader(final String name, final String value) {
        getHeaders().put(name, value);
        return this;
    }

public HttpResponseBuilder addHeader ( final String name , final String value ) { getHeaders ( ) . put ( name , value ) ; return this ; }

Add a header

@param name  name
@param value value
@return HttpResponseBuilder


public boolean isServiceRegistered(final String serviceId) {
        Map<String, Service> serviceIdToService = getServices();
        return serviceIdToService.containsKey(serviceId);
    }

public boolean isServiceRegistered ( final String serviceId ) { Map < String , Service > serviceIdToService = getServices ( ) ; return serviceIdToService . containsKey ( serviceId ) ; }

Checks to see if a service is registered with the local agent..

@param serviceId service id
@return true if a particular service is registered with
the local Consul agent, otherwise false.

Checks to see if a service is registered with the local agent ..


public void pingAgent() {

        HTTP.Response response = HTTP.getResponse(createURI("/self").toString());

        if (response.status() != 200) {
            die("Error pinging Consul", response.payloadAsString());
        }
    }

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


public void register(final Registration registration) {

        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());
        }
    }

public
void
register
(
final
Registration
registration
)
{
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
(
)
)
;
}
}

Register a service with Consul.

@param registration The registration payload.


public void deregister(final String serviceId) {

        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());
        }

    }

Remove registration of a particular service.

@param serviceId the service id that you want to remove.

Remove registration of a particular service .


public void deregisterCheck(String checkId) {

        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());
        }

    }

De-registers a Health Check with the Agent

@param checkId the id of the Check to deregister

De - registers a Health Check with the Agent


public void check(String checkId, Status status, String note) {

        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());
        }

    }

public
void
check
(
String
checkId
,
Status
status
,
String
note
)
{
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
(
)
)
;
}
}

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 pass(String checkId, @SuppressWarnings("SameParameterValue") String note) throws NotRegisteredException {
        checkTtl(checkId, Status.PASS, note);
    }

public void pass ( String checkId , @ SuppressWarnings ( "SameParameterValue" ) String note ) throws NotRegisteredException { checkTtl ( checkId , Status . PASS , note ) ; }

Sets a TTL check to "passing" state with a note

@param checkId check id
@param note    note

Sets a TTL check to passing state with a note


public void warn(String checkId, String note) throws NotRegisteredException {
        checkTtl(checkId, Status.WARN, note);
    }

public void warn ( String checkId , String note ) throws NotRegisteredException { checkTtl ( checkId , Status . WARN , note ) ; }

Sets a TTL check to "warning" state with a note.

@param checkId check id
@param note    note

Sets a TTL check to warning state with a note .


public void stop() {
        flush();
        if (httpServerProxy != null) {
            try {
                httpServerProxy.stop();
            } catch (Exception ex) {

                logger.warn("Problem closing httpServerProxy ", ex);
            }
        }
    }

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

Stop client. Stops processing call backs.

Stop client . Stops processing call backs .


private void handleAsyncCallback(final Response<Object> response, final Callback<Object> handler) {
        if (response.wasErrors()) {
            handler.onError(new Exception(response.body().toString()));
        } else {
            handler.accept(response.body());
        }
    }

private void handleAsyncCallback ( final Response < Object > response , final Callback < Object > handler ) { if ( response . wasErrors ( ) ) { handler . onError ( new Exception ( response . body ( ) . toString ( ) ) ) ; } else { handler . accept ( response . body ( ) ) ; } }


private void send(final String serviceName, final String message, final Consumer<Exception> exceptionConsumer) {

        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;
        }
    }

private void send ( final String serviceName , final String message , final Consumer < Exception > exceptionConsumer ) { 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 ; } }

Sends a message over websocket.

@param message     message to sendText over WebSocket
@param serviceName message to sendText over WebSocket


public <T> T createProxy(final Class<T> serviceInterface, final String serviceName) {

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

public < T > T createProxy ( final Class < T > serviceInterface , final String serviceName ) { return createProxy ( serviceInterface , serviceName , Str . join ( ' ' , uri , serviceName , UUID . randomUUID ( ) . toString ( ) ) ) ; }

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.

Creates a new client proxy given a client interface .


private ReceiveQueueListener<Response<Object>> createResponseQueueListener() {
        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();
            }
        };
    }

Creates the queue listener for method call responses from the client bundle.

@return the response queue listener to handle the responses to method calls.

Creates the queue listener for method call responses from the client bundle .


@Override
    public ReceiveQueue<T> receiveQueue() {

        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();
            }
        };
    }

@ Override public ReceiveQueue < T > receiveQueue ( ) { 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 ( ) ; } } ; }

Create a wrapper ReceiveQueue that does decoding on the fly.

@return wrapped ReceiveQueue

Create a wrapper ReceiveQueue that does decoding on the fly .


private SendQueue<T> createJsonSendQueue(final SendQueue<String> sendQueue) {

        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();
            }
        };
    }

private SendQueue < T > createJsonSendQueue ( final SendQueue < String > sendQueue ) { 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 ( ) ; } } ; }

Helper method to create SendQueue wrappers that do JSON encoding.

@param sendQueue sendQueue
@return sendQueue decorated with JSON encoding.

Helper method to create SendQueue wrappers that do JSON encoding .


@Override
    public void startListener(final ReceiveQueueListener<T> listener) {
        queue.startListener(item -> listener.receive(fromJsonFunction.apply(item)));
    }

@ Override public void startListener ( final ReceiveQueueListener < T > listener ) { queue . startListener ( item -> listener . receive ( fromJsonFunction . apply ( item ) ) ) ; }

Start a listener.

@param listener listener


public ServiceQueue build() {

        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;
    }

public
ServiceQueue
build
(
)
{
if
(
debug
)
logger
.
debug
(
"Building a service"
)
;
ServiceQueueSizer
serviceQueueSizer
=
;
if
(
statsConfig
!=
)
{
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
!=
)
{
serviceQueueSizer
.
setServiceQueue
(
serviceQueue
)
;
}
if
(
qBitSystemManager
!=
)
{
qBitSystemManager
.
registerService
(
serviceQueue
)
;
}
return
serviceQueue
;
}

Builds a service.

@return new service queue


@Override
    public void checkInOk(final String name) {

        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)));

    }

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


@Override
    public void failWithError(final String name, final Throwable error) {
        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)));

    }

@
Override
public
void
failWithError
(
final
String
name
,
final
Throwable
error
)
{
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
)
)
)
;
}

Fail the node for the service with a specific status.

@param name  name
@param error error

Fail the node for the service with a specific status .


public ManagedServiceBuilder enableLoggingMappedDiagnosticContext(final Set<String> requestHeaders) {
        this.enableRequestChain = true;
        this.enableLoggingMappedDiagnosticContext = true;
        this.requestHeadersToTrackForMappedDiagnosticContext = Collections.unmodifiableSet(requestHeaders);
        return this;
    }

Enable the logging diagnostic context

@param requestHeaders request headers to track in the MDC.
@return this


public ManagedServiceBuilder enableConsulServiceDiscovery(final String dataCenter) {
        final ConsulServiceDiscoveryBuilder consulServiceDiscoveryBuilder = consulServiceDiscoveryBuilder();
        consulServiceDiscoveryBuilder.setDatacenter(dataCenter);
        serviceDiscoverySupplier = consulServiceDiscoveryBuilder::build;
        return this;
    }

public ManagedServiceBuilder enableConsulServiceDiscovery ( final String dataCenter ) { final ConsulServiceDiscoveryBuilder consulServiceDiscoveryBuilder = consulServiceDiscoveryBuilder ( ) ; consulServiceDiscoveryBuilder . setDatacenter ( dataCenter ) ; serviceDiscoverySupplier = consulServiceDiscoveryBuilder :: build ; return this ; }

Enable consul discovery

@param dataCenter name of datacenter we are connecting to.
@return fluent, this


public AdminBuilder getAdminBuilder() {
        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;
    }

public AdminBuilder getAdminBuilder ( ) { 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 ; }

Get the Admin builder.

@return admin builder.


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

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

Get context meta builder.

@return context meta builder


public ManagedServiceBuilder addEndpointServiceWithServiceManagmentBundle(
            final Object endpointService, final ServiceManagementBundle serviceManagementBundle) {

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

Add an endpoint with a managment bundle

@param endpointService         endpoint service
@param serviceManagementBundle management bundle
@return this, fluent


public ManagedServiceBuilder addEndpointServiceWithAliasAndServiceManagmentBundle(
            final String alias,
            final Object endpointService, final ServiceManagementBundle serviceManagementBundle) {

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

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 addEndpointService(final Object endpointService) {
        getContextMetaBuilder().addService(endpointService.getClass());
        getEndpointServices().add(endpointService);
        return this;
    }

public ManagedServiceBuilder addEndpointService ( final Object endpointService ) { getContextMetaBuilder ( ) . addService ( endpointService . getClass ( ) ) ; getEndpointServices ( ) . add ( endpointService ) ; return this ; }

Add an endpoint service

@param endpointService endpoint service
@return this, fluent


public ManagedServiceBuilder addEndpointService(final String alias, final Object endpointService) {
        getContextMetaBuilder().addService(alias, endpointService.getClass());
        getEndpointServiceMapWithAlias().put(alias, endpointService);
        return this;
    }

public ManagedServiceBuilder addEndpointService ( final String alias , final Object endpointService ) { getContextMetaBuilder ( ) . addService ( alias , endpointService . getClass ( ) ) ; getEndpointServiceMapWithAlias ( ) . put ( alias , endpointService ) ; return this ; }

Add endpoint service with alias

@param alias           alias
@param endpointService endpoint service
@return this, fluent


public ServiceEndpointServer getServiceEndpointServer() {

        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;

    }

Get the ServiceEndpointServer constructed with all of the service endpionts that
you registered

@return new ServiceEndpointServer.


private Interceptors configureInterceptors() {
        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;
    }

Configure a list of common interceptors.

@return interceptors.

Configure a list of common interceptors .


public boolean destroy(final String sessionId, final Session session, final String datacenter) {

        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;
    }

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

Destroy the session.
@param sessionId id of session
@param session session
@param datacenter datacenter
@return true if success


@Override
    public List<EndpointDefinition> loadServices(final String serviceName) {

        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();
        }

    }

Load the services.

@param serviceName serviceName
@return list of EndpointDefinition


private void delete(String key, Map<String, String> params) {

        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());
        }
    }

private
void
delete
(
String
key
,
Map
<
String
,
String
>
params
)
{
final
URI
uri
=
createURI
(
"/"
+
key
)
;
final
HttpRequestBuilder
httpRequestBuilder
=
RequestUtils
.
getHttpRequestBuilder
(
,
,
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
(
)
)
;
}
}

Deletes a specified key.

@param key    The key to delete.
@param params Map of parameters, e.g. recurse.


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

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

Main entry point.

@param request request to handle


public void process() {

        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);
        });

    }

public
void
process
(
)
{
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
=
;
}
if
(
item
!=
)
{
sendToEventManager
(
item
)
;
}
}
while
(
item
!=
)
;
}
)
;
}

Process. This can be called periodically and it will check to see if there are messages on the queue.

Process . This can be called periodically and it will check to see if there are messages on the queue .


private void sendToEventManager(T item) {
        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();
        }
    }

Send the queue item to the event.

@param item item


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

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

Start listener. Once this is called messages can come in on a foreign thread.

Start listener . Once this is called messages can come in on a foreign thread .


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

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

Grab the current http request.

@return Optional http request.