Example usage for io.netty.buffer ByteBuf release

List of usage examples for io.netty.buffer ByteBuf release

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf release.

Prototype

boolean release();

Source Link

Document

Decreases the reference count by 1 and deallocates this object if the reference count reaches at 0 .

Usage

From source file:com.informatica.surf.sources.http.HttpListener.java

License:Apache License

public byte[] nextMessage() throws InterruptedException {
    _logger.debug("Checking queued messages");
    ByteBuf buf = _messageQueue.take();
    byte b[] = new byte[buf.readableBytes()];
    _logger.debug("Readable bytes = {}", b.length);
    buf.readBytes(b);/*  w w w .  j  a va  2s. c o  m*/
    buf.release();

    return b;
}

From source file:com.informatica.surf.sources.http.HttpServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*from  ww w.  j a v  a 2 s .  c  o  m*/
        buf.release();
        setContentLength(res, res.content().readableBytes());
    } else {
        setContentLength(res, 0);
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.jjneko.jjnet.networking.http.server.WebSocketHttpServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.status().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);//from ww w.  j a va 2  s  . c  om
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.jjzhk.Chapter11.websocket.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // ?????/*from ww w  .ja  v a  2 s. co  m*/
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        setContentLength(res, res.content().readableBytes());
    }

    // ??Keep-Alive?
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.king.platform.net.http.netty.response.HttpClientResponseHandler.java

License:Apache License

public void handleResponse(ChannelHandlerContext ctx, Object msg) throws Exception {
    HttpRequestContext httpRequestContext = ctx.channel().attr(HttpRequestContext.HTTP_REQUEST_ATTRIBUTE_KEY)
            .get();//w  w w  .j a  v a 2s  .  co m

    if (httpRequestContext == null) {
        logger.trace("httpRequestContext is null, msg was {}", msg);
        return;
    }

    NettyHttpClientResponse nettyHttpClientResponse = httpRequestContext.getNettyHttpClientResponse();

    RequestEventBus requestEventBus = nettyHttpClientResponse.getRequestEventBus();

    ResponseBodyConsumer responseBodyConsumer = nettyHttpClientResponse.getResponseBodyConsumer();

    try {

        if (msg instanceof HttpResponse) {
            requestEventBus.triggerEvent(Event.TOUCH);

            logger.trace("read HttpResponse");
            HttpResponse response = (HttpResponse) msg;

            HttpResponseStatus httpResponseStatus = response.getStatus();
            HttpHeaders httpHeaders = response.headers();

            nettyHttpClientResponse.setHttpResponseStatus(httpResponseStatus);
            nettyHttpClientResponse.setHttpHeaders(httpHeaders);

            requestEventBus.triggerEvent(Event.onReceivedStatus, httpResponseStatus);
            requestEventBus.triggerEvent(Event.onReceivedHeaders, httpHeaders);

            httpRequestContext.getTimeRecorder().readResponseHttpHeaders();

            if (httpRequestContext.isFollowRedirects()
                    && httpRedirector.isRedirectResponse(httpResponseStatus)) {
                httpRedirector.redirectRequest(httpRequestContext, httpHeaders);
                return;
            }

            if (response.getStatus().code() == 100) {
                requestEventBus.triggerEvent(Event.WRITE_BODY, ctx);
                return;
            }

            String contentLength = httpHeaders.get(HttpHeaders.Names.CONTENT_LENGTH);

            String contentType = httpHeaders.get(HttpHeaders.Names.CONTENT_TYPE);
            String charset = StringUtil.substringAfter(contentType, '=');
            if (charset == null) {
                charset = StandardCharsets.ISO_8859_1.name();
            }

            contentType = StringUtil.substringBefore(contentType, ';');

            if (contentLength != null) {
                long length = Long.parseLong(contentLength);
                responseBodyConsumer.onBodyStart(contentType, charset, length);
            } else {
                responseBodyConsumer.onBodyStart(contentType, charset, 0);
            }

            httpRequestContext.getTimeRecorder().responseBodyStart();

        } else if (msg instanceof HttpContent) {
            logger.trace("read HttpContent");
            requestEventBus.triggerEvent(Event.TOUCH);

            HttpResponseStatus httpResponseStatus = nettyHttpClientResponse.getHttpResponseStatus();
            HttpHeaders httpHeaders = nettyHttpClientResponse.getHttpHeaders();

            if (httpResponseStatus == null || (httpRequestContext.isFollowRedirects()
                    && httpRedirector.isRedirectResponse(httpResponseStatus))) {
                return;
            }

            if (msg == LastHttpContent.EMPTY_LAST_CONTENT
                    && nettyHttpClientResponse.getHttpResponseStatus().code() == 100) {
                logger.trace("read EMPTY_LAST_CONTENT with status code 100");
                return;
            }

            HttpContent chunk = (HttpContent) msg;

            ByteBuf content = chunk.content();

            content.resetReaderIndex();

            int readableBytes = content.readableBytes();

            if (readableBytes > 0) {
                ByteBuffer byteBuffer = content.nioBuffer();

                responseBodyConsumer.onReceivedContentPart(byteBuffer);
                requestEventBus.triggerEvent(Event.onReceivedContentPart, readableBytes, content);

            }

            content.release();

            requestEventBus.triggerEvent(Event.TOUCH);

            if (chunk instanceof LastHttpContent) {

                responseBodyConsumer.onCompletedBody();

                requestEventBus.triggerEvent(Event.onReceivedCompleted, httpResponseStatus, httpHeaders);
                httpRequestContext.getTimeRecorder().responseBodyCompleted();

                com.king.platform.net.http.HttpResponse httpResponse = new com.king.platform.net.http.HttpResponse(
                        httpResponseStatus.code(), responseBodyConsumer);

                for (Map.Entry<String, String> entry : httpHeaders.entries()) {
                    httpResponse.addHeader(entry.getKey(), entry.getValue());
                }

                requestEventBus.triggerEvent(Event.onHttpResponseDone, httpResponse);

                requestEventBus.triggerEvent(Event.COMPLETED, httpRequestContext);

            }
        }
    } catch (Throwable e) {
        requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, e);
    }
}

