Example usage for io.netty.channel ChannelHandlerContext pipeline

List of usage examples for io.netty.channel ChannelHandlerContext pipeline

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext pipeline.

Prototype

ChannelPipeline pipeline();

Source Link

Document

Return the assigned ChannelPipeline

Usage

From source file:io.reactivex.netty.channel.ObservableConnection.java

License:Apache License

public ObservableConnection(final ChannelHandlerContext ctx, MetricEventsSubject<?> eventsSubject,
        ChannelMetricEventProvider metricEventProvider) {
    super(ctx, eventsSubject, metricEventProvider);
    this.eventsSubject = eventsSubject;
    this.metricEventProvider = metricEventProvider;
    inputSubject = PublishSubject.create();
    ChannelHandlerContext firstContext = ctx.pipeline().firstContext();
    firstContext.fireUserEventTriggered(new NewRxConnectionEvent(inputSubject));
}

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

License:Apache License

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    super.channelReadComplete(ctx);
    ctx.pipeline().flush(); // If there is nothing to flush, this is a short-circuit in netty.
}

From source file:io.reactivex.netty.protocol.http.websocket.WebSocketClientHandler.java

License:Apache License

private void finishHandshake(ChannelHandlerContext ctx, FullHttpResponse msg, Channel ch) {
    try {/*  w ww .  ja  v a2s .  com*/
        handshaker.finishHandshake(ch, msg);
    } catch (WebSocketHandshakeException e) {
        eventsSubject.onEvent(WebSocketClientMetricsEvent.HANDSHAKE_FAILURE,
                Clock.onEndMillis(handshakeStartTime));
        handshakeFuture.setFailure(e);
        ctx.close();
        return;
    }
    eventsSubject.onEvent(WebSocketClientMetricsEvent.HANDSHAKE_SUCCESS, Clock.onEndMillis(handshakeStartTime));

    ChannelPipeline p = ctx.pipeline();
    ChannelHandlerContext nettyDecoderCtx = p.context(WebSocketFrameDecoder.class);
    p.addAfter(nettyDecoderCtx.name(), "websocket-read-metrics", new ClientReadMetricsHandler(eventsSubject));
    ChannelHandlerContext nettyEncoderCtx = p.context(WebSocketFrameEncoder.class);
    p.addAfter(nettyEncoderCtx.name(), "websocket-write-metrics", new ClientWriteMetricsHandler(eventsSubject));
    if (messageAggregation) {
        p.addAfter("websocket-read-metrics", "websocket-frame-aggregator",
                new WebSocketFrameAggregator(maxFramePayloadLength));
    }
    p.remove(HttpObjectAggregator.class);
    p.remove(this);

    handshakeFuture.setSuccess();
}

From source file:io.reactivex.netty.protocol.http.websocket.WebSocketServerHandler.java

License:Apache License

private void updatePipeline(ChannelHandlerContext ctx) {
    ChannelPipeline p = ctx.pipeline();
    ChannelHandlerContext nettyEncoderCtx = p.context(WebSocketFrameEncoder.class);
    p.addAfter(nettyEncoderCtx.name(), "websocket-write-metrics", new ServerWriteMetricsHandler(eventsSubject));
    ChannelHandlerContext nettyDecoderCtx = p.context(WebSocketFrameDecoder.class);
    p.addAfter(nettyDecoderCtx.name(), "websocket-read-metrics", new ServerReadMetricsHandler(eventsSubject));
    if (messageAggregator) {
        p.addAfter("websocket-read-metrics", "websocket-frame-aggregator",
                new WebSocketFrameAggregator(maxFramePayloadLength));
    }/*  w w w.  j a  va 2  s  . c om*/
    p.remove(this);
}

