Example usage for io.netty.util ReferenceCountUtil release

List of usage examples for io.netty.util ReferenceCountUtil release

Introduction

In this page you can find the example usage for io.netty.util ReferenceCountUtil release.

Prototype

public static boolean release(Object msg) 

Source Link

Document

Try to call ReferenceCounted#release() if the specified message implements ReferenceCounted .

Usage

From source file:io.netty.example.ocsp.OcspClientExample.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (!OpenSsl.isAvailable()) {
        throw new IllegalStateException("OpenSSL is not available!");
    }/*from   w ww. j  a  va2 s  .c  o  m*/

    if (!OpenSsl.isOcspSupported()) {
        throw new IllegalStateException("OCSP is not supported!");
    }

    // Using Wikipedia as an example. I'd rather use Netty's own website
    // but the server (Cloudflare) doesn't support OCSP stapling. A few
    // other examples could be Microsoft or Squarespace. Use OpenSSL's
    // CLI client to assess if a server supports OCSP stapling. E.g.:
    //
    // openssl s_client -tlsextdebug -status -connect www.squarespace.com:443
    //
    String host = "www.wikipedia.org";

    ReferenceCountedOpenSslContext context = (ReferenceCountedOpenSslContext) SslContextBuilder.forClient()
            .sslProvider(SslProvider.OPENSSL).enableOcsp(true).build();

    try {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Promise<FullHttpResponse> promise = group.next().newPromise();

            Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(group)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5 * 1000)
                    .handler(newClientHandler(context, host, promise));

            Channel channel = bootstrap.connect(host, 443).syncUninterruptibly().channel();

            try {
                FullHttpResponse response = promise.get();
                ReferenceCountUtil.release(response);
            } finally {
                channel.close();
            }
        } finally {
            group.shutdownGracefully();
        }
    } finally {
        context.release();
    }
}

From source file:io.reactivesocket.transport.tcp.ReactiveSocketFrameCodec.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof ByteBuf) {
        try {//ww w  .j a va  2  s .co  m
            buffer.wrap((ByteBuf) msg);
            frame.wrap(buffer, 0);
            ctx.fireChannelRead(frame);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    } else {
        super.channelRead(ctx, msg);
    }
}

From source file:io.reactivex.netty.pipeline.ObservableAdapter.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//from ww w  .  j  a  v a2  s .c  o  m
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (null != bridgedObserver) {
        try {
            bridgedObserver.onNext(msg);
        } catch (ClassCastException cce) {
            bridgedObserver.onError(new RuntimeException("Mismatched message type.", cce));
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}

From source file:io.reactivex.netty.protocol.http.client.ClientRequestResponseConverter.java

License:Apache License

@SuppressWarnings("unchecked")
private void invokeContentOnNext(Object nextObject) {
    try {//from  w ww  . jav a2  s.  c  o  m
        contentSubject.onNext(nextObject);
    } catch (ClassCastException e) {
        contentSubject.onError(e);
    } finally {
        ReferenceCountUtil.release(nextObject);
    }
}

From source file:io.reactivex.netty.protocol.http.server.DefaultErrorResponseGenerator.java

License:Apache License

@Override
public void updateResponse(HttpServerResponse<O> response, Throwable error) {
    response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
    response.getHeaders().set(HttpHeaders.Names.CONTENT_TYPE, "text/html");
    ByteBuf buffer = response.getChannelHandlerContext().alloc().buffer(1024);// 1KB initial length.
    PrintStream printStream = null;
    try {/*from w  w w.  j ava2  s.  co  m*/
        printStream = new PrintStream(new ByteBufOutputStream(buffer));
        error.printStackTrace(printStream);
        String errorPage = ERROR_HTML_TEMPLATE.replace(STACKTRACE_TEMPLATE_VARIABLE,
                buffer.toString(Charset.defaultCharset()));
        response.writeString(errorPage);
    } finally {
        ReferenceCountUtil.release(buffer);
        if (null != printStream) {
            try {
                printStream.flush();
                printStream.close();
            } catch (Exception e) {
                logger.error("Error closing stream for generating error response stacktrace. This is harmless.",
                        e);
            }
        }
    }
}

From source file:io.reactivex.netty.protocol.http.server.ServerRequestResponseConverter.java

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
private static void invokeContentOnNext(Object nextObject, PublishSubject contentSubject) {
    try {// w w w.  j a  v a  2  s. co  m
        contentSubject.onNext(nextObject);
    } catch (ClassCastException e) {
        contentSubject.onError(e);
    } finally {
        ReferenceCountUtil.release(nextObject);
    }
}

From source file:io.scalecube.socketio.pipeline.DisconnectHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        final HttpRequest req = (HttpRequest) msg;
        final HttpMethod requestMethod = req.getMethod();
        final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        final String requestPath = queryDecoder.path();

        boolean disconnect = queryDecoder.parameters().containsKey(DISCONNECT);
        if (disconnect) {
            if (log.isDebugEnabled())
                log.debug("Received HTTP disconnect request: {} {} from channel: {}", requestMethod,
                        requestPath, ctx.channel());

            final String sessionId = PipelineUtils.getSessionId(requestPath);
            final Packet disconnectPacket = new Packet(PacketType.DISCONNECT, sessionId);
            disconnectPacket.setOrigin(PipelineUtils.getOrigin(req));
            ctx.fireChannelRead(disconnectPacket);
            ReferenceCountUtil.release(msg);
            return;
        }/*from w  w  w . j a v  a2  s  .c o m*/
    }
    ctx.fireChannelRead(msg);
}