From source file:com.kixeye.kixmpp.client.KixmppClient.java

License:Apache License

/**
 * Performs auth.//from  w w  w . ja v  a  2s  . c  o m
 */
private void performAuth() {
    byte[] authToken = ("\0" + jid.getNode() + "\0" + password).getBytes(StandardCharsets.UTF_8);

    Element auth = new Element("auth", "urn:ietf:params:xml:ns:xmpp-sasl");
    auth.setAttribute("mechanism", "PLAIN");

    ByteBuf rawCredentials = channel.get().alloc().buffer().writeBytes(authToken);
    ByteBuf encodedCredentials = Base64.encode(rawCredentials);
    String encodedCredentialsString = encodedCredentials.toString(StandardCharsets.UTF_8);
    encodedCredentials.release();
    rawCredentials.release();

    auth.setText(encodedCredentialsString);

    channel.get().writeAndFlush(auth);
}

From source file:com.lambdaworks.redis.protocol.CommandArgs.java

License:Apache License

@Override
public String toString() {

    final StringBuilder sb = new StringBuilder();
    sb.append(getClass().getSimpleName());

    ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.buffer(singularArguments.size() * 10);
    encode(buffer);//from   ww w .j a v  a2  s .  c  om
    buffer.resetReaderIndex();

    byte[] bytes = new byte[buffer.readableBytes()];
    buffer.readBytes(bytes);
    sb.append(" [buffer=").append(new String(bytes));
    sb.append(']');
    buffer.release();

    return sb.toString();
}

From source file:com.liferay.sync.engine.lan.server.file.SyncChunkedFile.java

License:Open Source License

