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.opendaylight.openflowjava.protocol.impl.core.TlsDetector.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf bb, List<Object> list) throws Exception {
    if (bb.readableBytes() < 5) {
        return;/*w  w w .j a  v a 2 s  .c  o  m*/
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(ByteBufUtils.byteBufToHexString(bb));
    }
    if (isSsl(bb)) {
        LOGGER.debug("Connection is encrypted");
        enableSsl(ctx);
    } else {
        LOGGER.debug("Connection is not encrypted");
    }

    if (connectionFacade != null) {
        LOGGER.trace("Firing onConnectionReady notification");
        connectionFacade.fireConnectionReadyNotification();
    }

    ctx.pipeline().remove(COMPONENT_NAMES.TLS_DETECTOR.name());
}

From source file:org.ow2.petals.bc.gateway.commons.handlers.AuthenticatorSSLHandler.java

License:Open Source License

private void setUpSslHandlers(final ChannelHandlerContext ctx, final AbstractDomain domain,
        final @Nullable String certificate, final @Nullable String key, final @Nullable String passphrase,
        final @Nullable String remoteCertificate) throws SSLException {

    // TODO could we use certificate only for auth and not encryption?
    // TODO support openssl
    final SslHandler sslHandler;
    if (pdOrAuth.isB() && certificate != null && key != null) {
        // server side ssl, do not forget startTls so that our accept can be sent after the handler is added

        final ServiceUnitDataHandler handler = domain.getSUHandler();

        final SslContextBuilder builder = SslContextBuilder
                .forServer(ServiceUnitUtil.getFile(handler.getInstallRoot(), certificate),
                        ServiceUnitUtil.getFile(handler.getInstallRoot(), key), passphrase)
                .sslProvider(SslProvider.JDK).ciphers(null, IdentityCipherSuiteFilter.INSTANCE)
                .sessionCacheSize(0).sessionTimeout(0);

        if (remoteCertificate != null) {
            builder.trustManager(ServiceUnitUtil.getFile(handler.getInstallRoot(), remoteCertificate))
                    .clientAuth(ClientAuth.REQUIRE);
        }/*from   www  .  j  a  va 2  s  .  co  m*/

        // until https://github.com/netty/netty/issues/5170 is accepted
        // we need to create the handler by hand
        sslHandler = new SslHandler(builder.build().newEngine(ctx.alloc()), true);
    } else if (pdOrAuth.isA() && remoteCertificate != null) {
        // client side

        final String installRoot = domain.getSUHandler().getInstallRoot();
        final SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(SslProvider.JDK)
                .trustManager(ServiceUnitUtil.getFile(installRoot, remoteCertificate))
                .ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0);

        if (certificate != null && key != null) {
            builder.keyManager(ServiceUnitUtil.getFile(installRoot, certificate),
                    ServiceUnitUtil.getFile(installRoot, key), passphrase);
        }

        sslHandler = builder.build().newHandler(ctx.alloc());
    } else {
        sslHandler = null;
    }

    // For a server, it contains the transporter name and the consumer domain name (it was updated in channelRead0)
    // For a client, it contains the provider domain name (it was set by the component)
    final String logName = logger.getName();

    // let's replace the debug logger with something specific to this consumer
    ctx.pipeline().replace(HandlerConstants.LOG_DEBUG_HANDLER, HandlerConstants.LOG_DEBUG_HANDLER,
            new LoggingHandler(logName, LogLevel.TRACE));

    ctx.pipeline().replace(HandlerConstants.LOG_ERRORS_HANDLER, HandlerConstants.LOG_ERRORS_HANDLER,
            new LastLoggingHandler(logName + ".errors"));

    if (sslHandler != null) {
        // if there is a sslHandler, then we can only add the domain handler after the handshake is finished
        // if not we risk sending things too early in it

        sslHandler.handshakeFuture().addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final @Nullable Future<Channel> future) throws Exception {
                assert future != null;
                if (!future.isSuccess()) {
                    authenticationFuture.setFailure(future.cause());
                } else {
                    // I must keep the handler here until now in case there is an exception so that I can log it
                    ctx.pipeline().replace(HandlerConstants.DOMAIN_HANDLER, HandlerConstants.DOMAIN_HANDLER,
                            dhb.build(domain));
                    authenticationFuture.setSuccess(ctx.channel());
                }
            }
        });

        ctx.pipeline().addAfter(HandlerConstants.LOG_DEBUG_HANDLER, HandlerConstants.SSL_HANDLER, sslHandler);
    }

    if (pdOrAuth.isB()) {
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Sending an Accept (" + ctx.channel().remoteAddress() + ")");
        }

        // this must be sent after the ssh handler is replaced (when using ssl) so that we are ready to receive ssl data right away
        // but this must be sent before the domain handler is replaced (when not using ssl), because it will send
        // data and it must arrive AFTER our Accept
        ctx.writeAndFlush(new AuthAccept());
    }

    // else it is done in the FutureListener
    if (sslHandler == null) {
        ctx.pipeline().replace(HandlerConstants.DOMAIN_HANDLER, HandlerConstants.DOMAIN_HANDLER,
                dhb.build(domain));
        authenticationFuture.setSuccess(ctx.channel());
    }
}

