Example usage for io.netty.buffer Unpooled unreleasableBuffer

List of usage examples for io.netty.buffer Unpooled unreleasableBuffer

Introduction

In this page you can find the example usage for io.netty.buffer Unpooled unreleasableBuffer.

Prototype

public static ByteBuf unreleasableBuffer(ByteBuf buf) 

Source Link

Document

Return a unreleasable view on the given ByteBuf which will just ignore release and retain calls.

Usage

From source file:io.jsync.http.impl.ws.DefaultWebSocketFrame.java

License:Open Source License

/**
 * Creates a new frame with the specified frame type and the specified data.
 *
 * @param type         the type of the frame. {@code 0} is the only allowed type currently.
 * @param binaryData   the content of the frame.  If <tt>(type &amp; 0x80 == 0)</tt>,
 *                     it must be encoded in UTF-8.
 * @param isFinalFrame If this is the final frame in a sequence
 * @throws IllegalArgumentException if If <tt>(type &amp; 0x80 == 0)</tt> and the data is not encoded
 *                                  in UTF-8
 *//*from  ww w.ja  v a  2  s.c  om*/
public DefaultWebSocketFrame(FrameType type, ByteBuf binaryData, boolean isFinalFrame) {
    this.type = type;
    this.isFinalFrame = isFinalFrame;
    this.binaryData = Unpooled.unreleasableBuffer(binaryData);
}

From source file:io.vertx.benchmarks.HttpServerHandlerBenchmark.java

License:Open Source License

@Setup
public void setup() {
    vertx = (VertxInternal) Vertx.vertx();
    HttpServerOptions options = new HttpServerOptions();
    vertxChannel = new EmbeddedChannel(
            new HttpRequestDecoder(options.getMaxInitialLineLength(), options.getMaxHeaderSize(),
                    options.getMaxChunkSize(), false, options.getDecoderInitialBufferSize()),
            new HttpResponseEncoder());
    vertxChannel.config().setAllocator(new Alloc());

    ContextInternal context = new EventLoopContext(vertx, vertxChannel.eventLoop(), null, null, null,
            new JsonObject(), Thread.currentThread().getContextClassLoader());
    Handler<HttpServerRequest> app = request -> {
        HttpServerResponse response = request.response();
        MultiMap headers = response.headers();
        headers.add(HEADER_CONTENT_TYPE, RESPONSE_TYPE_PLAIN).add(HEADER_SERVER, SERVER)
                .add(HEADER_DATE, DATE_STRING).add(HEADER_CONTENT_LENGTH, HELLO_WORLD_LENGTH);
        response.end(HELLO_WORLD_BUFFER);
    };/*from   w  ww .  j  a v  a 2s  . co m*/
    HandlerHolder<HttpHandlers> holder = new HandlerHolder<>(context, new HttpHandlers(app, null, null, null));
    Http1xServerHandler handler = new Http1xServerHandler(null, new HttpServerOptions(), "localhost", holder,
            null);
    vertxChannel.pipeline().addLast("handler", handler);

    nettyChannel = new EmbeddedChannel(
            new HttpRequestDecoder(options.getMaxInitialLineLength(), options.getMaxHeaderSize(),
                    options.getMaxChunkSize(), false, options.getDecoderInitialBufferSize()),
            new HttpResponseEncoder(), new SimpleChannelInboundHandler<HttpRequest>() {

                private final byte[] STATIC_PLAINTEXT = "Hello, World!".getBytes(CharsetUtil.UTF_8);
                private final int STATIC_PLAINTEXT_LEN = STATIC_PLAINTEXT.length;
                private final ByteBuf PLAINTEXT_CONTENT_BUFFER = Unpooled
                        .unreleasableBuffer(Unpooled.directBuffer().writeBytes(STATIC_PLAINTEXT));
                private final CharSequence PLAINTEXT_CLHEADER_VALUE = new AsciiString(
                        String.valueOf(STATIC_PLAINTEXT_LEN));

                private final CharSequence TYPE_PLAIN = new AsciiString("text/plain");
                private final CharSequence SERVER_NAME = new AsciiString("Netty");
                private final CharSequence CONTENT_TYPE_ENTITY = HttpHeaderNames.CONTENT_TYPE;
                private final CharSequence DATE_ENTITY = HttpHeaderNames.DATE;
                private final CharSequence CONTENT_LENGTH_ENTITY = HttpHeaderNames.CONTENT_LENGTH;
                private final CharSequence SERVER_ENTITY = HttpHeaderNames.SERVER;

                private final DateFormat FORMAT = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
                private final CharSequence date = new AsciiString(FORMAT.format(new Date()));

                @Override
                protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
                    writeResponse(ctx, msg, PLAINTEXT_CONTENT_BUFFER.duplicate(), TYPE_PLAIN,
                            PLAINTEXT_CLHEADER_VALUE);
                }

                @Override
                public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                    ctx.flush();
                }

                private void writeResponse(ChannelHandlerContext ctx, HttpRequest request, ByteBuf buf,
                        CharSequence contentType, CharSequence contentLength) {

                    // Build the response object.
                    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                            HttpResponseStatus.OK, buf, false);
                    HttpHeaders headers = response.headers();
                    headers.set(CONTENT_TYPE_ENTITY, contentType);
                    headers.set(SERVER_ENTITY, SERVER_NAME);
                    headers.set(DATE_ENTITY, date);
                    headers.set(CONTENT_LENGTH_ENTITY, contentLength);

                    // Close the non-keep-alive connection after the write operation is done.
                    ctx.write(response, ctx.voidPromise());
                }
            });
    nettyChannel.config().setAllocator(new Alloc());

    GET = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(("GET / HTTP/1.1\r\n" + "\r\n").getBytes()));
    readerIndex = GET.readerIndex();
    writeIndex = GET.writerIndex();
}

