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:org.infinispan.rest.http2.Http2ClientInitializer.java

License:Apache License

/**
 * Configure the pipeline for TLS NPN negotiation to HTTP/2.
 *///  ww w.  j  a va  2 s . c o  m
private void configureSsl(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    // We must wait for the handshake to finish and the protocol to be negotiated before configuring
    // the HTTP/2 components of the pipeline.
    pipeline.addLast(new ApplicationProtocolNegotiationHandler("") {
        @Override
        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                ChannelPipeline p = ctx.pipeline();
                p.addLast(connectionHandler);
                configureEndOfPipeline(p);
                return;
            }
            ctx.close();
            throw new IllegalStateException("unknown protocol: " + protocol);
        }
    });
    pipeline.addLast(new UserEventLogger());
}

From source file:org.infinispan.server.core.transport.SaslServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buf = (ByteBuf) msg;/*from ww  w. java 2 s. c o  m*/
    Channel ch = ctx.channel();
    try {
        if (!firstPass) {
            readHeader(buf);
        } else {
            firstPass = false;
        }
        byte[] bytes = readBytes(buf);
        byte[] challenge = server.evaluateResponse(bytes);
        if (!server.isComplete()) {
            ch.writeAndFlush(newContinueMessage(ctx, Unpooled.wrappedBuffer(challenge)));
        } else {
            ch.writeAndFlush(newSuccessMessage(ctx, Unpooled.wrappedBuffer(challenge)));

            ChannelPipeline pipeline = ctx.pipeline();
            String qop = (String) server.getNegotiatedProperty(Sasl.QOP);
            if (qop != null && (qop.equalsIgnoreCase(AUTH_INT) || qop.equalsIgnoreCase(AUTO_CONF))) {
                SaslServer server = this.server;
                this.server = null;
                // Replace this handler now with the QopHandler
                // This is mainly done as the QopHandler itself will not block at all and so we can
                // get rid of the usage of the EventExecutorGroup after the negation took place.
                pipeline.replace(this, ctx.name(), new QopHandler(server));
            } else {
                // there is no need for any QOP handling so we are done now and can just remove ourself from the
                // pipeline
                pipeline.remove(this);
            }
        }
    } catch (SaslException e) {
        Object errorMsg = newErrorMessage(ctx, e);
        if (errorMsg != null) {
            ch.writeAndFlush(errorMsg).addListener(ChannelFutureListener.CLOSE);
        }
    }
}

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

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object obj) throws Exception {
    if (obj instanceof HttpMessage && !isWebSocket((HttpMessage) obj)) {
        if (null == ctx.pipeline().get(HMAC_AUTH)) {
            final HttpHMACAuthenticationHandler authHandler = new HttpHMACAuthenticationHandler(
                    hmacAuthenticator);//  w ww.  j ava  2s .c om
            ctx.pipeline().addAfter(PIPELINE_AUTHENTICATOR, HMAC_AUTH, authHandler);
        }
        ctx.fireChannelRead(obj);
    } else {
        super.channelRead(ctx, obj);
    }
}

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   w  w w .  j  ava  2 s.co 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();/* ww w . j a  v a 2  s .  c  o  m*/

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

From source file:org.jboss.aerogear.simplepush.server.netty.UserAgentReaperHandlerTest.java

License:Apache License

@SuppressWarnings({ "rawtypes", "unchecked" })
private ChannelHandlerContext channelHandlerContext() {
    final ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    final EventExecutor eventExecutor = mock(EventExecutor.class);
    final ScheduledFuture future = mock(ScheduledFuture.class);
    when(eventExecutor.scheduleAtFixedRate(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class)))
            .thenReturn(future);/*from   w  ww .  ja  v a 2 s .c om*/
    when(ctx.executor()).thenReturn(eventExecutor);
    when(ctx.pipeline()).thenReturn(mock(ChannelPipeline.class));
    return ctx;
}

From source file:org.jboss.aerogear.webpush.netty.Http2OrHttpHandler.java

License:Apache License

@Override
protected void configurePipeline(final ChannelHandlerContext ctx, final String protocol) throws Exception {
    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
        ctx.pipeline().addLast(new WebPushHttp2HandlerBuilder().webPushServer(webPushServer).build());
        return;//from   ww w . j a  va2  s .  c om
    }
    if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
        ctx.pipeline().addLast(new WebPushHttp11Handler(webPushServer));
        return;
    }
    throw new IllegalStateException("unknown protocol: " + protocol);
}

