Example usage for io.netty.channel ChannelPipeline get

List of usage examples for io.netty.channel ChannelPipeline get

Introduction

In this page you can find the example usage for io.netty.channel ChannelPipeline get.

Prototype

<T extends ChannelHandler> T get(Class<T> handlerType);

Source Link

Document

Returns the ChannelHandler of the specified type in this pipeline.

Usage

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.handler.SaslAndHMACAuthenticationHandlerTest.java

License:Apache License

@Test
public void testHttpChannelReadWhenAuthenticatorHasNotBeenAdded() throws Exception {
    final HMACAuthenticator hmacAuth = createMock(HMACAuthenticator.class);
    final SaslAndHMACAuthenticator authenticator = createMock(SaslAndHMACAuthenticator.class);
    final ChannelHandlerContext ctx = createMock(ChannelHandlerContext.class);
    final ChannelPipeline pipeline = createMock(ChannelPipeline.class);
    final HttpMessage msg = createMock(HttpMessage.class);
    final HttpHeaders headers = createMock(HttpHeaders.class);

    expect(authenticator.getHMACAuthenticator()).andReturn(hmacAuth);
    expect(authenticator.getSimpleAuthenticator()).andReturn(createMock(JanusGraphSimpleAuthenticator.class));
    expect(ctx.pipeline()).andReturn(pipeline).times(2);
    expect(pipeline.get("hmac_authenticator")).andReturn(null);
    expect(pipeline.addAfter(eq(PIPELINE_AUTHENTICATOR), eq("hmac_authenticator"), isA(ChannelHandler.class)))
            .andReturn(null);/*from   www.  java  2  s. c  o m*/
    expect(msg.headers()).andReturn(headers).times(2);
    expect(headers.get(isA(String.class))).andReturn(null).times(2);
    expect(ctx.fireChannelRead(eq(msg))).andReturn(ctx);
    replayAll();

    final SaslAndHMACAuthenticationHandler handler = new SaslAndHMACAuthenticationHandler(authenticator, null);
    handler.channelRead(ctx, msg);
}

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.handler.SaslAndHMACAuthenticationHandlerTest.java

License:Apache License

@Test
public void testHttpChannelReadWhenAuthenticatorHasBeenAdded() throws Exception {
    final SaslAndHMACAuthenticator authenticator = createMock(SaslAndHMACAuthenticator.class);
    final HMACAuthenticator hmacAuth = createMock(HMACAuthenticator.class);
    final ChannelHandlerContext ctx = createMock(ChannelHandlerContext.class);
    final ChannelHandler mockHandler = createMock(ChannelHandler.class);
    final ChannelPipeline pipeline = createMock(ChannelPipeline.class);
    final HttpMessage msg = createMock(HttpMessage.class);
    final HttpHeaders headers = createMock(HttpHeaders.class);

    expect(authenticator.getHMACAuthenticator()).andReturn(hmacAuth);
    expect(authenticator.getSimpleAuthenticator()).andReturn(createMock(JanusGraphSimpleAuthenticator.class));
    expect(ctx.pipeline()).andReturn(pipeline);
    expect(pipeline.get("hmac_authenticator")).andReturn(mockHandler);
    expect(msg.headers()).andReturn(headers).times(2);
    expect(headers.get(isA(String.class))).andReturn(null).times(2);
    expect(ctx.fireChannelRead(eq(msg))).andReturn(ctx);
    replayAll();//w w w.j a  v a  2  s .  co  m

    final SaslAndHMACAuthenticationHandler handler = new SaslAndHMACAuthenticationHandler(authenticator, null);
    handler.channelRead(ctx, msg);
}

From source file:org.jfxvnc.net.rfb.codec.ProtocolHandler.java

License:Apache License

@Override
public void handlerAdded(ChannelHandlerContext ctx) {
    ChannelPipeline cp = ctx.pipeline();
    if (cp.get(ProtocolHandshakeHandler.class) == null) {
        cp.addBefore(ctx.name(), "rfb-handshake-handler", new ProtocolHandshakeHandler(config));
    }/*from w  ww.j av  a 2  s.c o m*/
}

From source file:org.jooby.internal.netty.NettyResponse.java

License:Apache License