From source file:org.pidome.server.system.network.http.HttpProtocolNegotiator.java

/**
 * Configures the channel to use spdy.//w w  w.j a  v  a2  s .c  om
 * @param ctx The channel handler.
 * @param version The spdy version.
 * @param port The port used.
 * @throws Exception When the channel can not be configured.
 */
private static void configureSpdy(ChannelHandlerContext ctx, SpdyVersion version, int port) throws Exception {
    ctx.pipeline().addLast(new SpdyFrameCodec(version)).addLast(new SpdySessionHandler(version, true))
            .addLast(new SpdyHttpEncoder(version)).addLast(new SpdyHttpDecoder(version, 5242880))
            .addLast(new SpdyHttpResponseStreamIdHandler()).addLast(new HttpClientHandler(true, port))
            .addLast(new UserEventLogger());
}

From source file:org.pidome.server.system.network.http.HttpProtocolNegotiator.java

/**
 * Configures an http2 channel.// w  ww.ja  va  2  s. c om
 * @param ctx 
 */
private static void configureHttp2(ChannelHandlerContext ctx, int port) {
    DefaultHttp2Connection connection = new DefaultHttp2Connection(true);
    InboundHttp2ToHttpAdapter listener = new InboundHttp2ToHttpAdapterBuilder(connection)
            .propagateSettings(true).validateHttpHeaders(false).maxContentLength(5242880).build();

    ctx.pipeline().addLast(
            new HttpToHttp2ConnectionHandlerBuilder().frameListener(listener).connection(connection).build());

    ctx.pipeline().addLast(new Http2ClientHandler(port));
}

From source file:org.pidome.server.system.network.http.HttpProtocolNegotiator.java

/**
 * Configures the channel to use http./*from   w ww  .j  a v  a 2s  .  c om*/
 * This defaults to http 1.1
 * @param ctx The channel context
 * @param ssl if the channel should be used with ssl enabled.
 * @param port The port the channel lives on.
 * @throws Exception When the http channel can not be configured.
 */
protected static void configureHttp1(ChannelHandlerContext ctx, boolean ssl, int port) throws Exception {
    setHttp1PipeLine(ctx.pipeline(), ssl, port);
}

From source file:org.redisson.client.handler.CommandBatchEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, CommandsData msg, ByteBuf out) throws Exception {
    CommandEncoder encoder = ctx.pipeline().get(CommandEncoder.class);
    for (CommandData<?, ?> commandData : msg.getCommands()) {
        encoder.encode(ctx, commandData, out);
    }//from   www  . j  av  a2s  .  c  o m
}

