Handles an incoming SASL list mechanisms response and dispatches the next SASL AUTH step.

@param ctx the handler context.
@param msg the incoming message to investigate.
@throws Exception if something goes wrong during negotiation.
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);
                }
            }
        });
    }
407773
def exception(self, msg, *args, **kwargs):
        
        extra = kwargs.setdefault('extra', {})
        extra['exc_fullstack'] = self.isEnabledFor(logging.DEBUG)
        kwargs['exc_info'] = True
        self.log(logging.ERROR, msg, *args, **kwargs)
944511
@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof Frame) {
            Frame frame = (Frame) msg;
            if (hasCurrentTransaction()) {
                String tid = currentDataFrameTransaction.getId();
                logger.trace("Received frame within transaction ({}) context: {}", tid, frame);

                // give new frame to current transaction
                NettyZWaveChannelContext zctx = new NettyZWaveChannelContext();
                if (currentDataFrameTransaction.addFrame(zctx, frame)) {
                    if (currentDataFrameTransaction.isComplete()) {
                        logger.trace("*** Data frame transaction ({}) completed", tid);
                        logger.trace("");
                        cancelTimeoutCallback();
                    }
                    zctx.process(ctx);
                // if transaction didn't consume frame, then pass it down the pipeline
                } else {
                    logger.trace("Transaction ignored frame so passing it along");
                    ctx.fireChannelRead(msg);
                }
            } else if (msg instanceof AddNodeToNetwork) {
                logger.trace("Received ADD_NODE_STATUS_NODE_FOUND; starting transaction");
                NettyZWaveChannelContext zctx = new NettyZWaveChannelContext();
                currentDataFrameTransaction = new NodeInclusionTransaction(zctx, (DataFrame)msg);
                zctx.process(ctx);
            } else {
                logger.trace("Received frame outside of transaction context so passing it along: {}", frame);
                ctx.fireChannelRead(msg);
            }
        }
    }
998413
private void sendInitialMessage(final ChannelHandlerContext ctx) throws Exception {
        final long connectTimeoutMillis = this.connectTimeoutMillis;
        if (connectTimeoutMillis > 0) {
            connectTimeoutFuture = ctx.executor().schedule(new Runnable() {
                @Override
                public void run() {
                    if (!connectPromise.isDone()) {
                        setConnectFailure(new ProxyConnectException(exceptionMessage("timeout")));
                    }
                }
            }, connectTimeoutMillis, TimeUnit.MILLISECONDS);
        }

        final Object initialMessage = newInitialMessage(ctx);
        if (initialMessage != null) {
            sendToProxyServer(initialMessage);
        }

        readIfNeeded(ctx);
    }
984003
@Override
    public void handleMessage(Message msg) {
        if (msg.what == ASYNC) {
            mAsyncDispatcher.dispatch();
        } else if (msg.what == SYNC) {
            mSyncDispatcher.dispatch();
        } else super.handleMessage(msg);
    }
1077751
protected final String exceptionMessage(String msg) {
        if (msg == null) {
            msg = "";
        }

        StringBuilder buf = new StringBuilder(128 + msg.length())
            .append(protocol())
            .append(", ")
            .append(authScheme())
            .append(", ")
            .append(proxyAddress)
            .append(" => ")
            .append(destinationAddress);
        if (!msg.isEmpty()) {
            buf.append(", ").append(msg);
        }

        return buf.toString();
    }
600840
@Override
	public void channelActive(final ChannelHandlerContext ctx) throws Exception {
		if (this.ctx == null) {
			this.ctx = ctx;
		}

		super.channelActive(ctx);
	}
1161427
@Override
    protected void channelRead0(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
        switch (msg.getStatus()) {
            case SUCCESS:
                originalPromise.setSuccess();
                ctx.pipeline().remove(this);
                ctx.fireChannelActive();
                break;
            case ACCESS_ERROR:
                originalPromise.setFailure(new AuthenticationException("Authentication failure on Select Bucket command"));
                break;
            case NOTFOUND_ERROR:
                originalPromise.setFailure(new AuthenticationException("Bucket not found on Select Bucket command"));
                break;
            default:
                originalPromise.setFailure(new AuthenticationException("Unhandled select bucket status: "
                        + msg.getStatus()));
        }
    }
50657
private void proxy(final SipResponse msg) {
        final ViaHeader via = msg.getViaHeader();
        final Connection connection = this.stack.connect(via.getHost(), via.getPort());
        connection.send(msg);
    }
844909
public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
        logResponse("Sending SOAP response", messageContext, false);
        
        return true;
    }
846950
public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {
        logRequest("Received SOAP request", messageContext, true);
        
        return true;
    }
