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:net.petercashel.nettyCore.common.packetCore.PacketBase.java

License:Apache License

public void sendPacket(ChannelHandlerContext ctx) {
    ByteBuf b = ctx.alloc().buffer(Packet.packetBufSize + Packet.packetHeaderSize,
            Packet.packetBufSize + Packet.packetHeaderSize);
    b.writeInt(PacketRegistry.GetOtherSide());
    b.writeInt(packetID);//from   w w  w  . ja va 2  s . co m
    b.writeBytes(packet);
    if (b.readableBytes() == (Packet.packetBufSize + Packet.packetHeaderSize)) {
        ctx.writeAndFlush(b);
    } else if (b.readableBytes() > (Packet.packetBufSize + Packet.packetHeaderSize)) {
        System.out.println("INVALID PACKET! DISCARDING!");
    } else {
        b.writeZero(b.writableBytes());

        if (b.readableBytes() == (Packet.packetBufSize + Packet.packetHeaderSize)) {
            ctx.writeAndFlush(b);
        } else if (b.readableBytes() > (Packet.packetBufSize + Packet.packetHeaderSize)) {
            System.out.println("INVALID PACKET! DISCARDING!");
        }
    }

}

From source file:net.tomp2p.message.TestMessage.java

License:Apache License

/**
 * Mock Nettys ChannelHandlerContext with the minimal functions.
 * /* w  w w  . j av a  2s.  c om*/
 * @param buf
 *            The buffer to use for decoding
 * @param m2
 *            The message reference to store the result
 * @return The mocked ChannelHandlerContext
 */
@SuppressWarnings("unchecked")
private ChannelHandlerContext mockChannelHandlerContext(final AlternativeCompositeByteBuf buf,
        final AtomicReference<Message> m2) {
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    ByteBufAllocator alloc = mock(ByteBufAllocator.class);
    when(ctx.alloc()).thenReturn(alloc);
    when(alloc.ioBuffer()).thenReturn(buf);

    DatagramChannel dc = mock(DatagramChannel.class);
    when(ctx.channel()).thenReturn(dc);
    when(ctx.writeAndFlush(any(), any(ChannelPromise.class))).thenReturn(null);

    Attribute<InetSocketAddress> attr = mock(Attribute.class);
    when(ctx.attr(any(AttributeKey.class))).thenReturn(attr);

    when(ctx.fireChannelRead(any())).then(new Answer<Void>() {
        @Override
        public Void answer(final InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            m2.set((Message) args[0]);
            return null;
        }
    });

    when(ctx.fireExceptionCaught(any(Throwable.class))).then(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            for (Object obj : args) {
                if (obj instanceof Throwable) {
                    ((Throwable) obj).printStackTrace();
                } else {
                    System.err.println("Err: " + obj);
                }
            }
            return null;
        }

    });

    return ctx;
}

From source file:net.tridentsdk.server.netty.packet.PacketDecrypter.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    ByteBuf bufOut = ctx.alloc().buffer(in.readableBytes());

    if (this.connection.isEncryptionEnabled()) {
        bufOut.writeBytes(this.connection.decrypt(Codec.toArray(in)));
    } else {//from w  w w. j ava 2s  .co m
        bufOut.writeBytes(in);
    }

    out.add(bufOut);
}

From source file:netty.mmb.http2.Server.HelloWorldHttp1Handler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
    if (HttpHeaderUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }/*from  w  ww .  j a  va2  s .c om*/
    boolean keepAlive = HttpHeaderUtil.isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());

    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 (!keepAlive) {
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.writeAndFlush(response);
    }
}

From source file:netty.mmb.http2.Server.Http1Handler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
    //        100Continuehttp://www.cnblogs.com/tekkaman/archive/2013/04/03/2997781.html
    if (HttpHeaderUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }//ww w  .  j  a va2  s .  co  m
    boolean keepAlive = HttpHeaderUtil.isKeepAlive(req);

    //        
    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(Http2Handler.RESPONSE_BYTES.duplicate());

    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 (!keepAlive) {
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        //            ,
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.writeAndFlush(response);
    }
}

