Dispatches incoming SASL responses to the appropriate handler methods.

@param ctx the handler context.
@param msg the incoming message to investigate.
@throws Exception if something goes wrong during negotiation.
8919
@Override
    protected void channelRead0(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
        if (msg.getOpcode() == SASL_LIST_MECHS_OPCODE) {
            handleListMechsResponse(ctx, msg);
        } else if (msg.getOpcode() == SASL_AUTH_OPCODE) {
            handleAuthResponse(ctx, msg);
        } else if (msg.getOpcode() == SASL_STEP_OPCODE) {
            checkIsAuthed(msg);
        }
    }
764975
@Override
  public void channelRead(
      final ChannelHandlerContext ctx, final Object msg) throws Exception {
    try {
      this.listener.channelRead(ctx, msg);
    } finally {
      ReferenceCountUtil.release(msg);
    }
  }
987608
public void msg( Thread t, int severity, Object source, Throwable ex, String msg ) {
        logger.msg( t, severity,source,ex,msg);
    }
270411
def handle_request(self, msg):
        
        method = self.__class__.unhandled_request
        if msg.name in self._request_handlers:
            method = self._request_handlers[msg.name]

        try:
            reply = method(self, msg)
            if isinstance(reply, Message):
                # If it is a message object, assume it is a reply.
                reply.mid = msg.mid
                assert (reply.mtype == Message.REPLY)
                assert (reply.name == msg.name)
                self._logger.info("%s OK" % (msg.name,))
                self.send_message(reply)
            else:
                # Just pass on what is, potentially, a future. The implementor
                # of the request handler method must arrange for a reply to be
                # sent. Since clients have no business dealing with requests in
                # any case we don't do much to help them.
                return reply
        # We do want to catch everything that inherits from Exception
        # pylint: disable-msg = W0703
        except Exception:
            e_type, e_value, trace = sys.exc_info()
            reason = "\n".join(traceback.format_exception(
                e_type, e_value, trace, self._tb_limit))
            self._logger.error("Request %s FAIL: %s" % (msg.name, reason))
825808
public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException {
        try {
            logResponse("Received SOAP response", messageContext, true);
        } catch (SoapEnvelopeException e) {
            log.warn("Unable to write SOAP response to logger", e);
        } catch (TransformerException e) {
            log.warn("Unable to write SOAP response to logger", e);
        }
        
        return true;
    }
984003
@Override
    public void handleMessage(Message msg) {
        if (msg.what == ASYNC) {
            mAsyncDispatcher.dispatch();
        } else if (msg.what == SYNC) {
            mSyncDispatcher.dispatch();
        } else super.handleMessage(msg);
    }
1307979
Object proceedAndSendMessage(InvocationContext ctx, String topic, boolean jsonPayload) throws Exception {
		MessageToClient messageToClient = new MessageToClient();
		messageToClient.setId(topic);
		Object result = ctx.proceed();
		if(jsonPayload) {
			if(!String.class.isInstance(result)) {
				throw new UnsupportedOperationException("Method annotated JsTopic(jsonPayload=true) must return String type and correct Json.");
			}
			messageToClient.setJson((String) result);
		} else {
			messageToClient.setResponse(result);
		}
		wsEvent.fire(messageToClient);
		return result;
	}
763627
@Override
	public void process(Packet message, MessageContext ctx)
	{
		if (MalisisGui.current() != null)
			MalisisGui.current().close();
	}
848670
function (msg) {
            var msgHandlers;
            if (!msg.method) {
                // no message type, ignoring it
                // TODO: should we trigger a generic event?
                console.log("[Brackets LiveDev] Received message without method.");
                return;
            }
            // get handlers for msg.method
            msgHandlers = this.handlers[msg.method];

            if (msgHandlers && msgHandlers.length > 0) {
                // invoke handlers with the received message
                msgHandlers.forEach(function (handler) {
                    try {
                        // TODO: check which context should be used to call handlers here.
                        handler(msg);
                        return;
                    } catch (e) {
                        console.log("[Brackets LiveDev] Error executing a handler for " + msg.method);
                        console.log(e.stack);
                        return;
                    }
                });
            } else {
                // no subscribers, ignore it.
                // TODO: any other default handling? (eg. specific respond, trigger as a generic event, etc.);
                console.log("[Brackets LiveDev] No subscribers for message " + msg.method);
                return;
            }
        }
812900
void processAck(Message msg) {
        PubAck pa;
        Exception ex = null;
        try {
            pa = PubAck.parseFrom(msg.getData());
        } catch (InvalidProtocolBufferException e) {
            // If we are speaking to a server we don't understand, let the
            // user know.
            System.err.println("Protocol error: " +  e.getStackTrace());
            return;
        }

        // Remove
        AckClosure ackClosure = removeAck(pa.getGuid());
        if (ackClosure != null) {
            // Capture error if it exists.
            String ackError = pa.getError();

            if (ackClosure.ah != null) {
                if (!ackError.isEmpty()) {
                    ex = new IOException(ackError);
                }
                // Perform the ackHandler callback
                ackClosure.ah.onAck(pa.getGuid(), ex);
            } else if (ackClosure.ch != null) {
                try {
                    ackClosure.ch.put(ackError);
                } catch (InterruptedException e) {
                    // ignore
                }
            }
        }
    }
