Example usage for io.netty.channel ChannelHandlerContext alloc

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

Introduction

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

Prototype

ByteBufAllocator alloc();

Source Link

Document

Return the assigned ByteBufAllocator which will be used to allocate ByteBuf s.

Usage

From source file:io.lettuce.core.ProtectedModeTests.java

License:Apache License

@BeforeClass
public static void beforeClass() throws Exception {

    server = new MockTcpServer();

    server.addHandler(() -> {//from  w w  w .  j av a2  s . c o  m
        return new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {

                String message = getMessage();
                ByteBuf buffer = ctx.alloc().buffer(message.length() + 3);
                buffer.writeCharSequence("-", StandardCharsets.US_ASCII);
                buffer.writeCharSequence(message, StandardCharsets.US_ASCII);
                buffer.writeByte('\r').writeByte('\n');

                ctx.writeAndFlush(buffer).addListener(future -> {
                    ctx.close();
                });
            }
        };
    });

    server.initialize(TestSettings.nonexistentPort());

    client = RedisClient.create(TestClientResources.get(),
            RedisURI.create(TestSettings.host(), TestSettings.nonexistentPort()));
}

From source file:io.lettuce.core.protocol.CommandHandler.java

License:Apache License

/**
 * @see io.netty.channel.ChannelInboundHandlerAdapter#channelRegistered(io.netty.channel.ChannelHandlerContext)
 *///  www . ja v  a 2  s  . c o m
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {

    if (isClosed()) {
        logger.debug("{} Dropping register for a closed channel", logPrefix());
    }

    channel = ctx.channel();

    if (debugEnabled) {
        logPrefix = null;
        logger.debug("{} channelRegistered()", logPrefix());
    }

    setState(LifecycleState.REGISTERED);

    buffer = ctx.alloc().directBuffer(8192 * 8);
    ctx.fireChannelRegistered();
}

From source file:io.lettuce.core.server.RandomServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {

    byte[] response = new byte[count];

    Arrays.fill(response, "A".getBytes()[0]);

    ByteBuf buf = ctx.alloc().heapBuffer(response.length);

    ByteBuf encoded = buf.writeBytes(response);
    ctx.writeAndFlush(encoded);//from w w w  . jav a  2s  .com
}

From source file:io.lunamc.plugins.example.netty.ExamplePlayHandler.java

License:Apache License

private void writeJoinGame(ChannelHandlerContext ctx) {
    ByteBuf out = ctx.alloc().buffer();
    // Write packet id of join game (0x23)
    ProtocolUtils.writeVarInt(out, 0x23);
    // Write entity id
    out.writeInt(42);/*www. j  a va  2  s  . c om*/
    // Write game mode (0 = survival)
    out.writeByte(0);
    // Write dimension (0 = overworld)
    out.writeInt(0);
    // Write difficulty (0 = peaceful)
    out.writeByte(0);
    // Write max players
    out.writeByte(1);
    // Write level type
    ProtocolUtils.writeString(out, "default");
    // Write reduced debug info
    out.writeBoolean(false);

    // Send it to the client
    ctx.writeAndFlush(out, ctx.voidPromise());
}

From source file:io.lunamc.plugins.example.netty.ExamplePlayHandler.java

License:Apache License

private void writeBrand(ChannelHandlerContext ctx) {
    ByteBuf data = ctx.alloc().buffer();
    ByteBuf out = ctx.alloc().buffer();/* ww  w. ja v  a 2 s . c  om*/
    try {
        // Write plugin message data
        ProtocolUtils.writeString(data, "LunaMC_Example");

        // Write packet id of plugin message (0x18)
        ProtocolUtils.writeVarInt(out, 0x18);
        // Write channel name
        ProtocolUtils.writeString(out, "MC|Brand");
        // Write plugin message
        ProtocolUtils.writeVarInt(out, data.readableBytes());
        out.writeBytes(data);
    } finally {
        data.release();
    }

    // Send it to the client
    ctx.writeAndFlush(out, ctx.voidPromise());
}

From source file:io.lunamc.plugins.example.netty.ExamplePlayHandler.java

License:Apache License

private void writeKick(ChannelHandlerContext ctx) {
    LOGGER.info("Example play handling done for {}", connection.getProfile());
    TextComponent message = componentBuilderFactory.requireInstance().createTextComponentBuilder().text(
            "Thank you " + connection.getProfile().getName() + " for trying out the LunaMC Example Plugin!")
            .build();/*from   w w w  .  j  a v a2 s  .c  o  m*/
    String json = jsonMapper.requireInstance().serialize(message);

    ByteBuf out = ctx.alloc().buffer();
    // Write packet id of disconnect (0x1a)
    ProtocolUtils.writeVarInt(out, 0x1a);
    // Write reason
    ProtocolUtils.writeString(out, json);

    // Send it to the client and closes the connection
    NettyUtils.writeFlushAndClose(ctx, out);
}

From source file:io.maelstorm.server.example.HelloEndpoint.java

License:Open Source License

public Deferred<FullHttpResponse> process(ChannelHandlerContext context, AggregatedFullHttpRequest request) {
    ByteBuf buffer = context.alloc().buffer();
    buffer.writeBytes(response);//from  www .  j a  v a2 s  .c om
    FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK,
            buffer, false);
    response.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/html");
    Deferred<FullHttpResponse> deferred = new Deferred<FullHttpResponse>();
    deferred.callback(response);
    return deferred;
}

From source file:io.maelstorm.server.ResponseUtils.java

License:Open Source License

public static Deferred<FullHttpResponse> makeSimpleHtmlResponse(ChannelHandlerContext context,
        HttpVersion version, HttpResponseStatus status, String message) {
    ByteBuf buffer = context.alloc().buffer(message.length());
    buffer.writeBytes(message.getBytes());
    FullHttpResponse response = new DefaultFullHttpResponse(version, status, buffer, false);
    response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html");
    Deferred<FullHttpResponse> deferred = new Deferred<FullHttpResponse>();
    deferred.callback(response);//from w  w w . ja  va  2 s  .c  o  m
    return deferred;
}

From source file:io.maelstorm.server.ShutDownEndpoint.java

License:Open Source License

public Deferred<FullHttpResponse> process(ChannelHandlerContext context, AggregatedFullHttpRequest request) {
    ByteBuf buffer = context.alloc().buffer(resp.length());
    buffer.writeBytes(resp.getBytes());/*from  w ww .  j a  v  a 2s. c om*/
    FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK,
            buffer);
    response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html");
    Deferred<FullHttpResponse> deferred = new Deferred<FullHttpResponse>();
    deferred.callback(response);
    shutDownGracefully();
    super.doShutdown();
    return deferred;
}

From source file:io.moquette.parser.netty.SubAckEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext chc, SubAckMessage message, ByteBuf out) {
    if (message.types().isEmpty()) {
        throw new IllegalArgumentException("Found a suback message with empty topics");
    }//from  ww  w .j  av a  2 s  . c o  m

    int variableHeaderSize = 2 + message.types().size();
    ByteBuf buff = chc.alloc().buffer(6 + variableHeaderSize);
    try {
        buff.writeByte(AbstractMessage.SUBACK << 4);
        buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize));
        buff.writeShort(message.getMessageID());
        for (QOSType c : message.types()) {
            buff.writeByte(c.byteValue());
        }

        out.writeBytes(buff);
    } finally {
        buff.release();
    }
}