From source file:netty.protocol.discard.example.DiscardClientHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    this.ctx = ctx;

    // Initialize the message.
    //        content = ctx.alloc().directBuffer(DiscardClient.SIZE).writeZero(DiscardClient.SIZE);
    String msg = "Hello server!";
    content = ctx.alloc().directBuffer(DiscardClient.SIZE).writeBytes(msg.getBytes());

    // Send the initial messages.
    generateTraffic();/* ww  w.j ava  2 s  .co m*/
}

From source file:netty5.http.server.HelloWorldHttp1Handler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
    if (HttpHeaderUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }//w  ww  . j  a  va2 s  .c  o m
    boolean keepAlive = HttpHeaderUtil.isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());
    ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")");

    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 (!keepAlive) {
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.writeAndFlush(response);
    }
}

From source file:nettyClient4.clientDecoder.java

License:Apache License

/**
 *  is overridden to avoid memory copy.//from   w ww. j a va  2 s .  com
 *  Unpooled ByteBufs?????,
 * ChannelHandlerContext.alloc()Channel.alloc()
 * ??ByteBufAllocator?ByteBuf,?GC
 * @param  buffer
 * @param  index
 * @param  length
 * @param  ctx   ChannelHandlerContext
 * @return
 */
protected ByteBuf extractFrame(ByteBuf buffer, int index, int length, ChannelHandlerContext ctx) {
    ByteBuf frame = ctx.alloc().buffer(length);
    frame.writeBytes(buffer, index, length);
    return frame;
}

From source file:netty_client.TimeClientHandler.java

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

    final ChannelFuture f = ctx.writeAndFlush(time); // (3)
    f.addListener(new ChannelFutureListener() {
        @Override/*from  www. ja  v  a 2 s  . co  m*/
        public void operationComplete(ChannelFuture future) {
            assert f == future;
            ctx.close();
        }
    }); // (4)
}

