Encodes a {@link NoopRequest} into its lower level representation.

@param ctx the {@link ChannelHandlerContext} to use for allocation and others.
@param msg the incoming message.
@return a ready {@link BinaryMemcacheRequest}.
175064
private static BinaryMemcacheRequest handleNoopRequest(final ChannelHandlerContext ctx, final NoopRequest msg) {
        BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest();
        request.setOpcode(OP_NOOP);
        return request;
    }
217765
@Override
    public void channelHandlerContext(ChannelHandlerContext ctx) throws Http2Exception {
        this.ctx = checkNotNull(ctx, "ctx");

        // Writing the pending bytes will not check writability change and instead a writability change notification
        // to be provided by an explicit call.
        channelWritabilityChanged();

        // Don't worry about cleaning up queued frames here if ctx is null. It is expected that all streams will be
        // closed and the queue cleanup will occur when the stream state transitions occur.

        // If any frames have been queued up, we should send them now that we have a channel context.
        if (isChannelWritable()) {
            writePendingBytes();
        }
    }
976989
public static ByteBuf toByteBuf(ChannelHandlerContext ctx, Throwable cause) {
        if (cause == null || cause.getMessage() == null) {
            return Unpooled.EMPTY_BUFFER;
        }

        return ByteBufUtil.writeUtf8(ctx.alloc(), cause.getMessage());
    }
1297386
public BaseMessage sendMessageRequest(BaseMessage messageOut)
    {
        TrxMessageHeader trxMessageHeader = (TrxMessageHeader)messageOut.getMessageHeader();
        
        BaseMessage messageReply = null;
        String strMessageCode = (String)trxMessageHeader.get(LocalMessageTransport.LOCAL_PROCESSOR);
        if (trxMessageHeader.getMessageInfoMap() != null)
        {
            trxMessageHeader.getMessageInfoMap().remove(TrxMessageHeader.MESSAGE_PROCESSOR_CLASS);
            trxMessageHeader.getMessageInfoMap().remove(TrxMessageHeader.BASE_PACKAGE);
        }
        MessageProcessInfoModel recMessageProcessInfo = (MessageProcessInfoModel)this.getRecord(MessageProcessInfoModel.MESSAGE_PROCESS_INFO_FILE);
        if (recMessageProcessInfo == null)
            recMessageProcessInfo = (MessageProcessInfoModel)Record.makeRecordFromClassName(MessageProcessInfoModel.THICK_CLASS, this);
        messageOut.setMessageHeader(null);  // Since I am basically change this from out to in
        recMessageProcessInfo.setupMessageHeaderFromCode(messageOut.getMessage(), strMessageCode, null);
        recMessageProcessInfo.free();
        String strDefaultProcessorClass = BaseMessageInProcessor.class.getName();
        BaseExternalMessageProcessor messageInProcessor = (BaseExternalMessageProcessor)BaseMessageProcessor.getMessageProcessor(this.getTask(), (BaseMessage)messageOut.getMessage(), strDefaultProcessorClass);
        if (messageInProcessor != null)
        {   // Always
                // Note: Since recProduct is already read you may be able to speed things up by passing recProduct to this process..
            messageReply = messageInProcessor.processMessage((BaseMessage)messageOut.getMessage());
            messageInProcessor.free();
        }
        messageOut.setMessageHeader(trxMessageHeader);  // Restore this to the original message
        // Note messageReply is an internal message, ready to use updating the record
        ExternalMessage externalTrxMessage = this.createExternalMessage(messageReply, null);
        if (externalTrxMessage != null)
            externalTrxMessage.convertInternalToExternal(this);    // Convert my standard message to the OTA EC message
        return messageReply;
    }
881716
private void sendPingFrame(ChannelHandlerContext ctx, SendPingCommand msg,
      ChannelPromise promise) {
    // Don't check lifecycleManager.getShutdownStatus() since we want to allow pings after shutdown
    // but before termination. After termination, messages will no longer arrive because the
    // pipeline clears all handlers on channel close.

    PingCallback callback = msg.callback();
    Executor executor = msg.executor();
    // we only allow one outstanding ping at a time, so just add the callback to
    // any outstanding operation
    if (ping != null) {
      promise.setSuccess();
      ping.addCallback(callback, executor);
      return;
    }

    // Use a new promise to prevent calling the callback twice on write failure: here and in
    // NettyClientTransport.ping(). It may appear strange, but it will behave the same as if
    // ping != null above.
    promise.setSuccess();
    promise = ctx().newPromise();
    // set outstanding operation
    long data = USER_PING_PAYLOAD;
    Stopwatch stopwatch = stopwatchFactory.get();
    stopwatch.start();
    ping = new Http2Ping(data, stopwatch);
    ping.addCallback(callback, executor);
    // and then write the ping
    encoder().writePing(ctx, false, USER_PING_PAYLOAD, promise);
    ctx.flush();
    final Http2Ping finalPing = ping;
    promise.addListener(new ChannelFutureListener() {
      @Override
      public void operationComplete(ChannelFuture future) throws Exception {
        if (future.isSuccess()) {
          transportTracer.reportKeepAliveSent();
        } else {
          Throwable cause = future.cause();
          if (cause instanceof ClosedChannelException) {
            cause = lifecycleManager.getShutdownThrowable();
            if (cause == null) {
              cause = Status.UNKNOWN.withDescription("Ping failed but for unknown reason.")
                  .withCause(future.cause()).asException();
            }
          }
          finalPing.failed(cause);
          if (ping == finalPing) {
            ping = null;
          }
        }
      }
    });
  }