From source file:org.jdiameter.client.impl.transport.tls.netty.StartTlsClientHandler.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//ww w.  j  a va 2s.c o m
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.debug("StartTlsClientHandler");
    ByteBuf buf = (ByteBuf) msg;
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), bytes);

    if ("StartTlsResponse".equals(new String(bytes))) {
        logger.debug("received StartTlsResponse");

        SslContext sslContext = SslContextFactory.getSslContextForClient(this.tlsTransportClient.getConfig());
        SSLEngine sslEngine = sslContext.newEngine(ctx.alloc());
        sslEngine.setUseClientMode(true);
        SslHandler sslHandler = new SslHandler(sslEngine, false);

        final ChannelPipeline pipeline = ctx.pipeline();
        pipeline.remove("startTlsClientHandler");
        pipeline.addLast("sslHandler", sslHandler);

        logger.debug("StartTls starting handshake");

        sslHandler.handshakeFuture().addListener(new GenericFutureListener() {
            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()) {
                    logger.debug("StartTls handshake succesfull");

                    tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKEN);

                    logger.debug("restoring all handlers");

                    pipeline.addLast("decoder",
                            new DiameterMessageDecoder(
                                    StartTlsClientHandler.this.tlsTransportClient.getParent(),
                                    StartTlsClientHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("msgHandler", new DiameterMessageHandler(
                            StartTlsClientHandler.this.tlsTransportClient.getParent(), true));

                    pipeline.addLast("encoder", new DiameterMessageEncoder(
                            StartTlsClientHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("inbandWriter", new InbandSecurityHandler());
                }
            }
        });

    }
}

From source file:org.jdiameter.client.impl.transport.tls.netty.StartTlsInitiator.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//  w ww  .  j  a  v a2s  .c  o  m
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof IMessage) {
        IMessage m = (IMessage) msg;
        logger.debug("StartTlsInitiator");
        if (m.getCommandCode() == IMessage.CAPABILITIES_EXCHANGE_ANSWER
                && this.tlsTransportClient.getTlsHandshakingState() == TlsHandshakingState.INIT) {
            AvpSet set = m.getAvps();
            Avp inbandAvp = set.getAvp(Avp.INBAND_SECURITY_ID);
            if (inbandAvp != null && inbandAvp.getUnsigned32() == 1) {
                this.tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKING);

                final ChannelPipeline pipeline = ctx.pipeline();
                pipeline.remove("decoder");
                pipeline.remove("msgHandler");
                pipeline.remove(this);
                pipeline.remove("encoder");
                pipeline.remove("inbandWriter");

                pipeline.addLast("startTlsClientHandler", new StartTlsClientHandler(this.tlsTransportClient));

                logger.debug("Sending StartTlsRequest");
                ctx.writeAndFlush(Unpooled.wrappedBuffer("StartTlsRequest".getBytes()))
                        .addListener(new GenericFutureListener() {

                            @Override
                            public void operationComplete(Future f) throws Exception {
                                if (!f.isSuccess()) {
                                    logger.error(f.cause().getMessage(), f.cause());
                                }
                            }
                        });

            }
        }
    }

    ReferenceCountUtil.release(msg);
}

From source file:org.jdiameter.client.impl.transport.tls.netty.StartTlsServerHandler.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from   w  w w  . j  a  v a 2  s.  c  o  m*/
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.debug("StartTlsServerHandler");
    ByteBuf buf = (ByteBuf) msg;
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), bytes);

    if ("StartTlsRequest".equals(new String(bytes))) {
        logger.debug("Received StartTlsRequest");
        SslContext sslContext = SslContextFactory.getSslContextForServer(this.tlsTransportClient.getConfig());
        SSLEngine sslEngine = sslContext.newEngine(ctx.alloc());
        sslEngine.setUseClientMode(false);
        SslHandler sslHandler = new SslHandler(sslEngine, false);

        final ChannelPipeline pipeline = ctx.pipeline();

        pipeline.remove("decoder");
        pipeline.remove("msgHandler");
        pipeline.remove("encoder");
        pipeline.remove("inbandWriter");
        pipeline.remove(this);

        pipeline.addLast("sslHandler", sslHandler);

        sslHandler.handshakeFuture().addListener(new GenericFutureListener() {

            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()) {
                    logger.debug("StartTls server handshake succesfull");

                    tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKEN);

                    logger.debug("restoring all handlers");

                    pipeline.addLast("decoder",
                            new DiameterMessageDecoder(
                                    StartTlsServerHandler.this.tlsTransportClient.getParent(),
                                    StartTlsServerHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("msgHandler", new DiameterMessageHandler(
                            StartTlsServerHandler.this.tlsTransportClient.getParent(), true));

                    pipeline.addLast("encoder", new DiameterMessageEncoder(
                            StartTlsServerHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("inbandWriter", new InbandSecurityHandler());

                }
            }
        });

        ReferenceCountUtil.release(msg);
        logger.debug("Sending StartTlsResponse");
        ctx.writeAndFlush(Unpooled.wrappedBuffer("StartTlsResponse".getBytes()))
                .addListener(new GenericFutureListener() {

                    @Override
                    public void operationComplete(Future f) throws Exception {
                        if (!f.isSuccess()) {
                            logger.error(f.cause().getMessage(), f.cause());
                        }

                    }
                });
    } else {
        ctx.fireChannelRead(msg);
    }

}