572875
private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause) {
        setHandshakeFailure(ctx, cause, true, true, false);
    }
118540
@Override
    protected void throwStreamException(String msg, Location loc)
        throws XMLStreamException
    {
        if (loc == null) {
            throw new WstxParsingException(msg);
        }
        throw new WstxParsingException(msg, loc);
    }
294934
@Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable exception) throws Exception {
    if (exception instanceof FrameDecodingException) {
      int streamId = ((FrameDecodingException) exception).streamId;
      LOG.debug("[{}] Error while decoding response on stream id {}", logPrefix, streamId);
      if (streamId >= 0) {
        // We know which request matches the failing response, fail that one only
        ResponseCallback responseCallback = inFlight.get(streamId);
        if (responseCallback != null) {
          try {
            responseCallback.onFailure(exception.getCause());
          } catch (Throwable t) {
            Loggers.warnWithException(
                LOG, "[{}] Unexpected error while invoking failure handler", logPrefix, t);
          }
        }
        release(streamId, ctx);
      } else {
        Loggers.warnWithException(
            LOG,
            "[{}] Unexpected error while decoding incoming event frame",
            logPrefix,
            exception.getCause());
      }
    } else {
      // Otherwise fail all pending requests
      abortAllInFlight(
          (exception instanceof HeartbeatException)
              ? (HeartbeatException) exception
              : new ClosedConnectionException("Unexpected error on channel", exception));
      ctx.close();
    }
  }
584515
@Override
  public void handlerRemoved(final ChannelHandlerContext ctx) throws Exception {
    if (responseContent != null && responseContent.refCnt() > 0) {
      responseContent.release();
      responseContent = null;
    }
  }
534549
@Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {
      if (exceptionRaised.get()) {
        return;
      }

      if (!(msg instanceof HttpRequest)) {
        // If there is no methodInfo, it means the request was already rejected.
        // What we received here is just residue of the request, which can be ignored.
        if (methodInfo != null) {
          ReferenceCountUtil.retain(msg);
          ctx.fireChannelRead(msg);
        }
        return;
      }
      HttpRequest request = (HttpRequest) msg;
      BasicHttpResponder responder = new BasicHttpResponder(ctx.channel(), sslEnabled);

      // Reset the methodInfo for the incoming request error handling
      methodInfo = null;
      methodInfo = prepareHandleMethod(request, responder, ctx);

      if (methodInfo != null) {
        ReferenceCountUtil.retain(msg);
        ctx.fireChannelRead(msg);
      } else {
        if (!responder.isResponded()) {
          // If not yet responded, just respond with a not found and close the connection
          HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
          HttpUtil.setContentLength(response, 0);
          HttpUtil.setKeepAlive(response, false);
          ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        } else {
          // If already responded, just close the connection
          ctx.channel().close();
        }
      }
    } finally {
      ReferenceCountUtil.release(msg);
    }
  }
1305096
private Object invoke(ServiceRequestContext ctx, HttpRequest req, @Nullable AggregatedHttpMessage message) {
        try (SafeCloseable ignored = ctx.push(false)) {
            final ResolverContext resolverContext = new ResolverContext(ctx, req, message);
            final Object[] arguments = toArguments(resolvers, resolverContext);
            return method.invoke(object, arguments);
        } catch (Throwable cause) {
            return exceptionHandler.handleException(ctx, req, cause);
        }
    }
768612
private void handleListMechsResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
        String remote = ctx.channel().remoteAddress().toString();
        String[] supportedMechanisms = msg.content().toString(CharsetUtil.UTF_8).split(" ");
        if (supportedMechanisms.length == 0) {
            throw new AuthenticationException("Received empty SASL mechanisms list from server: " + remote);
        }
        if (forceSaslPlain) {
            LOGGER.trace("Got SASL Mechs {} but forcing PLAIN due to config setting.", Arrays.asList(supportedMechanisms));
            supportedMechanisms = new String[] { "PLAIN" };
        }

        saslClient = Sasl.createSaslClient(supportedMechanisms, null, "couchbase", remote, null, this);
        selectedMechanism = saslClient.getMechanismName();
        int mechanismLength = selectedMechanism.length();
        byte[] bytePayload = saslClient.hasInitialResponse() ? saslClient.evaluateChallenge(new byte[]{}) : null;
        ByteBuf payload = bytePayload != null ? ctx.alloc().buffer().writeBytes(bytePayload) : Unpooled.EMPTY_BUFFER;

        FullBinaryMemcacheRequest initialRequest = new DefaultFullBinaryMemcacheRequest(
            selectedMechanism.getBytes(CharsetUtil.UTF_8),
            Unpooled.EMPTY_BUFFER,
            payload
        );
        initialRequest
            .setOpcode(SASL_AUTH_OPCODE)
            .setKeyLength((short) mechanismLength)
            .setTotalBodyLength(mechanismLength + payload.readableBytes());

        ChannelFuture future = ctx.writeAndFlush(initialRequest);
        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);
                }
            }
        });
    }