From source file:org.redisson.client.handler.CommandDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    QueueCommand data = ctx.channel().attr(CommandsQueue.CURRENT_COMMAND).get();

    if (log.isTraceEnabled()) {
        log.trace("channel: {} message: {}", ctx.channel(),
                in.toString(0, in.writerIndex(), CharsetUtil.UTF_8));
    }/*from  w w  w  . ja  v a2s .  com*/
    if (state() == null) {
        boolean makeCheckpoint = data != null;
        if (data != null) {
            if (data instanceof CommandsData) {
                makeCheckpoint = false;
            } else {
                CommandData<Object, Object> cmd = (CommandData<Object, Object>) data;
                if (cmd.getCommand().getReplayMultiDecoder() != null && (NestedMultiDecoder.class
                        .isAssignableFrom(cmd.getCommand().getReplayMultiDecoder().getClass())
                        || SlotsDecoder.class
                                .isAssignableFrom(cmd.getCommand().getReplayMultiDecoder().getClass())
                        || ListMultiDecoder.class
                                .isAssignableFrom(cmd.getCommand().getReplayMultiDecoder().getClass()))) {
                    makeCheckpoint = false;
                }
            }
        }
        state(new State(makeCheckpoint));
    }

    state().setDecoderState(null);

    if (data == null) {
        decode(in, null, null, ctx.channel());
    } else if (data instanceof CommandData) {
        CommandData<Object, Object> cmd = (CommandData<Object, Object>) data;
        try {
            if (state().getLevels().size() > 0) {
                decodeFromCheckpoint(ctx, in, data, cmd);
            } else {
                decode(in, cmd, null, ctx.channel());
            }
        } catch (Exception e) {
            cmd.tryFailure(e);
        }
    } else if (data instanceof CommandsData) {
        CommandsData commands = (CommandsData) data;
        try {
            decodeCommandBatch(ctx, in, data, commands);
        } catch (Exception e) {
            commands.getPromise().tryFailure(e);
        }
        return;
    }

    ctx.pipeline().get(CommandsQueue.class).sendNextCommand(ctx.channel());

    state(null);
}

From source file:org.redisson.client.handler.CommandDecoder.java

License:Apache License

private void decodeCommandBatch(ChannelHandlerContext ctx, ByteBuf in, QueueCommand data,
        CommandsData commandBatch) {//w w w  .j a  v a  2 s  .  c  o m
    int i = state().getBatchIndex();

    RedisException error = null;
    while (in.writerIndex() > in.readerIndex()) {
        CommandData<Object, Object> cmd = null;
        try {
            checkpoint();
            state().setBatchIndex(i);
            cmd = (CommandData<Object, Object>) commandBatch.getCommands().get(i);
            decode(in, cmd, null, ctx.channel());
            i++;
        } catch (IOException e) {
            cmd.tryFailure(e);
        }
        if (!cmd.isSuccess()) {
            error = (RedisException) cmd.cause();
        }
    }

    if (commandBatch.isNoResult() || i == commandBatch.getCommands().size()) {
        RPromise<Void> promise = commandBatch.getPromise();
        if (error != null) {
            if (!promise.tryFailure(error) && promise.cause() instanceof RedisTimeoutException) {
                log.warn("response has been skipped due to timeout! channel: {}, command: {}", ctx.channel(),
                        LogHelper.toString(data));
            }
        } else {
            if (!promise.trySuccess(null) && promise.cause() instanceof RedisTimeoutException) {
                log.warn("response has been skipped due to timeout! channel: {}, command: {}", ctx.channel(),
                        LogHelper.toString(data));
            }
        }

        ctx.pipeline().get(CommandsQueue.class).sendNextCommand(ctx.channel());

        state(null);
    } else {
        checkpoint();
        state().setBatchIndex(i);
    }
}

From source file:org.redisson.client.handler.CommandsListEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, CommandsData msg, ByteBuf out) throws Exception {
    for (CommandData<?, ?> commandData : msg.getCommands()) {
        ctx.pipeline().get(CommandEncoder.class).encode(ctx, (CommandData<Object, Object>) commandData, out);
    }// w  ww  . ja v  a2s .c  o  m
}

From source file:org.rzo.netty.ahessian.io.InputStreamHandler.java

License:Apache License

public static InputStreamHandler getHandler(ChannelHandlerContext ctx) {
    return ctx.pipeline().get(InputStreamHandler.class);
}