From source file:io.reactivex.netty.server.ConnectionLifecycleHandler.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    super.userEventTriggered(ctx, evt);
    if (evt instanceof SslHandshakeCompletionEvent) {
        final long startTimeMillis = Clock.newStartTimeMillis();
        connection = connectionFactory.newConnection(ctx.pipeline().lastContext());
        handleConnection(startTimeMillis);
    }//from  ww w .  j a  va 2s.  c om
}

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

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ?//www. j a  v  a  2s .  c  om
    if (msg instanceof ByteBuf) {
        ByteBuf message = (ByteBuf) msg;
        if (message.readableBytes() >= policyRequestBuffer.readableBytes()) {
            ByteBuf data = message.slice(0, policyRequestBuffer.readableBytes());
            if (data.equals(policyRequestBuffer)) {
                // Remove SSL handler from pipeline otherwise on channel close SSL handler
                // will fail all pending writes instead of flushing them and as a result
                // client won't get flash policy file.
                if (ctx.pipeline().get(SocketIOChannelInitializer.SSL_HANDLER) != null) {
                    ctx.pipeline().remove(SocketIOChannelInitializer.SSL_HANDLER);
                }

                // Send flash policy file and close connection
                ByteBuf response = PipelineUtils.copiedBuffer(ctx.alloc(), policyResponse);
                ChannelFuture f = ctx.writeAndFlush(response);
                f.addListener(ChannelFutureListener.CLOSE);
                if (log.isDebugEnabled())
                    log.debug("Sent flash policy file to channel: {}", ctx.channel());
                message.release();
                return;
            }
        }
        ctx.pipeline().remove(this);
    }
    ctx.fireChannelRead(msg);
}

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

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ?/*  w w  w .j  a v  a  2  s.com*/
    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);
}

From source file:io.termd.core.http.netty.TtyWebSocketFrameHandler.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
        ctx.pipeline().remove(HttpRequestHandler.class);
        group.add(ctx.channel());/*  ww w. j  a v a  2  s .c o m*/
        conn = new HttpTtyConnection() {
            @Override
            protected void write(byte[] buffer) {
                ByteBuf byteBuf = Unpooled.buffer();
                byteBuf.writeBytes(buffer);
                context.writeAndFlush(new TextWebSocketFrame(byteBuf));
            }

            @Override
            public void schedule(Runnable task, long delay, TimeUnit unit) {
                context.executor().schedule(task, delay, unit);
            }

            @Override
            public void execute(Runnable task) {
                context.executor().execute(task);
            }

            @Override
            public void close() {
                context.close();
            }
        };
        handler.accept(conn);
    } else {
        super.userEventTriggered(ctx, evt);
    }
}

From source file:io.undertow.websockets.utils.WebSocketTestClient.java

License:Open Source License

/**
 * Send the WebSocketFrame and call the FrameListener once a frame was received as response or
 * when an Exception was caught.//from w  ww.j  a  v a 2s . com
 */
public WebSocketTestClient send(WebSocketFrame frame, final FrameListener listener) {
    ch.pipeline().addLast("responseHandler" + count.incrementAndGet(),
            new SimpleChannelInboundHandler<Object>() {

                @Override
                protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (msg instanceof CloseWebSocketFrame) {
                        closed = true;
                    }
                    listener.onFrame((WebSocketFrame) msg);
                    ctx.pipeline().remove(this);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    cause.printStackTrace();
                    listener.onError(cause);
                    ctx.pipeline().remove(this);
                }
            });
    ChannelFuture cf = ch.writeAndFlush(frame).syncUninterruptibly();
    if (!cf.isSuccess()) {
        listener.onError(cf.cause());
    }
    return this;
}

From source file:io.urmia.api.handler.RestApiHandler.java

License:Open Source License

private void setupProxyToPUT(final ChannelHandlerContext ctx, final ObjectRequest objectRequest)
        throws Exception {

    final List<ServiceInstance<NodeType>> st;
    final Optional<FullObjectName> fon;

    if (objectRequest.isLink()) {
        fon = findByName(objectRequest.getLinkLocation());

        if (fon.isPresent()) {
            st = findAllStorageInstanceUp(mds.storedNodes(fon.get().attributes.etag));
            log.info("LINK proxy storage node: {}, for {} -> {}", st, objectRequest,
                    objectRequest.getLinkLocation());
        } else {//from   w  ww . j a  v a  2 s.co m
            st = Collections.emptyList();
        }
    } else {
        fon = Optional.absent();

        st = ns.suggestStorage(objectRequest.getDurability());
        log.info("PUT proxy storage node: {}, download mode: {}, durability: {}", st, false,
                objectRequest.getDurability());
    }

    if (st.isEmpty())
        throw new Exception("not found instances for PUT: " + objectRequest);

    HttpProxyFrontendHandler proxy = new HttpProxyFrontendHandler(st, mds, httpRequest, ctx, false, fon);

    ctx.pipeline().addLast("proxy", proxy);

    proxyMode = true;

    //ctx.read(); // commented to mln

}