759624
protected void handleResponse(final NextFilter nextFilter,
            final IoBuffer buf, int step) throws Exception {
        int len = 2;
        if (step == SocksProxyConstants.SOCKS5_GREETING_STEP) {
            // Send greeting message
            byte method = buf.get(1);

            if (method == SocksProxyConstants.NO_ACCEPTABLE_AUTH_METHOD) {
                throw new IllegalStateException(
                        "No acceptable authentication method to use with " +
                        "the socks proxy server");
            }

            getSession().setAttribute(SELECTED_AUTH_METHOD, method);

        } else if (step == SocksProxyConstants.SOCKS5_AUTH_STEP) {
            // Authentication to the SOCKS server 
            byte method = (Byte) getSession().getAttribute(
                    Socks5LogicHandler.SELECTED_AUTH_METHOD);

            if (method == SocksProxyConstants.GSSAPI_AUTH) {
                int oldPos = buf.position();

                if (buf.get(0) != 0x01) {
                    throw new IllegalStateException("Authentication failed");
                }
                if (buf.get(1) == 0xFF) {
                    throw new IllegalStateException(
                            "Authentication failed: GSS API Security Context Failure");
                }

                if (buf.remaining() >= 2) {
                    byte[] size = new byte[2];
                    buf.get(size);
                    int s = ByteUtilities.makeIntFromByte2(size);
                    if (buf.remaining() >= s) {
                        byte[] token = new byte[s];
                        buf.get(token);
                        getSession().setAttribute(GSS_TOKEN, token);
                        len = 0;
                    } else {
                        //buf.position(oldPos);
                        return;
                    }
                } else {
                    buf.position(oldPos);
                    return;
                }
            } else if (buf.get(1) != SocksProxyConstants.V5_REPLY_SUCCEEDED) {
                throw new IllegalStateException("Authentication failed");
            }

        } else if (step == SocksProxyConstants.SOCKS5_REQUEST_STEP) {
            // Send the request
            byte addressType = buf.get(3);
            len = 6;
            if (addressType == SocksProxyConstants.IPV6_ADDRESS_TYPE) {
                len += 16;
            } else if (addressType == SocksProxyConstants.IPV4_ADDRESS_TYPE) {
                len += 4;
            } else if (addressType == SocksProxyConstants.DOMAIN_NAME_ADDRESS_TYPE) {
                len += 1 + (buf.get(4));
            } else {
                throw new IllegalStateException("Unknwon address type");
            }

            if (buf.remaining() >= len) {
                // handle response
                byte status = buf.get(1);
                LOGGER.debug("  response status: {}", SocksProxyConstants
                        .getReplyCodeAsString(status));

                if (status == SocksProxyConstants.V5_REPLY_SUCCEEDED) {
                    buf.position(buf.position() + len);
                    setHandshakeComplete();
                    return;
                }

                throw new Exception("Proxy handshake failed - Code: 0x"
                            + ByteUtilities.asHex(new byte[] { status }));
            }

            return;
        }

        if (len > 0) {
            buf.position(buf.position() + len);
        }

        // Move to the handshaking next step if not in the middle of
        // the authentication process
        boolean isAuthenticating = false;
        if (step == SocksProxyConstants.SOCKS5_AUTH_STEP) {
            byte method = (Byte) getSession().getAttribute(
                    Socks5LogicHandler.SELECTED_AUTH_METHOD);
            if (method == SocksProxyConstants.GSSAPI_AUTH) {
                GSSContext ctx = (GSSContext) getSession().getAttribute(
                        GSS_CONTEXT);
                if (ctx == null || !ctx.isEstablished()) {
                    isAuthenticating = true;
                }
            }
        }

        if (!isAuthenticating) {
            getSession().setAttribute(HANDSHAKE_STEP, ++step);
        }

        doHandshake(nextFilter);
    }
266026
public void send(Message msg) throws Exception {
        num_senders.incrementAndGet();
        long size=msg.size();

        lock.lock();
        try {
            if(count + size >= transport.getMaxBundleSize())
                sendBundledMessages();

            addMessage(msg, size);

            // at this point, we haven't sent our message yet !
            if(num_senders.decrementAndGet() == 0) // no other sender threads present at this time
                sendBundledMessages();
            // else there are other sender threads waiting, so our message will be sent by a different thread
        }
        finally {
            lock.unlock();
        }
    }
1212393
protected void initiateCommsHandshaking() 
      throws SIConnectionLostException, SIConnectionDroppedException
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "initiateCommsHandshaking");
      
      initiateCommsHandshakingImpl(false);
      
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "initiateCommsHandshaking");
   }
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;
	}
649427
@Override
  protected void channelRead0(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception {
    ResponseStatus status = MessageUtil.getResponseStatus(msg);
    if (status.isSuccess()) {
      step++;
      switch (step) {
        case HELLO:
          hello(ctx, msg);
          break;
        case SELECT:
          select(ctx);
          break;
        case OPEN:
          open(ctx);
          break;
        case REMOVE:
          remove(ctx);
          break;
        default:
          originalPromise().setFailure(new IllegalStateException("Unidentified DcpConnection step " + step));
          break;
      }
    } else {
      originalPromise().setFailure(new IllegalStateException("Could not open DCP Connection: Failed in the "
          + toString(step) + " step, response status is " + status));
    }
  }
1243539
@Override
	public void process(Packet message, MessageContext ctx)
	{
		EntityPlayerSP player = (EntityPlayerSP) Utils.getClientPlayer();
		if (message.type == ContainerType.TYPE_TILEENTITY)
		{
			IDirectInventoryProvider inventoryProvider = TileEntityUtils.getTileEntity(	IDirectInventoryProvider.class,
																						Utils.getClientWorld(),
																						message.pos);
			if (inventoryProvider != null)
				MalisisInventory.open(player, inventoryProvider, message.windowId);
		}

		else if (message.type == ContainerType.TYPE_ITEM)
		{
			//TODO: send and use slot number instead of limited to equipped
			ItemStack itemStack = player.getHeldItemMainhand();
			if (itemStack == null || !(itemStack.getItem() instanceof IDeferredInventoryProvider<?>))
				return;

			@SuppressWarnings("unchecked")
			IDeferredInventoryProvider<ItemStack> inventoryProvider = (IDeferredInventoryProvider<ItemStack>) itemStack.getItem();
			MalisisInventory.open(player, inventoryProvider, itemStack, message.windowId);
		}
	}