From source file:io.scalecube.socketio.pipeline.HandshakeHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // //from w ww  .  ja  v a 2s . c  o  m
    if (msg instanceof HttpRequest) {
        final HttpRequest req = (HttpRequest) msg;
        final HttpMethod requestMethod = req.getMethod();
        final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        final String requestPath = queryDecoder.path();

        if (!requestPath.startsWith(handshakePath)) {
            log.warn("Received HTTP bad request: {} {} from channel: {}", requestMethod, requestPath,
                    ctx.channel());

            HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
            ChannelFuture f = ctx.channel().writeAndFlush(res);
            f.addListener(ChannelFutureListener.CLOSE);
            ReferenceCountUtil.release(req);
            return;
        }

        if (HttpMethod.GET.equals(requestMethod) && requestPath.equals(handshakePath)) {
            if (log.isDebugEnabled())
                log.debug("Received HTTP handshake request: {} {} from channel: {}", requestMethod, requestPath,
                        ctx.channel());

            handshake(ctx, req, queryDecoder);
            ReferenceCountUtil.release(req);
            return;
        }
    }

    super.channelRead(ctx, msg);
}

From source file:io.scalecube.socketio.pipeline.JsonpPollingHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ?//from   ww w.ja  v a 2  s  .c  o m
    if (msg instanceof FullHttpRequest) {
        final FullHttpRequest req = (FullHttpRequest) msg;
        final HttpMethod requestMethod = req.getMethod();
        final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        final String requestPath = queryDecoder.path();

        if (requestPath.startsWith(connectPath)) {
            if (log.isDebugEnabled())
                log.debug("Received HTTP JSONP-Polling request: {} {} from channel: {}", requestMethod,
                        requestPath, ctx.channel());

            final String sessionId = PipelineUtils.getSessionId(requestPath);
            final String origin = PipelineUtils.getOrigin(req);

            if (HttpMethod.GET.equals(requestMethod)) {
                // Process polling request from client
                SocketAddress clientIp = PipelineUtils.getHeaderClientIPParamValue(req, remoteAddressHeader);

                String jsonpIndexParam = PipelineUtils.extractParameter(queryDecoder, "i");
                final ConnectPacket packet = new ConnectPacket(sessionId, origin);
                packet.setTransportType(TransportType.JSONP_POLLING);
                packet.setJsonpIndexParam(jsonpIndexParam);
                packet.setRemoteAddress(clientIp);

                ctx.fireChannelRead(packet);
            } else if (HttpMethod.POST.equals(requestMethod)) {
                // Process message request from client
                ByteBuf buffer = req.content();
                String content = buffer.toString(CharsetUtil.UTF_8);
                if (content.startsWith("d=")) {
                    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(content, CharsetUtil.UTF_8,
                            false);
                    content = PipelineUtils.extractParameter(queryStringDecoder, "d");
                    content = preprocessJsonpContent(content);
                    ByteBuf buf = PipelineUtils.copiedBuffer(ctx.alloc(), content);
                    List<Packet> packets = PacketFramer.decodePacketsFrame(buf);
                    buf.release();
                    for (Packet packet : packets) {
                        packet.setSessionId(sessionId);
                        packet.setOrigin(origin);
                        ctx.fireChannelRead(packet);
                    }
                } else {
                    log.warn(
                            "Can't process HTTP JSONP-Polling message. Incorrect content format: {} from channel: {}",
                            content, ctx.channel());
                }
            } else {
                log.warn(
                        "Can't process HTTP JSONP-Polling request. Unknown request method: {} from channel: {}",
                        requestMethod, ctx.channel());
            }
            ReferenceCountUtil.release(msg);
            return;
        }
    }
    super.channelRead(ctx, msg);
}

From source file:io.scalecube.socketio.pipeline.ResourceHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ?//from w w w  . j a  va 2  s.co m
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        String requestPath = queryDecoder.path();
        URL resUrl = resources.get(requestPath);
        if (resUrl != null) {
            if (log.isDebugEnabled())
                log.debug("Received HTTP resource request: {} {} from channel: {}", req.getMethod(),
                        requestPath, ctx.channel());

            URLConnection fileUrl = resUrl.openConnection();
            long lastModified = fileUrl.getLastModified();
            // check if file has been modified since last request
            if (isNotModified(req, lastModified)) {
                sendNotModified(ctx);
                return;
            }
            // create resource input-stream and check existence
            final InputStream is = fileUrl.getInputStream();
            if (is == null) {
                sendError(ctx, HttpResponseStatus.NOT_FOUND);
                return;
            }
            // create ok response
            HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            // set Content-Length header
            HttpHeaders.setContentLength(res, fileUrl.getContentLengthLong());
            // set Content-Type header
            setContentTypeHeader(res, fileUrl);
            // set Date, Expires, Cache-Control and Last-Modified headers
            setDateAndCacheHeaders(res, lastModified);
            // write initial response header
            ctx.write(res);

            // write the content stream
            ctx.pipeline().addBefore(ctx.name(), "chunked-writer-handler", new ChunkedWriteHandler());
            ChannelFuture writeFuture = ctx.writeAndFlush(new ChunkedStream(is, fileUrl.getContentLength()));
            // add operation complete listener so we can close the channel and the input stream
            writeFuture.addListener(ChannelFutureListener.CLOSE);
            ReferenceCountUtil.release(msg);
            return;
        }
    }
    super.channelRead(ctx, msg);
}