@Override
public ByteBuf readChunk(ByteBufAllocator byteBufAllocator) throws Exception {

    long offset = _offset;

    if (offset >= _endOffset) {
        return null;
    }/*from  ww w .  j a  v a  2s . c o  m*/

    int chunkSize = (int) Math.min((long) _chunkSize, _endOffset - offset);

    ByteBuf byteBuf = byteBufAllocator.buffer(chunkSize);

    boolean release = true;

    try {
        FileTime currentFileTime = Files.getLastModifiedTime(_path, LinkOption.NOFOLLOW_LINKS);

        long currentTime = currentFileTime.toMillis();

        if (currentTime != _modifiedTime) {
            throw new Exception("File modified during transfer: " + _path);
        }

        int bytesRead = 0;

        if (_closeAggressively || (_fileChannel == null)) {
            _fileChannel = FileChannel.open(_path);

            _fileChannel.position(_offset);
        }

        while (true) {
            int localBytesRead = byteBuf.writeBytes(_fileChannel, chunkSize - bytesRead);

            if (localBytesRead >= 0) {
                bytesRead += localBytesRead;

                if (bytesRead != chunkSize) {
                    continue;
                }
            }

            _offset += bytesRead;

            release = false;

            return byteBuf;
        }
    } finally {
        if (_closeAggressively && (_fileChannel != null)) {
            _fileChannel.close();
        }

        if (release) {
            byteBuf.release();
        }
    }
}

From source file:com.linecorp.armeria.client.encoding.ZlibStreamDecoder.java

License:Apache License

private byte[] fetchDecoderOutput() {
    CompositeByteBuf decoded = Unpooled.compositeBuffer();
    for (;;) {//from www. j  a  v a2s. c o  m
        ByteBuf buf = decoder.readInbound();
        if (buf == null) {
            break;
        }
        if (!buf.isReadable()) {
            buf.release();
            continue;
        }
        decoded.addComponent(true, buf);
    }
    byte[] ret = ByteBufUtil.getBytes(decoded);
    decoded.release();
    return ret;
}

From source file:com.linecorp.armeria.client.Http2ClientSettingsTest.java

License:Apache License

@Test
public void maxFrameSize() throws Exception {

    try (ServerSocket ss = new ServerSocket(0)) {
        final int port = ss.getLocalPort();

        final ClientFactory clientFactory = new ClientFactoryBuilder().useHttp2Preface(true)
                .http2MaxFrameSize(DEFAULT_MAX_FRAME_SIZE * 2) // == 16384 * 2
                .build();//w  w w  .jav a  2s .c o  m

        final HttpClient client = HttpClient.of(clientFactory, "http://127.0.0.1:" + port);
        final CompletableFuture<AggregatedHttpMessage> future = client.get("/").aggregate();

        try (Socket s = ss.accept()) {
            final InputStream in = s.getInputStream();
            final BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());

            readBytes(in, connectionPrefaceBuf().capacity()); // Read the connection preface and discard it.

            // Read a SETTINGS frame and validate it.
            assertSettingsFrameOfMaxFrameSize(in);

            sendEmptySettingsAndAckFrame(bos);

            readBytes(in, 9); // Read a SETTINGS_ACK frame and discard it.
            readHeadersFrame(in); // Read a HEADERS frame and discard it.

            sendHeaderFrame(bos);

            ////////////////////////////////////////
            // Transmission of data gets started. //
            ////////////////////////////////////////

            // Send a DATA frame that indicates sending data as much as 0x8000 for stream id 03.
            bos.write(new byte[] { 0x00, (byte) 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03 });
            bos.write(EMPTY_DATA);
            bos.write(EMPTY_DATA);
            bos.flush();

            readBytes(in, 13); // Read a WINDOW_UPDATE frame for connection and discard it.
            readBytes(in, 13); // Read a WINDOW_UPDATE frame for stream id 03 and discard it.

            // Send a DATA frame that exceed MAX_FRAME_SIZE by 1.
            bos.write(new byte[] { 0x00, (byte) 0x80, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03 });
            bos.flush(); // Triggers the client to send a GOAWAY frame for the connection.

            // The client send a GOAWAY frame and the server read it.
            final ByteBuf buffer = readGoAwayFrame(in);
            final DefaultHttp2FrameReader frameReader = new DefaultHttp2FrameReader();

            final CountDownLatch latch = new CountDownLatch(1);
            frameReader.readFrame(null, buffer, new Http2EventAdapter() {
                @Override
                public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode,
                        ByteBuf debugData) throws Http2Exception {
                    assertThat(lastStreamId).isZero(); // 0: connection error
                    assertThat(errorCode).isEqualTo(Http2Error.FRAME_SIZE_ERROR.code());
                    latch.countDown();
                }
            });
            latch.await();
            buffer.release();
        }
    }
}