From source file:org.apache.activemq.artemis.core.buffers.impl.ChannelBufferWrapper.java

License:Apache License

public ChannelBufferWrapper(final ByteBuf buffer, boolean releasable) {
    if (!releasable) {
        this.buffer = Unpooled.unreleasableBuffer(buffer);
    } else {//from  ww w.j a  v a  2 s  .  com
        this.buffer = buffer;
    }
    this.releasable = releasable;
}

From source file:org.apache.giraph.utils.DynamicChannelBufferOutputStream.java

License:Apache License

/**
 * Constructor/*from  w w  w .  j  av  a  2s.  c  o m*/
 *
 * @param estimatedLength Estimated length of the buffer
 */
public DynamicChannelBufferOutputStream(int estimatedLength) {
    buffer = Unpooled.unreleasableBuffer(Unpooled.buffer(estimatedLength)).order(ByteOrder.LITTLE_ENDIAN);
    // -- TODO unresolved what are benefits of using releasable?
    // currently nit because it is just used in 1 test file
}

From source file:org.hornetq.utils.ChannelBufferWrapperTest.java

License:Apache License

@Test
public void testUnwrap() {
    ByteBuf buff = UnpooledByteBufAllocator.DEFAULT.heapBuffer(100);

    ByteBuf wrapped = buff;//from w  w  w  . j  a v a  2  s.c o  m

    for (int i = 0; i < 10; i++) {
        wrapped = Unpooled.unreleasableBuffer(wrapped);
    }

    // If this starts to loop forever it means that Netty has changed
    // the semantic of Unwrap call and it's returning itself
    Assert.assertEquals(buff, ChannelBufferWrapper.unwrap(wrapped));

    // does it work with itself as well?
    Assert.assertEquals(buff, ChannelBufferWrapper.unwrap(buff));
}

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  a2  s  .  c o  m
    }

    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;
}

From source file:ratpack.session.internal.LocalMemorySessionStore.java

License:Apache License

@Override
public Promise<ByteBuf> load(AsciiString sessionId) {
    return Promise.sync(() -> {
        maybeCleanup();//from  w  ww . j av  a 2s . co m
        ByteBuf value = cache.getIfPresent(sessionId);
        if (value != null) {
            return Unpooled.unreleasableBuffer(value.slice());
        } else {
            return Unpooled.EMPTY_BUFFER;
        }
    });
}

From source file:ratpack.session.store.internal.LocalMemorySessionStoreAdapter.java

License:Apache License

@Override
public Promise<ByteBuf> load(SessionId sessionId, ByteBufAllocator bufferAllocator) {
    return execControl.promiseFrom(() -> {
        ByteBuf value = cache.getIfPresent(sessionId.getValue());
        if (value != null) {
            return Unpooled.unreleasableBuffer(value);
        } else {/*from  w  w  w .  ja  va2s .c o  m*/
            return Unpooled.buffer(0, 0);
        }
    });
}