334076
@Override
  @SuppressWarnings("FutureReturnValueIgnored")
  public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
    if (failCause != null) {
      promise.setFailure(failCause);
      ReferenceCountUtil.release(msg);
    } else {
      bufferedWrites.add(new ChannelWrite(msg, promise));
    }
  }
571788
@Override
  protected void channelRead0(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception {
    if (SaslListMechsResponse.is(msg)) {
      handleListMechsResponse(ctx, msg);
    } else if (SaslAuthResponse.is(msg)) {
      handleAuthResponse(ctx, msg);
    } else if (SaslStepResponse.is(msg)) {
      checkIsAuthed(ctx, MessageUtil.getResponseStatus(msg));
    } else {
      throw new IllegalStateException("Received unexpected SASL response! " + MessageUtil.humanize(msg));
    }
  }
384416
protected List<TaskMessage> decode(ChannelHandlerContext ctx, Channel channel,
      ChannelBuffer buf) {
    this.dataInput.setChannelBuffer(buf);

    final int SESSION_LENGTH = 4; //int
    final int SOURCE_TASK_LENGTH = 8; //long
    final int TARGET_TASK_LENGTH = 8; //long
    final int MESSAGE_LENGTH = 4; //int
    final int HEADER_LENGTH = SESSION_LENGTH + SOURCE_TASK_LENGTH + TARGET_TASK_LENGTH + MESSAGE_LENGTH;

    // Make sure that we have received at least a short message
    long available = buf.readableBytes();
    if (available < HEADER_LENGTH) {
      //need more data
      return null;
    }

    List<TaskMessage> taskMessageList = new ArrayList<TaskMessage>();

    // Use while loop, try to decode as more messages as possible in single call
    while (available >= HEADER_LENGTH) {

      // Mark the current buffer position before reading task/len field
      // because the whole frame might not be in the buffer yet.
      // We will reset the buffer position to the marked position if
      // there's not enough bytes in the buffer.
      buf.markReaderIndex();

      int sessionId = buf.readInt();
      long targetTask = buf.readLong();
      long sourceTask = buf.readLong();
      // Read the length field.
      int length = buf.readInt();

      available -= HEADER_LENGTH;

      if (length <= 0) {
        taskMessageList.add(new TaskMessage(sessionId, targetTask, sourceTask, null));
        break;
      }

      // Make sure if there's enough bytes in the buffer.
      if (available < length) {
        // The whole bytes were not received yet - return null.
        buf.resetReaderIndex();
        break;
      }
      available -= length;

      // There's enough bytes in the buffer. Read it.
      Object message = serializer.deserialize(dataInput, length);

      // Successfully decoded a frame.
      // Return a TaskMessage object
      taskMessageList.add(new TaskMessage(sessionId, targetTask, sourceTask, message));
    }

    return taskMessageList.size() == 0 ? null : taskMessageList;
  }
824541
private void handleAuthResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
        if (saslClient.isComplete()) {
            checkIsAuthed(msg);
            return;
        }

        byte[] response = new byte[msg.content().readableBytes()];
        msg.content().readBytes(response);
        byte[] evaluatedBytes = saslClient.evaluateChallenge(response);

        if (evaluatedBytes != null) {
            ByteBuf content;

            // This is needed against older server versions where the protocol does not
            // align on cram and plain, the else block is used for all the newer cram-sha*
            // mechanisms.
            //
            // Note that most likely this is only executed in the CRAM-MD5 case only, but
            // just to play it safe keep it for both mechanisms.
            if (selectedMechanism.equals("CRAM-MD5") || selectedMechanism.equals("PLAIN")) {
                String[] evaluated = new String(evaluatedBytes).split(" ");
                content = Unpooled.copiedBuffer(username + "\0" + evaluated[1], CharsetUtil.UTF_8);
            } else {
                content = Unpooled.wrappedBuffer(evaluatedBytes);
            }

            FullBinaryMemcacheRequest stepRequest = new DefaultFullBinaryMemcacheRequest(
                selectedMechanism.getBytes(CharsetUtil.UTF_8),
                Unpooled.EMPTY_BUFFER,
                content
            );
            stepRequest
                .setOpcode(SASL_STEP_OPCODE)
                .setKeyLength((short) selectedMechanism.length())
                .setTotalBodyLength(content.readableBytes() + selectedMechanism.length());

            ChannelFuture future = ctx.writeAndFlush(stepRequest);
            future.addListener(new GenericFutureListener<Future<Void>>() {
                @Override
                public void operationComplete(Future<Void> future) throws Exception {
                    if (!future.isSuccess()) {
                        LOGGER.warn("Error during SASL Auth negotiation phase.", future);
                    }
                }
            });
        } else {
            throw new AuthenticationException("SASL Challenge evaluation returned null.");
        }
    }
