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:org.evilco.network.rcon.common.codec.RconCodec.java

License:Apache License

/**
 * {@inheritDoc}/*from  www. j a v a 2  s  . com*/
 */
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> objects)
        throws Exception {
    // set order
    byteBuf = byteBuf.order(ByteOrder.LITTLE_ENDIAN);

    // read identifier
    int identifier = byteBuf.readInt();

    // read packet identifier
    int packetID = byteBuf.readInt();

    // allocate buffer
    ByteBuf buffer = channelHandlerContext.alloc().buffer((byteBuf.readableBytes() - 1));

    // read data
    byteBuf.readBytes(buffer, (byteBuf.readableBytes() - 2));

    // read null byte
    Preconditions.checkState((byteBuf.readByte() == 0x00 && byteBuf.readByte() == 0x00),
            "The last byte is not null");
    Preconditions.checkState((byteBuf.readableBytes() == 0), "There is still data left in the packet.");

    // read data
    IPacket packet = this.configuration.getInboundRegistry().createPacketInstance(packetID, buffer);

    // log
    getLogger().debug("Decoded packet of type " + packet.getClass().getName() + " (packetID: " + packetID
            + ", identifier: " + identifier + ").");

    // construct wrapper
    PacketWrapper wrapper = new PacketWrapper(identifier, packet);

    // fire event
    PacketReceiveEvent event = new PacketReceiveEvent(wrapper);
    this.eventBus.post(event);

    // process
    if (!event.isCancelled())
        objects.add(event.getPacket());
    else
        getLogger().debug(
                "Ignoring packet with identifier %s (packetID: %s, type: %s): Event has been cancelled.",
                identifier, packetID, packet.getClass());
}

From source file:org.fengbaoxp.netty.official.EchoServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;//w w  w  . j  a va  2s  .c  o  m
    StringBuilder smsg = new StringBuilder();
    while (in.isReadable()) {
        smsg.append((char) in.readByte());
    }
    logger.info(smsg.toString());
    final ByteBuf out = ctx.alloc().buffer();
    out.writeBytes(smsg.toString().getBytes());
    ctx.write(out);
    ctx.flush();
}

From source file:org.fengbaoxp.netty.official.TimeServerHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    final ByteBuf time = ctx.alloc().buffer(4);
    time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L));

    final ChannelFuture f = ctx.writeAndFlush(time);
    f.addListener((future) -> {//from   w  w  w . ja  v  a 2s  . co  m
        assert f == future;
        ctx.close();
    });
}

From source file:org.gameoss.gridcast.p2p.serialization.ProtostuffEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
    if (msg instanceof ByteBuf) {
        // assume already serialized so just pass through
        ByteBuf buf = (ByteBuf) msg;//from  w  w w . j av  a  2s.  c  o m
        out.add(buf.retain());
    } else {
        // serialize
        ByteBuf buf = ctx.alloc().buffer();
        serializeToByteBuf(registry, buf, msg);
        out.add(buf);
    }
}

From source file:org.glowroot.agent.plugin.netty.Http2ServerHandler.java

License:Apache License

@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
        boolean endOfStream) {
    if (endOfStream) {
        ByteBuf content = ctx.alloc().buffer();
        content.writeBytes(CONTENT);// w ww.jav  a  2  s.  c  o m
        sendResponse(ctx, streamId, content);
    }
}

From source file:org.iotivity.cloud.util.CoapLogHandler.java

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {

    if (msg instanceof CoapMessage) {

        CoapMessage coapMessage = (CoapMessage) msg;

        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append(getStringCtx(ctx));
        strBuilder//ww  w  .ja  v a 2s  .  c o m
                .append("\n/******************************************************************************/\n");
        strBuilder.append(getStringCoapMessage(coapMessage));
        strBuilder
                .append("\n/******************************************************************************/\n");
        Logger.d(strBuilder.toString());

    } else if (msg instanceof String) {

        String message = (String) msg;

        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append(getStringCtx(ctx));
        strBuilder
                .append("\n/******************************************************************************/\n");
        strBuilder.append(message);
        strBuilder
                .append("\n/******************************************************************************/\n");
        Logger.d(strBuilder.toString());

        ByteBuf outByteBuf = ctx.alloc().buffer();
        outByteBuf.writeBytes(message.getBytes(StandardCharsets.UTF_8));
    }

    ctx.write(msg);
}

From source file:org.jboss.aerogear.webpush.netty.WebPushHttp11Handler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
    if (HttpUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }/*from w ww .  j  a  v a 2 s. c  o  m*/
    final ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(RESPONSE_BYTES);

    final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

    if (!HttpUtil.isKeepAlive(req)) {
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.writeAndFlush(response);
    }
}

