@Override
 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
   if (cause instanceof IOException) {
     if (LOGGER.isDebugEnabled()) {
       LOGGER.debug(
           logIdent(ctx, endpoint) + "Connection reset by peer: " + cause.getMessage(), cause);
     } else {
       LOGGER.info(logIdent(ctx, endpoint) + "Connection reset by peer: " + cause.getMessage());
     }
     handleOutstandingOperations(ctx);
   } else if (cause instanceof DecoderException
       && cause.getCause() instanceof SSLHandshakeException) {
     if (!connectFuture.isDone()) {
       connectFuture.setFailure(cause.getCause());
     } else {
       // This should not be possible, since handshake is done before connecting. But just in case,
       // we
       // can trap and log an error that might slip through for one reason or another.
       LOGGER.warn(
           logIdent(ctx, endpoint)
               + "Caught SSL exception after being connected: "
               + cause.getMessage(),
           cause);
     }
   } else {
     LOGGER.warn(
         logIdent(ctx, endpoint) + "Caught unknown exception: " + cause.getMessage(), cause);
     ctx.fireExceptionCaught(cause);
   }
 }
  @Override
  protected void decode(ChannelHandlerContext ctx, RESPONSE msg, List<Object> out)
      throws Exception {
    if (currentDecodingState == DecodingState.INITIAL) {
      currentRequest = sentRequestQueue.poll();
      currentDecodingState = DecodingState.STARTED;
      if (currentRequest != null) {
        Long st = sentRequestTimings.poll();
        if (st != null) {
          currentOpTime = System.nanoTime() - st;
        } else {
          currentOpTime = -1;
        }
      }

      if (traceEnabled) {
        LOGGER.trace("{}Started decoding of {}", logIdent(ctx, endpoint), currentRequest);
      }
    }

    try {
      CouchbaseResponse response = decodeResponse(ctx, msg);
      if (response != null) {
        publishResponse(response, currentRequest.observable());

        if (currentDecodingState == DecodingState.FINISHED) {
          if (currentRequest != null
              && currentOpTime >= 0
              && env() != null
              && env().networkLatencyMetricsCollector().isEnabled()) {
            NetworkLatencyMetricsIdentifier identifier =
                new NetworkLatencyMetricsIdentifier(
                    remoteHostname,
                    serviceType().toString(),
                    currentRequest.getClass().getSimpleName(),
                    response.status().toString());
            env().networkLatencyMetricsCollector().record(identifier, currentOpTime);
          }
        }
      }
    } catch (CouchbaseException e) {
      currentRequest.observable().onError(e);
    } catch (Exception e) {
      currentRequest.observable().onError(new CouchbaseException(e));
    }

    if (currentDecodingState == DecodingState.FINISHED) {
      if (traceEnabled) {
        LOGGER.trace("{}Finished decoding of {}", logIdent(ctx, endpoint), currentRequest);
      }
      currentRequest = null;
      currentDecodingState = DecodingState.INITIAL;
    }
  }
 /**
  * Override to customize the behavior when a keep alive has been responded to.
  *
  * <p>The default behavior is to log the event and the response status at trace level.
  *
  * @param ctx the channel context.
  * @param keepAliveResponse the keep alive request that was sent when keep alive was triggered
  */
 protected void onKeepAliveResponse(
     ChannelHandlerContext ctx, CouchbaseResponse keepAliveResponse) {
   if (traceEnabled) {
     LOGGER.trace(
         logIdent(ctx, endpoint) + "keepAlive was answered, status " + keepAliveResponse.status());
   }
 }
 public void run(Statement statement) {
   try {
     QueryResult result = bucket.query(statement);
     printout(result, false);
   } catch (Exception e) {
     LOGGER.error("Error while issuing statement " + demoName(), e);
   }
 }
 // issue a Query
 public void run(Query q, boolean shouldPause) {
   try {
     QueryResult result = bucket.query(q);
     printout(result, shouldPause);
   } catch (Exception e) {
     LOGGER.error("Error while issuing " + demoName(), e);
   }
 }
 private void pause(boolean shouldPause) {
   try {
     if (shouldPause) {
       System.in.read();
     }
   } catch (IOException e) {
     LOGGER.error("pause error", e);
   }
 }
 /**
  * Creates a new {@link AbstractGenericHandler} with a custom queue.
  *
  * @param endpoint the endpoint reference.
  * @param responseBuffer the response buffer.
  * @param queue the queue.
  */
 protected AbstractGenericHandler(
     final AbstractEndpoint endpoint,
     final EventSink<ResponseEvent> responseBuffer,
     final Queue<REQUEST> queue,
     final boolean isTransient) {
   this.endpoint = endpoint;
   this.responseBuffer = responseBuffer;
   this.sentRequestQueue = queue;
   this.currentDecodingState = DecodingState.INITIAL;
   this.isTransient = isTransient;
   this.traceEnabled = LOGGER.isTraceEnabled();
   this.sentRequestTimings = new ArrayDeque<Long>();
 }
  /**
   * Cancells any outstanding operations which are currently on the wire.
   *
   * @param ctx the handler context.
   */
  private void handleOutstandingOperations(final ChannelHandlerContext ctx) {
    if (sentRequestQueue.isEmpty()) {
      LOGGER.trace(logIdent(ctx, endpoint) + "Not cancelling operations - sent queue is empty.");
      return;
    }

    LOGGER.debug(
        logIdent(ctx, endpoint)
            + "Cancelling "
            + sentRequestQueue.size()
            + " outstanding requests.");
    while (!sentRequestQueue.isEmpty()) {
      REQUEST req = sentRequestQueue.poll();
      try {
        sideEffectRequestToCancel(req);
        req.observable().onError(new RequestCancelledException("Request cancelled in-flight."));
      } catch (Exception ex) {
        LOGGER.info("Exception thrown while cancelling outstanding operation: " + req, ex);
      }
    }

    sentRequestTimings.clear();
  }
 /**
  * Override to customize the behavior when a keep alive has been triggered and a keep alive
  * request sent.
  *
  * <p>The default behavior is to log the event at debug level.
  *
  * @param ctx the channel context.
  * @param keepAliveRequest the keep alive request that was sent when keep alive was triggered
  */
 protected void onKeepAliveFired(ChannelHandlerContext ctx, CouchbaseRequest keepAliveRequest) {
   if (LOGGER.isDebugEnabled()) {
     LOGGER.debug(logIdent(ctx, endpoint) + "KeepAlive fired");
   }
 }
 @Override
 public void channelActive(ChannelHandlerContext ctx) throws Exception {
   LOGGER.debug(logIdent(ctx, endpoint) + "Channel Active.");
   remoteHostname = ctx.channel().remoteAddress().toString();
   ctx.fireChannelActive();
 }
 @Override
 public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
   LOGGER.debug(logIdent(ctx, endpoint) + "Channel Inactive.");
   endpoint.notifyChannelInactive();
   ctx.fireChannelInactive();
 }