@Override
public void send(final FileChannel channel, final long offset, final long count) throws Exception {
    DefaultHttpResponse rsp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
    if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
        headers.remove(HttpHeaderNames.TRANSFER_ENCODING);
        headers.set(HttpHeaderNames.CONTENT_LENGTH, count);
    }//from w  ww .  ja v  a  2  s .c om

    if (keepAlive) {
        headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    // dump headers
    rsp.headers().set(headers);
    ChannelHandlerContext ctx = this.ctx;
    ctx.channel().attr(NettyRequest.NEED_FLUSH).set(false);

    ChannelPipeline pipeline = ctx.pipeline();
    boolean ssl = pipeline.get(SslHandler.class) != null;

    if (ssl) {
        // add chunker
        chunkHandler(pipeline);

        // Create the chunked input here already, to properly handle the IOException
        HttpChunkedInput chunkedInput = new HttpChunkedInput(
                new ChunkedNioFile(channel, offset, count, bufferSize));

        ctx.channel().eventLoop().execute(() -> {
            // send headers
            ctx.write(rsp);
            // chunked file
            keepAlive(ctx.writeAndFlush(chunkedInput));
        });
    } else {
        ctx.channel().eventLoop().execute(() -> {
            // send headers
            ctx.write(rsp);
            // file region
            ctx.write(new DefaultFileRegion(channel, offset, count));
            keepAlive(ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT));
        });
    }

    committed = true;

}

From source file:org.jooby.internal.netty.NettyResponse.java

License:Apache License

private void chunkHandler(final ChannelPipeline pipeline) {
    if (pipeline.get("chunker") == null) {
        pipeline.addAfter("codec", "chunker", new ChunkedWriteHandler());
    }/*  w  ww  . j  a  v  a 2 s  .c o m*/
}

From source file:org.opendaylight.protocol.bgp.rib.impl.BGPSessionImpl.java

License:Open Source License

public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen,
        final int localHoldTimer, final BGPPeerRegistry peerRegistry) {
    this.listener = Preconditions.checkNotNull(listener);
    this.channel = Preconditions.checkNotNull(channel);
    this.limiter = new ChannelOutputLimiter(this);
    this.channel.pipeline().addLast(this.limiter);
    this.holdTimerValue = (remoteOpen.getHoldTimer() < localHoldTimer) ? remoteOpen.getHoldTimer()
            : localHoldTimer;//  w ww .  j  a v a2  s .c  om
    LOG.info("BGP HoldTimer new value: {}", this.holdTimerValue);
    this.keepAlive = this.holdTimerValue / KA_TO_DEADTIMER_RATIO;
    this.asNumber = AsNumberUtil.advertizedAsNumber(remoteOpen);
    this.peerRegistry = peerRegistry;

    final Set<TablesKey> tts = Sets.newHashSet();
    final Set<BgpTableType> tats = Sets.newHashSet();
    final List<AddressFamilies> addPathCapabilitiesList = Lists.newArrayList();
    if (remoteOpen.getBgpParameters() != null) {
        for (final BgpParameters param : remoteOpen.getBgpParameters()) {
            for (final OptionalCapabilities optCapa : param.getOptionalCapabilities()) {
                final CParameters cParam = optCapa.getCParameters();
                if (cParam.getAugmentation(CParameters1.class) == null) {
                    continue;
                }
                if (cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability() != null) {
                    final MultiprotocolCapability multi = cParam.getAugmentation(CParameters1.class)
                            .getMultiprotocolCapability();
                    final TablesKey tt = new TablesKey(multi.getAfi(), multi.getSafi());
                    LOG.trace("Added table type to sync {}", tt);
                    tts.add(tt);
                    tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
                } else if (cParam.getAugmentation(CParameters1.class).getAddPathCapability() != null) {
                    final AddPathCapability addPathCap = cParam.getAugmentation(CParameters1.class)
                            .getAddPathCapability();
                    addPathCapabilitiesList.addAll(addPathCap.getAddressFamilies());
                }
            }
        }
    }

    this.sync = new BGPSynchronization(this.listener, tts);
    this.tableTypes = tats;
    this.addPathTypes = addPathCapabilitiesList;

    if (!this.addPathTypes.isEmpty()) {
        final ChannelPipeline pipeline = this.channel.pipeline();
        final BGPByteToMessageDecoder decoder = pipeline.get(BGPByteToMessageDecoder.class);
        decoder.addDecoderConstraint(MultiPathSupport.class,
                MultiPathSupportImpl.createParserMultiPathSupport(this.addPathTypes));
    }

    if (this.holdTimerValue != 0) {
        channel.eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                handleHoldTimer();
            }
        }, this.holdTimerValue, TimeUnit.SECONDS);

        channel.eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                handleKeepaliveTimer();
            }
        }, this.keepAlive, TimeUnit.SECONDS);
    }
    this.bgpId = remoteOpen.getBgpIdentifier();
    this.sessionStats = new BGPSessionStatsImpl(this, remoteOpen, this.holdTimerValue, this.keepAlive, channel,
            Optional.<BGPSessionPreferences>absent(), this.tableTypes, this.addPathTypes);
}