543324
private void sendNotModified(ChannelHandlerContext ctx) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED);
        setDateHeader(response);

        this.sendAndCleanupConnection(ctx, response);
    }
777984
private Message getMessageFromProxy(Message msg) {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "getMessageFromProxy", msg);

        try {
            if (msg instanceof Proxy) {
                //check whether proxy is type of our InvocationHanlder.
                InvocationHandler handler = Proxy.getInvocationHandler(msg);

                //deal only with our handlers.. other Proxy handlers.. leave as it is..
                if (handler instanceof MessageProxyInvocationHandler) {
                    msg = ((MessageProxyInvocationHandler) handler).getMessage();

                }
            }

        } catch (Exception e) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                SibTr.debug(this, tc, "Exception in getMessageFromProxy .. returning msg as it is", e);

        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "getMessageFromProxy", msg);

        return msg;

    }
1300235
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception {
        // Make sure that we have received at least a short
        long available = buf.readableBytes();
        // Length of control message is 10.
        // Minimum length of a task message is 6(short taskId, int length).
        if (available < 6) {
            // need more data
            return null;
        }

        long startTime = 0L;
        if (isServer && enableNettyMetrics) {
            startTime = msgDecodeTimer.getTime();
        }
        try {
            // Mark the current buffer position before reading task/len field
            // because the whole frame might not be in the buffer yet.
            // We will reset the buffer position to the marked position if
            // there's not enough bytes in the buffer.
            buf.markReaderIndex();

            // read the short field
            short code = buf.readShort();
            available -= 2;

            // case 1: Control message
            ControlMessage ctrl_msg = ControlMessage.mkMessage(code);
            if (ctrl_msg != null) {
                if (available < 12) {
                    // The time stamp bytes were not received yet - return null.
                    buf.resetReaderIndex();
                    return null;
                }
                long timeStamp = buf.readLong();
                int clientPort = buf.readInt();
                available -= 12;
                if (ctrl_msg == ControlMessage.EOB_MESSAGE) {
                    long interval = System.currentTimeMillis() - timeStamp;
                    if (interval < 0)
                        interval = 0;

                    if (enableNettyMetrics) {
                        AsmHistogram netTransTime = getTransmitHistogram(channel, clientPort);
                        if (netTransTime != null) {
                            netTransTime.update(interval * TimeUtils.NS_PER_US);
                        }
                    }
                    if (MetricUtils.metricAccurateCal)
                        NettyMetricInstance.networkWorkerTransmitTime.update(interval * TimeUtils.NS_PER_US);
                }
                NettyMetricInstance.nettyServerRecvSpeed.update(ctrl_msg.getEncodedLength());
                return ctrl_msg;
            }

            // case 2: task Message
            short type = code;
            short task = buf.readShort();
            available -= 2;

            // Make sure that we have received at least an integer (length)
            if (available < 4) {
                // need more data
                buf.resetReaderIndex();

                return null;
            }

            // Read the length field.
            int length = buf.readInt();
            if (length <= 0) {
                LOG.info("Receive one message whose TaskMessage's message length is {}", length);
                return new TaskMessage(task, null);
            }

            // Make sure if there's enough bytes in the buffer.
            available -= 4;
            if (available < length) {
                // The whole bytes were not received yet - return null.
                buf.resetReaderIndex();

                return null;
            }

            // There's enough bytes in the buffer. Read it.
            ChannelBuffer payload = buf.readBytes(length);

            // Successfully decoded a frame.
            // Return a TaskMessage object

            byte[] rawBytes = payload.array();
            // @@@ TESTING CODE
            // LOG.info("Receive task:{}, length: {}, data:{}",
            // task, length, JStormUtils.toPrintableString(rawBytes));

            TaskMessage ret = new TaskMessage(type, task, rawBytes);
            NettyMetricInstance.nettyServerRecvSpeed.update(rawBytes.length + 8);
            return ret;
        } finally {
            if (isServer && enableNettyMetrics && msgDecodeTimer != null) {
                msgDecodeTimer.updateTime(startTime);
            }
        }

    }