From source file:openbns.commons.net.codec.sts.HttpObjectDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    switch (state()) {
    case SKIP_CONTROL_CHARS: {
        try {//from ww  w . jav a2  s .c o m
            skipControlCharacters(buffer);
            checkpoint(State.READ_INITIAL);
        } finally {
            checkpoint();
        }
    }
    case READ_INITIAL:
        try {
            String[] initialLine = splitInitialLine(readLine(buffer, maxInitialLineLength));
            if (initialLine.length < 3) {
                // Invalid initial line - ignore.
                checkpoint(State.SKIP_CONTROL_CHARS);
                return;
            }

            message = createMessage(initialLine);
            checkpoint(State.READ_HEADER);
        } catch (Exception e) {
            out.add(invalidMessage(e));
            return;
        }
    case READ_HEADER:
        try {
            State nextState = readHeaders(buffer);
            checkpoint(nextState);
            if (nextState == State.READ_CHUNK_SIZE) {
                if (!chunkedSupported) {
                    throw new IllegalArgumentException("Chunked messages not supported");
                }
                // Chunked encoding - generate StsMessage first.  HttpChunks will follow.
                out.add(message);
                return;
            }
            if (nextState == State.SKIP_CONTROL_CHARS) {
                // No content is expected.
                out.add(message);
                out.add(LastStsContent.EMPTY_LAST_CONTENT);
                reset();
                return;
            }
            long contentLength = contentLength();
            if (contentLength == 0 || contentLength == -1 && isDecodingRequest()) {
                out.add(message);
                out.add(LastStsContent.EMPTY_LAST_CONTENT);
                reset();
                return;
            }

            assert nextState == State.READ_FIXED_LENGTH_CONTENT
                    || nextState == State.READ_VARIABLE_LENGTH_CONTENT;

            out.add(message);

            if (nextState == State.READ_FIXED_LENGTH_CONTENT) {
                // chunkSize will be decreased as the READ_FIXED_LENGTH_CONTENT state reads data chunk by chunk.
                chunkSize = contentLength;
            }

            // We return here, this forces decode to be called again where we will decode the content
            return;
        } catch (Exception e) {
            out.add(invalidMessage(e));
            return;
        }
    case READ_VARIABLE_LENGTH_CONTENT: {
        // Keep reading data as a chunk until the end of connection is reached.
        int toRead = Math.min(actualReadableBytes(), maxChunkSize);
        if (toRead > 0) {
            ByteBuf content = readBytes(ctx.alloc(), buffer, toRead);
            if (buffer.isReadable()) {
                out.add(new DefaultStsContent(content));
            } else {
                // End of connection.
                out.add(new DefaultLastStsContent(content, validateHeaders));
                reset();
            }
        } else if (!buffer.isReadable()) {
            // End of connection.
            out.add(LastStsContent.EMPTY_LAST_CONTENT);
            reset();
        }
        return;
    }
    case READ_FIXED_LENGTH_CONTENT: {
        int readLimit = actualReadableBytes();

        // Check if the buffer is readable first as we use the readable byte count
        // to create the HttpChunk. This is needed as otherwise we may end up with
        // create a HttpChunk instance that contains an empty buffer and so is
        // handled like it is the last HttpChunk.
        //
        // See https://github.com/commons/commons/issues/433
        if (readLimit == 0) {
            return;
        }

        int toRead = Math.min(readLimit, maxChunkSize);
        if (toRead > chunkSize) {
            toRead = (int) chunkSize;
        }
        ByteBuf content = readBytes(ctx.alloc(), buffer, toRead);
        chunkSize -= toRead;

        if (chunkSize == 0) {
            // Read all content.
            out.add(new DefaultLastStsContent(content, validateHeaders));
            reset();
        } else {
            out.add(new DefaultStsContent(content));
        }
        return;
    }
    /**
     * everything else after this point takes care of reading chunked content. basically, read chunk size,
     * read chunk, read and ignore the CRLF and repeat until 0
     */
    case READ_CHUNK_SIZE:
        try {
            AppendableCharSequence line = readLine(buffer, maxInitialLineLength);
            int chunkSize = getChunkSize(line.toString());
            this.chunkSize = chunkSize;
            if (chunkSize == 0) {
                checkpoint(State.READ_CHUNK_FOOTER);
                return;
            } else {
                checkpoint(State.READ_CHUNKED_CONTENT);
            }
        } catch (Exception e) {
            out.add(invalidChunk(e));
            return;
        }
    case READ_CHUNKED_CONTENT: {
        assert chunkSize <= Integer.MAX_VALUE;
        int toRead = Math.min((int) chunkSize, maxChunkSize);

        StsContent chunk = new DefaultStsContent(readBytes(ctx.alloc(), buffer, toRead));
        chunkSize -= toRead;

        out.add(chunk);

        if (chunkSize == 0) {
            // Read all content.
            checkpoint(State.READ_CHUNK_DELIMITER);
        } else {
            return;
        }
    }
    case READ_CHUNK_DELIMITER: {
        for (;;) {
            byte next = buffer.readByte();
            if (next == StsConstants.CR) {
                if (buffer.readByte() == StsConstants.LF) {
                    checkpoint(State.READ_CHUNK_SIZE);
                    return;
                }
            } else if (next == StsConstants.LF) {
                checkpoint(State.READ_CHUNK_SIZE);
                return;
            } else {
                checkpoint();
            }
        }
    }
    case READ_CHUNK_FOOTER:
        try {
            LastStsContent trailer = readTrailingHeaders(buffer);
            out.add(trailer);
            reset();
            return;
        } catch (Exception e) {
            out.add(invalidChunk(e));
            return;
        }
    case BAD_MESSAGE: {
        // Keep discarding until disconnection.
        buffer.skipBytes(actualReadableBytes());
        break;
    }
    case UPGRADED: {
        // Do not touch anything read - other handler will replace this codec with the upgraded protocol codec to
        // take the trafic over.
        break;
    }
    }
}