From source file:org.spout.engine.listener.channel.SpoutProxyConnectListener.java

License:Open Source License

@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (!future.isDone()) {
        throw new IllegalStateException("Connect operation was not done when listener was triggered");
    } else {/*from www .jav  a2s.c o m*/
        Channel c = future.channel();
        if (future.isSuccess()) {
            Spout.getLogger().info("Connect to server successful " + c.remoteAddress() + ", " + playerName);
            session.bindAuxChannel(c);
            ChannelPipeline pipeline = c.pipeline();
            if (pipeline != null) {
                CommonHandler d = pipeline.get(CommonHandler.class);
                if (d != null) {
                    d.setSession(session);
                }
                Protocol protocol = session.getProtocol();
                if (protocol != null) {
                    Message intro = protocol.getIntroductionMessage(playerName,
                            (InetSocketAddress) c.remoteAddress());
                    c.writeAndFlush(intro);
                    return;
                }
            }
            session.disconnect("Login failed for backend server");
        } else {
            Spout.getLogger().info("Failed to connect to server " + c.remoteAddress() + ", " + playerName);
            session.disconnect("Unable to connect to backend server");
        }
    }
}

From source file:org.thingsplode.synapse.proxy.Dispatcher.java

License:Apache License

protected void connect() throws InterruptedException {
    try {//from w ww  . j a va2 s  .  co  m
        ChannelFuture cf = b.connect(host, port).addListener((ChannelFutureListener) (ChannelFuture future) -> {
            if (!future.isSuccess()) {
                logger.warn("Connecting to the channel was not successfull.");
            } else {
                logger.debug("Connected Channel@EndpointProxy");
            }
        }).sync();

        ChannelHandler handler = cf.channel().pipeline().get(EndpointProxy.WS_MESSAGE_DECODER);
        if (handler != null) {
            //if websocket client handler is added to the mix, the next step is to handshake with it
            logger.debug("Initiating websocket handshake ...");
            ((WSMessageDecoder) handler).getHandshakeFuture().sync()
                    .addListener((ChannelFutureListener) (ChannelFuture future) -> {
                        if (!future.isSuccess()) {
                            //todo: close dispatcher and websocket connection
                            //((WSResponseToResponseDecoder) handler).
                        } else {
                            logger.debug("Handshake@EndpointProxy");
                            ChannelPipeline pl = future.channel().pipeline();
                            if (pl.get(EndpointProxy.HTTP_REQUEST_ENCODER) != null) {
                                pl.remove(EndpointProxy.HTTP_REQUEST_ENCODER);
                            }

                            if (pl.get(EndpointProxy.HTTP_RESPONSE_DECODER) != null) {
                                pl.remove(EndpointProxy.HTTP_RESPONSE_DECODER);
                            }

                            if (pl.get(EndpointProxy.HTTP_RESPONSE_AGGREGATOR) != null) {
                                pl.remove(EndpointProxy.HTTP_RESPONSE_AGGREGATOR);
                            }
                        }
                    });
        }

        while (!cf.isSuccess()) {
            logger.warn("Connection attempt was not successfull / retrying...");
            cf = handleReconnect(b, host, port);
            if (cf == null) {
                break;
            }
        }

        this.channel = cf.channel();
        if (channel == null) {
            throw new InterruptedException("Cannot connect.");
        }
        channel.closeFuture().addListener((ChannelFutureListener) (ChannelFuture future) -> {
            if (future.isSuccess()) {
                logger.debug("Channel@Proxy is closed / evicting active requests.");
                dispatchedFutureHandler.evictActiveRequests();
            }
        });
    } catch (Exception ex) {
        logger.warn("Could not connect: " + ex.getMessage(), ex);
        ChannelFuture cf2 = handleReconnect(b, host, port);
        if (cf2 != null) {
            this.channel = cf2.channel();
        } else {
            throw ex;
        }
    }
}