801603
private void setHttpRequestHeaders(MessageContext msgContext, HttpRequest httpRequest) {
    @SuppressWarnings("unchecked")
    Map<Object, Object> requestHeaders =
        (Map<Object, Object>) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);
    if (requestHeaders != null) {
      for (Entry<Object, Object> headerEntry : requestHeaders.entrySet()) {
        Object headerKey = headerEntry.getKey();
        if (headerKey == null) {
          continue;
        }
        String headerName = headerKey.toString().trim();
        Object headerValue = headerEntry.getValue();
        if (HTTPConstants.HEADER_AUTHORIZATION.equals(headerName)
            && (headerValue instanceof String)) {
          // HttpRequest expects the Authorization header to be a list of values,
          // so handle the case where it is simply a string.
          httpRequest.getHeaders().setAuthorization((String) headerValue);
        } else {
          httpRequest.getHeaders().set(headerName, headerValue);
        }
      }
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
      httpRequest.getHeaders().setContentEncoding(HTTPConstants.COMPRESSION_GZIP);
    }
  }
1065821
private QYBaseRespMsg processMessageHandle(QYBaseReqMsg msg){
        if(CollectionUtil.isEmpty(messageHandles)){
            synchronized (LOCK){
                messageHandles = this.initMessageHandles();
            }
        }
        if(CollectionUtil.isNotEmpty(messageHandles)){
            for(QYMessageHandle messageHandle : messageHandles){
                QYBaseRespMsg resultMsg = null;
                boolean result;
                try{
                    result = messageHandle.beforeHandle(msg);
                }catch (Exception e){
                    result = false;
                }
                if(result){
                    resultMsg = messageHandle.handle(msg);
                }
                if(BeanUtil.nonNull(resultMsg)){
                    return resultMsg;
                }
            }
        }
        return null;
    }
70917
private void handleListMechsResponse(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception {
    String remote = ctx.channel().remoteAddress().toString();
    String[] supportedMechanisms = SaslListMechsResponse.supportedMechs(msg);
    if (supportedMechanisms.length == 0) {
      throw new AuthenticationException("Received empty SASL mechanisms list from server: " + remote);
    }

    saslClient = Sasl.createSaslClient(supportedMechanisms, null, "couchbase", remote, null, this);
    selectedMechanism = saslClient.getMechanismName();

    byte[] bytePayload = saslClient.hasInitialResponse() ? saslClient.evaluateChallenge(new byte[]{}) : null;
    ByteBuf payload = bytePayload != null ? ctx.alloc().buffer().writeBytes(bytePayload) : Unpooled.EMPTY_BUFFER;

    ByteBuf request = ctx.alloc().buffer();
    SaslAuthRequest.init(request);
    SaslAuthRequest.mechanism(selectedMechanism, request);
    SaslAuthRequest.challengeResponse(payload, request);
    payload.release();

    ChannelFuture future = ctx.writeAndFlush(request);
    future.addListener(new GenericFutureListener<Future<Void>>() {
      @Override
      public void operationComplete(Future<Void> future) throws Exception {
        if (!future.isSuccess()) {
          LOGGER.warn("Error during SASL Auth negotiation phase.", future);
          originalPromise().setFailure(future.cause());
        }
      }
    });
  }
971405
private void createProxyHandler() throws MessageStoreException {
        if (TraceComponent.isAnyTracingEnabled()
            && tc.isEntryEnabled())
            SibTr.entry(tc, "createProxyHandler");

        _multiMEProxyHandler = new MultiMEProxyHandler(this, _txManager);
        _persistentStore.addItemStream(_multiMEProxyHandler, _txManager
                        .createAutoCommitTransaction());

        if (TraceComponent.isAnyTracingEnabled()
            && tc.isEntryEnabled())
            SibTr.exit(tc, "createProxyHandler");
    }
416960
@Override
  protected void channelRead0(final ChannelHandlerContext ctx, final HttpObject msg) throws Exception {
    if (msg instanceof HttpContent) {
      HttpContent content = (HttpContent) msg;
      decodeChunk((InetSocketAddress) ctx.channel().remoteAddress(), content.content());
    }
  }