Example usage for io.netty.channel ChannelHandlerContext channel

List of usage examples for io.netty.channel ChannelHandlerContext channel

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext channel.

Prototype

Channel channel();

Source Link

Document

Return the Channel which is bound to the ChannelHandlerContext .

Usage

From source file:com.corundumstudio.socketio.transport.XHRPollingTransport.java

License:Apache License

private void onGet(UUID sessionId, ChannelHandlerContext ctx, String origin) {
    HandshakeData data = authorizeHandler.getHandshakeData(sessionId);
    if (data == null) {
        sendError(ctx, origin, sessionId);
        return;/*w w w  .  jav  a  2s.c o m*/
    }

    XHRPollingClient client = (XHRPollingClient) sessionId2Client.get(sessionId);
    if (client == null) {
        client = createClient(origin, ctx.channel(), sessionId, data);
    }

    client.bindChannel(ctx.channel(), origin);

    scheduleDisconnect(ctx.channel(), sessionId);
    scheduleNoop(sessionId);
}

From source file:com.corundumstudio.socketio.transport.XHRPollingTransport.java

License:Apache License

private void sendError(ChannelHandlerContext ctx, String origin, UUID sessionId) {
    log.debug("Client with sessionId: {} was not found! Reconnect error response sended", sessionId);
    Packet packet = new Packet(PacketType.ERROR);
    packet.setReason(ErrorReason.CLIENT_NOT_HANDSHAKEN);
    packet.setAdvice(ErrorAdvice.RECONNECT);
    ctx.channel().writeAndFlush(new XHRErrorMessage(packet, origin, sessionId));
}

From source file:com.couchbase.client.core.endpoint.AbstractGenericHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    LOGGER.debug(logIdent(ctx, endpoint) + "Channel Active.");

    SocketAddress addr = ctx.channel().remoteAddress();
    if (addr instanceof InetSocketAddress) {
        // Avoid lookup, so just use the address
        remoteHostname = ((InetSocketAddress) addr).getAddress().getHostAddress();
    } else {/*from   w  w w . jav  a 2s  .com*/
        // Should not happen in production, but in testing it might be different
        remoteHostname = addr.toString();
    }
    ctx.fireChannelActive();
}

From source file:com.couchbase.client.core.endpoint.AbstractGenericHandler.java

License:Apache License

@Override
public void channelWritabilityChanged(final ChannelHandlerContext ctx) throws Exception {
    if (!ctx.channel().isWritable()) {
        ctx.flush();//  ww w .ja v a2s  . co  m
    }
    ctx.fireChannelWritabilityChanged();
}

From source file:com.couchbase.client.core.endpoint.AbstractGenericHandler.java

License:Apache License

@Override
public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
        CouchbaseRequest keepAlive = createKeepAliveRequest();
        if (keepAlive != null) {
            keepAlive.observable().subscribe(new KeepAliveResponseAction(ctx));
            onKeepAliveFired(ctx, keepAlive);

            Channel channel = ctx.channel();
            if (channel.isActive() && channel.isWritable()) {
                ctx.pipeline().writeAndFlush(keepAlive);
            }/*from   w w w. j  a v  a  2  s  .  co m*/
        }
    } else {
        super.userEventTriggered(ctx, evt);
    }
}

From source file:com.couchbase.client.core.endpoint.AbstractGenericHandler.java

License:Apache License

/**
 * Simple log helper to give logs a common prefix.
 *
 * @param ctx the context./*from  w w  w  .  j  a va 2  s  . com*/
 * @param endpoint the endpoint.
 * @return a prefix string for logs.
 */
protected static String logIdent(final ChannelHandlerContext ctx, final Endpoint endpoint) {
    return "[" + ctx.channel().remoteAddress() + "][" + endpoint.getClass().getSimpleName() + "]: ";
}

From source file:com.couchbase.client.core.endpoint.AbstractGenericHandler.java

License:Apache License

/**
 * Helper method to return the remote http host, cached.
 *
 * @param ctx the handler context./*w w w. j a  v  a2s .co m*/
 * @return the remote http host.
 */
protected String remoteHttpHost(ChannelHandlerContext ctx) {
    if (remoteHttpHost == null) {
        SocketAddress addr = ctx.channel().remoteAddress();
        if (addr instanceof InetSocketAddress) {
            InetSocketAddress inetAddr = (InetSocketAddress) addr;
            remoteHttpHost = inetAddr.getAddress().getHostAddress() + ":" + inetAddr.getPort();
        } else {
            remoteHttpHost = addr.toString();
        }
    }
    return remoteHttpHost;
}

From source file:com.couchbase.client.core.endpoint.binary.BinaryAuthHandler.java

License:Open Source License

/**
 * Handles an incoming SASL list mechanisms response and dispatches the next SASL AUTH step.
 *
 * @param ctx the handler context./*w  w  w  .j  ava2s  .  co  m*/
 * @param msg the incoming message to investigate.
 * @throws Exception
 */
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);
    }

    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,
            Unpooled.EMPTY_BUFFER, payload);
    initialRequest.setOpcode(SASL_AUTH_OPCODE).setKeyLength((short) mechanismLength)
            .setTotalBodyLength(mechanismLength + payload.readableBytes());

    ctx.writeAndFlush(initialRequest);
}

From source file:com.couchbase.client.core.endpoint.binary.BinaryCodec.java

License:Open Source License

@Override
protected void decode(final ChannelHandlerContext ctx, final FullBinaryMemcacheResponse msg,
        final List<Object> in) throws Exception {
    Class<?> clazz = queue.poll();

    ResponseStatus status = convertStatus(msg.getStatus());
    long cas = msg.getCAS();
    if (clazz.equals(GetBucketConfigRequest.class)) {
        InetSocketAddress addr = (InetSocketAddress) ctx.channel().remoteAddress();
        in.add(new GetBucketConfigResponse(convertStatus(msg.getStatus()),
                msg.content().toString(CharsetUtil.UTF_8), addr.getHostName()));
    } else if (clazz.equals(GetRequest.class)) {
        in.add(new GetResponse(status, cas, msg.content().copy()));
    } else if (clazz.equals(InsertRequest.class)) {
        in.add(new InsertResponse(status, cas));
    } else if (clazz.equals(UpsertRequest.class)) {
        in.add(new UpsertResponse(status, cas));
    } else if (clazz.equals(ReplaceRequest.class)) {
        in.add(new ReplaceResponse(status, cas));
    } else if (clazz.equals(RemoveRequest.class)) {
        in.add(new RemoveResponse(convertStatus(msg.getStatus())));
    } else {/*from  w  ww  .  j  a  v  a  2 s  .c  om*/
        throw new IllegalStateException("Got a response message for a request that was not sent." + msg);
    }
}

From source file:com.couchbase.client.core.endpoint.binary.BinarySaslClient.java

License:Open Source License

/**
 * Handles an incoming SASL list mechanisms response and dispatches the next SASL AUTH step.
 *
 * @param ctx the handler context./*from   ww  w . j  a  va2  s.c o m*/
 * @param msg the incoming message to investigate.
 * @throws Exception
 */
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 IllegalStateException("Received empty SASL mechanisms list from server: " + remote);
    }

    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,
            Unpooled.EMPTY_BUFFER, payload);
    initialRequest.setOpcode(SASL_AUTH_OPCODE).setKeyLength((short) mechanismLength)
            .setTotalBodyLength(mechanismLength + payload.readableBytes());

    ctx.writeAndFlush(initialRequest);
}