From source file:org.vertx.java.core.http.impl.ClientConnection.java

License:Open Source License

NetSocket createNetSocket() {
    // connection was upgraded to raw TCP socket
    upgradedConnection = true;//from  w  w  w .  j  a v a2  s .  c  o m
    DefaultNetSocket socket = new DefaultNetSocket(vertx, channel, context, client.tcpHelper, true);
    Map<Channel, DefaultNetSocket> connectionMap = new HashMap<Channel, DefaultNetSocket>(1);
    connectionMap.put(channel, socket);

    // Flush out all pending data
    endReadAndFlush();

    // remove old http handlers and replace the old handler with one that handle plain sockets
    ChannelPipeline pipeline = channel.pipeline();
    ChannelHandler inflater = pipeline.get(HttpContentDecompressor.class);
    if (inflater != null) {
        pipeline.remove(inflater);
    }
    pipeline.remove("codec");
    pipeline.replace("handler", "handler", new VertxNetHandler(client.vertx, connectionMap) {
        @Override
        public void exceptionCaught(ChannelHandlerContext chctx, Throwable t) throws Exception {
            // remove from the real mapping
            client.connectionMap.remove(channel);
            super.exceptionCaught(chctx, t);
        }

        @Override
        public void channelInactive(ChannelHandlerContext chctx) throws Exception {
            // remove from the real mapping
            client.connectionMap.remove(channel);
            super.channelInactive(chctx);
        }

        @Override
        public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception {
            if (msg instanceof HttpContent) {
                ReferenceCountUtil.release(msg);
                return;
            }
            super.channelRead(chctx, msg);
        }
    });
    return socket;
}

From source file:org.vertx.java.core.http.impl.ServerConnection.java

License:Open Source License

NetSocket createNetSocket() {
    DefaultNetSocket socket = new DefaultNetSocket(vertx, channel, context, server.tcpHelper, false);
    Map<Channel, DefaultNetSocket> connectionMap = new HashMap<Channel, DefaultNetSocket>(1);
    connectionMap.put(channel, socket);/*from w  ww  . ja v  a  2 s .c  o m*/

    // Flush out all pending data
    endReadAndFlush();

    // remove old http handlers and replace the old handler with one that handle plain sockets
    ChannelPipeline pipeline = channel.pipeline();
    ChannelHandler compressor = pipeline.get(HttpChunkContentCompressor.class);
    if (compressor != null) {
        pipeline.remove(compressor);
    }

    pipeline.remove("httpDecoder");
    if (pipeline.get("chunkedWriter") != null) {
        pipeline.remove("chunkedWriter");
    }

    channel.pipeline().replace("handler", "handler", new VertxNetHandler(server.vertx, connectionMap) {
        @Override
        public void exceptionCaught(ChannelHandlerContext chctx, Throwable t) throws Exception {
            // remove from the real mapping
            server.connectionMap.remove(channel);
            super.exceptionCaught(chctx, t);
        }

        @Override
        public void channelInactive(ChannelHandlerContext chctx) throws Exception {
            // remove from the real mapping
            server.connectionMap.remove(channel);
            super.channelInactive(chctx);
        }

        @Override
        public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception {
            if (msg instanceof HttpContent) {
                ReferenceCountUtil.release(msg);
                return;
            }
            super.channelRead(chctx, msg);
        }
    });

    // check if the encoder can be removed yet or not.
    if (lastWriteFuture == null) {
        channel.pipeline().remove("httpEncoder");
    } else {
        lastWriteFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                channel.pipeline().remove("httpEncoder");
            }
        });
    }
    return socket;
}