From source file:org.jdiameter.client.impl.transport.tls.netty.StartTlsClientHandler.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from  ww w .j  a  va 2 s.  co  m*/
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.debug("StartTlsClientHandler");
    ByteBuf buf = (ByteBuf) msg;
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), bytes);

    if ("StartTlsResponse".equals(new String(bytes))) {
        logger.debug("received StartTlsResponse");

        SslContext sslContext = SslContextFactory.getSslContextForClient(this.tlsTransportClient.getConfig());
        SSLEngine sslEngine = sslContext.newEngine(ctx.alloc());
        sslEngine.setUseClientMode(true);
        SslHandler sslHandler = new SslHandler(sslEngine, false);

        final ChannelPipeline pipeline = ctx.pipeline();
        pipeline.remove("startTlsClientHandler");
        pipeline.addLast("sslHandler", sslHandler);

        logger.debug("StartTls starting handshake");

        sslHandler.handshakeFuture().addListener(new GenericFutureListener() {
            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()) {
                    logger.debug("StartTls handshake succesfull");

                    tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKEN);

                    logger.debug("restoring all handlers");

                    pipeline.addLast("decoder",
                            new DiameterMessageDecoder(
                                    StartTlsClientHandler.this.tlsTransportClient.getParent(),
                                    StartTlsClientHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("msgHandler", new DiameterMessageHandler(
                            StartTlsClientHandler.this.tlsTransportClient.getParent(), true));

                    pipeline.addLast("encoder", new DiameterMessageEncoder(
                            StartTlsClientHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("inbandWriter", new InbandSecurityHandler());
                }
            }
        });

    }
}

From source file:org.jdiameter.client.impl.transport.tls.netty.StartTlsServerHandler.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from   w  w w. j a  va 2  s .c  om
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.debug("StartTlsServerHandler");
    ByteBuf buf = (ByteBuf) msg;
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), bytes);

    if ("StartTlsRequest".equals(new String(bytes))) {
        logger.debug("Received StartTlsRequest");
        SslContext sslContext = SslContextFactory.getSslContextForServer(this.tlsTransportClient.getConfig());
        SSLEngine sslEngine = sslContext.newEngine(ctx.alloc());
        sslEngine.setUseClientMode(false);
        SslHandler sslHandler = new SslHandler(sslEngine, false);

        final ChannelPipeline pipeline = ctx.pipeline();

        pipeline.remove("decoder");
        pipeline.remove("msgHandler");
        pipeline.remove("encoder");
        pipeline.remove("inbandWriter");
        pipeline.remove(this);

        pipeline.addLast("sslHandler", sslHandler);

        sslHandler.handshakeFuture().addListener(new GenericFutureListener() {

            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()) {
                    logger.debug("StartTls server handshake succesfull");

                    tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKEN);

                    logger.debug("restoring all handlers");

                    pipeline.addLast("decoder",
                            new DiameterMessageDecoder(
                                    StartTlsServerHandler.this.tlsTransportClient.getParent(),
                                    StartTlsServerHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("msgHandler", new DiameterMessageHandler(
                            StartTlsServerHandler.this.tlsTransportClient.getParent(), true));

                    pipeline.addLast("encoder", new DiameterMessageEncoder(
                            StartTlsServerHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("inbandWriter", new InbandSecurityHandler());

                }
            }
        });

        ReferenceCountUtil.release(msg);
        logger.debug("Sending StartTlsResponse");
        ctx.writeAndFlush(Unpooled.wrappedBuffer("StartTlsResponse".getBytes()))
                .addListener(new GenericFutureListener() {

                    @Override
                    public void operationComplete(Future f) throws Exception {
                        if (!f.isSuccess()) {
                            logger.error(f.cause().getMessage(), f.cause());
                        }

                    }
                });
    } else {
        ctx.fireChannelRead(msg);
    }

}

From source file:org.jfxvnc.net.rfb.codec.decoder.rect.RawRectDecoder.java

License:Apache License

@Override
public boolean decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (framebuffer == null) {
        framebuffer = Unpooled.unreleasableBuffer(ctx.alloc().buffer(capacity));
    } else if (framebuffer.capacity() != capacity) {
        framebuffer.capacity(capacity);// w w  w. j  av  a 2 s  . c om
    }

    if (framebuffer.isWritable() && in.isReadable()) {
        logger.trace("readable/writable {}/{}", in.readableBytes(), framebuffer.writableBytes());
        framebuffer.writeBytes(in, Math.min(in.readableBytes(), framebuffer.writableBytes()));
    }
    if (!framebuffer.isWritable()) {
        logger.trace("read {} raw bytes completed", framebuffer.readableBytes());
        sendRect(out);
        framebuffer.clear();
        return true;
    }
    return false;
}