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.apache.tinkerpop.gremlin.server.handler.SaslAuthenticationHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
    if (msg instanceof RequestMessage) {
        final RequestMessage requestMessage = (RequestMessage) msg;

        final Attribute<Authenticator.SaslNegotiator> negotiator = ctx.attr(StateKey.NEGOTIATOR);
        final Attribute<RequestMessage> request = ctx.attr(StateKey.REQUEST_MESSAGE);
        if (negotiator.get() == null) {
            // First time through so save the request and send an AUTHENTICATE challenge with no data
            negotiator.set(authenticator.newSaslNegotiator(getRemoteInetAddress(ctx)));
            request.set(requestMessage);
            final ResponseMessage authenticate = ResponseMessage.build(requestMessage)
                    .code(ResponseStatusCode.AUTHENTICATE).create();
            ctx.writeAndFlush(authenticate);
        } else {/*w ww.ja v  a2  s .  c om*/
            if (requestMessage.getOp().equals(Tokens.OPS_AUTHENTICATION)
                    && requestMessage.getArgs().containsKey(Tokens.ARGS_SASL)) {

                final Object saslObject = requestMessage.getArgs().get(Tokens.ARGS_SASL);
                final byte[] saslResponse;

                if (saslObject instanceof byte[]) {
                    saslResponse = (byte[]) saslObject;
                } else if (saslObject instanceof String) {
                    saslResponse = BASE64_DECODER.decode((String) saslObject);
                } else {
                    final ResponseMessage error = ResponseMessage.build(request.get())
                            .statusMessage("Incorrect type for : " + Tokens.ARGS_SASL
                                    + " - byte[] or base64 encoded String is expected")
                            .code(ResponseStatusCode.REQUEST_ERROR_MALFORMED_REQUEST).create();
                    ctx.writeAndFlush(error);
                    return;
                }

                try {
                    final byte[] saslMessage = negotiator.get().evaluateResponse(saslResponse);
                    if (negotiator.get().isComplete()) {
                        // todo: do something with this user
                        final AuthenticatedUser user = negotiator.get().getAuthenticatedUser();

                        // If we have got here we are authenticated so remove the handler and pass
                        // the original message down the pipeline for processing
                        ctx.pipeline().remove(this);
                        final RequestMessage original = request.get();
                        ctx.fireChannelRead(original);
                    } else {
                        // not done here - send back the sasl message for next challenge. note that we send back
                        // the base64 encoded sasl as well as the byte array. the byte array will eventually be
                        // phased out, but is present now for backward compatibility in 3.2.x
                        final Map<String, Object> metadata = new HashMap<>();
                        metadata.put(Tokens.ARGS_SASL, BASE64_ENCODER.encodeToString(saslMessage));
                        final ResponseMessage authenticate = ResponseMessage.build(requestMessage)
                                .statusAttributes(metadata).code(ResponseStatusCode.AUTHENTICATE)
                                .result(saslMessage).create();
                        ctx.writeAndFlush(authenticate);
                    }
                } catch (AuthenticationException ae) {
                    final ResponseMessage error = ResponseMessage.build(request.get())
                            .statusMessage(ae.getMessage()).code(ResponseStatusCode.UNAUTHORIZED).create();
                    ctx.writeAndFlush(error);
                }
            } else {
                final ResponseMessage error = ResponseMessage.build(requestMessage)
                        .statusMessage("Failed to authenticate").code(ResponseStatusCode.UNAUTHORIZED).create();
                ctx.writeAndFlush(error);
            }
        }
    } else {
        logger.warn("{} only processes RequestMessage instances - received {} - channel closing",
                this.getClass().getSimpleName(), msg.getClass());
        ctx.close();
    }
}

From source file:org.apache.tinkerpop.gremlin.server.handler.WsAndHttpChannelizerHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object obj) {
    final ChannelPipeline pipeline = ctx.pipeline();
    if (obj instanceof HttpMessage && !WebSocketHandlerUtil.isWebSocket((HttpMessage) obj)) {
        if (null != pipeline.get(PIPELINE_AUTHENTICATOR)) {
            pipeline.remove(PIPELINE_REQUEST_HANDLER);
            final ChannelHandler authenticator = pipeline.get(PIPELINE_AUTHENTICATOR);
            pipeline.remove(PIPELINE_AUTHENTICATOR);
            pipeline.addAfter(PIPELINE_HTTP_RESPONSE_ENCODER, PIPELINE_AUTHENTICATOR, authenticator);
            pipeline.addAfter(PIPELINE_AUTHENTICATOR, PIPELINE_REQUEST_HANDLER,
                    this.httpGremlinEndpointHandler);
        } else {/*from ww w.ja v a2s  .c  o m*/
            pipeline.remove(PIPELINE_REQUEST_HANDLER);
            pipeline.addAfter(PIPELINE_HTTP_RESPONSE_ENCODER, PIPELINE_REQUEST_HANDLER,
                    this.httpGremlinEndpointHandler);
        }
    }
    ctx.fireChannelRead(obj);
}

From source file:org.artJava.chat.SecureChatServerHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) {//

    //       System.out.println("channelactive!");

    // Once session is secured, send a greeting and register the channel to the global channel
    // list so the channel received the messages from others.
    ////from w w w  .  j ava  2  s.  c  om
    ctx.pipeline().get(SslHandler.class).handshakeFuture()
            .addListener(new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName()
                            + " secure chat service!\n");
                    ctx.writeAndFlush("Your session is protected by "
                            + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()
                            + " cipher suite.\n");

                    channels.add(ctx.channel());
                }
            });
}

From source file:org.asynchttpclient.netty.channel.SslInitializer.java

License:Apache License

@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
        ChannelPromise promise) throws Exception {

    InetSocketAddress remoteInetSocketAddress = (InetSocketAddress) remoteAddress;
    String peerHost = remoteInetSocketAddress.getHostString();
    int peerPort = remoteInetSocketAddress.getPort();

    SslHandler sslHandler = channelManager.createSslHandler(peerHost, peerPort);

    ctx.pipeline().replace(ChannelManager.SSL_HANDLER, ChannelManager.SSL_HANDLER, sslHandler);

    ctx.connect(remoteAddress, localAddress, promise);
}

From source file:org.asynchttpclient.netty.handler.AsyncHttpClientHandler.java

License:Open Source License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {

    Channel channel = ctx.channel();
    Object attribute = Channels.getAttribute(channel);

    try {/*from  w w w  . j  a  v  a 2s .  c  o m*/
        if (attribute instanceof Callback) {
            Callback ac = (Callback) attribute;
            if (msg instanceof LastHttpContent) {
                ac.call();
            } else if (!(msg instanceof HttpContent)) {
                logger.info("Received unexpected message while expecting a chunk: " + msg);
                ac.call();
                Channels.setDiscard(channel);
            }

        } else if (attribute instanceof NettyResponseFuture) {
            NettyResponseFuture<?> future = (NettyResponseFuture<?>) attribute;
            handleRead(channel, future, msg);

        } else if (attribute instanceof StreamedResponsePublisher) {

            StreamedResponsePublisher publisher = (StreamedResponsePublisher) attribute;

            if (msg instanceof HttpContent) {
                ByteBuf content = ((HttpContent) msg).content();
                // Republish as a HttpResponseBodyPart
                if (content.readableBytes() > 0) {
                    HttpResponseBodyPart part = config.getResponseBodyPartFactory().newResponseBodyPart(content,
                            false);
                    ctx.fireChannelRead(part);
                }
                if (msg instanceof LastHttpContent) {
                    // Remove the handler from the pipeline, this will trigger
                    // it to finish
                    ctx.pipeline().remove(publisher);
                    // Trigger a read, just in case the last read complete
                    // triggered no new read
                    ctx.read();
                    // Send the last content on to the protocol, so that it can
                    // conclude the cleanup
                    handleRead(channel, publisher.future(), msg);
                }
            } else {
                logger.info("Received unexpected message while expecting a chunk: " + msg);
                ctx.pipeline().remove(publisher);
                Channels.setDiscard(channel);
            }
        } else if (attribute != DiscardEvent.INSTANCE) {
            // unhandled message
            logger.debug("Orphan channel {} with attribute {} received message {}, closing", channel, attribute,
                    msg);
            Channels.silentlyCloseChannel(channel);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:org.asynchttpclient.providers.netty.channel.SslInitializer.java

License:Apache License

@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
        ChannelPromise promise) throws Exception {

    InetSocketAddress remoteInetSocketAddress = (InetSocketAddress) remoteAddress;
    String peerHost = remoteInetSocketAddress.getHostName();
    int peerPort = remoteInetSocketAddress.getPort();

    SslHandler sslHandler = channels.createSslHandler(peerHost, peerPort);

    ctx.pipeline().replace(Channels.SSL_HANDLER, Channels.SSL_HANDLER, sslHandler);

    ctx.connect(remoteAddress, localAddress, promise);
}

From source file:org.asynchttpclient.providers.netty.handler.NettyChannelHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object e) throws Exception {

    Object attribute = Channels.getDefaultAttribute(ctx);

    // FIXME is || !(e instanceof HttpContent) necessary?
    if (attribute instanceof Callback && (e instanceof LastHttpContent /* || !(e instanceof HttpContent) */)) {
        Callback ac = (Callback) attribute;
        ac.call();//from  w w  w  .j a  va2s  .  c  o  m
        Channels.setDefaultAttribute(ctx, DiscardEvent.INSTANCE);

    } else if (attribute instanceof NettyResponseFuture) {
        Protocol p = (ctx.pipeline().get(HttpClientCodec.class) != null ? httpProtocol : webSocketProtocol);
        NettyResponseFuture<?> future = (NettyResponseFuture<?>) attribute;

        p.handle(ctx, future, e);

    } else if (attribute != DiscardEvent.INSTANCE) {
        try {
            LOGGER.trace("Closing an orphan channel {}", ctx.channel());
            ctx.channel().close();
        } catch (Throwable t) {
        }
    }
}

From source file:org.asynchttpclient.providers.netty.handler.NettyChannelHandler.java

License:Apache License

public void channelInactive(ChannelHandlerContext ctx) throws Exception {

    if (closed.get()) {
        return;//from   ww  w .  j a v  a2 s  . c  o m
    }

    try {
        super.channelInactive(ctx);
    } catch (Exception ex) {
        LOGGER.trace("super.channelClosed", ex);
    }

    channels.removeFromPool(ctx);
    Object attachment = Channels.getDefaultAttribute(ctx);
    LOGGER.debug("Channel Closed: {} with attachment {}", ctx.channel(), attachment);

    if (attachment instanceof Callback) {
        Callback callback = (Callback) attachment;
        Channels.setDefaultAttribute(ctx, callback.future());
        callback.call();

    } else if (attachment instanceof NettyResponseFuture<?>) {
        NettyResponseFuture<?> future = NettyResponseFuture.class.cast(attachment);
        future.touch();

        if (!config.getIOExceptionFilters().isEmpty() && requestSender
                .applyIoExceptionFiltersAndReplayRequest(ctx, future, new IOException("Channel Closed"))) {
            return;
        }

        Protocol p = (ctx.pipeline().get(HttpClientCodec.class) != null ? httpProtocol : webSocketProtocol);
        p.onClose(ctx);

        if (future != null && !future.isDone() && !future.isCancelled()) {
            if (!requestSender.retry(ctx.channel(), future)) {
                channels.abort(future, AsyncHttpProviderUtils.REMOTELY_CLOSED_EXCEPTION);
            }
        } else {
            channels.closeChannel(ctx);
        }
    }
}

From source file:org.asynchttpclient.providers.netty.handler.NettyChannelHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception {
    Channel channel = ctx.channel();
    Throwable cause = e.getCause() != null ? e.getCause() : e;
    NettyResponseFuture<?> future = null;

    if (cause instanceof PrematureChannelClosureException) {
        return;// ww  w  . jav  a  2  s.  c o m
    }

    LOGGER.debug("Unexpected I/O exception on channel {}", channel, cause);

    try {
        if (cause instanceof ClosedChannelException) {
            return;
        }

        Object attribute = Channels.getDefaultAttribute(ctx);
        if (attribute instanceof NettyResponseFuture<?>) {
            future = (NettyResponseFuture<?>) attribute;
            future.attachChannel(null, false);
            future.touch();

            if (cause instanceof IOException) {

                // FIXME why drop the original exception and create a new
                // one?
                if (!config.getIOExceptionFilters().isEmpty()) {
                    if (requestSender.applyIoExceptionFiltersAndReplayRequest(ctx, future,
                            new IOException("Channel Closed"))) {
                        return;
                    }
                } else {
                    // Close the channel so the recovering can occurs.
                    try {
                        ctx.channel().close();
                    } catch (Throwable t) {
                        // Swallow.
                    }
                    return;
                }
            }

            if (NettyResponseFutures.abortOnReadCloseException(cause)
                    || NettyResponseFutures.abortOnWriteCloseException(cause)) {
                LOGGER.debug("Trying to recover from dead Channel: {}", channel);
                return;
            }
        } else if (attribute instanceof Callback) {
            future = Callback.class.cast(attribute).future();
        }
    } catch (Throwable t) {
        cause = t;
    }

    if (future != null) {
        try {
            LOGGER.debug("Was unable to recover Future: {}", future);
            channels.abort(future, cause);
        } catch (Throwable t) {
            LOGGER.error(t.getMessage(), t);
        }
    }

    Protocol protocol = ctx.pipeline().get(HttpClientCodec.class) != null ? httpProtocol : webSocketProtocol;
    protocol.onError(ctx, e);

    channels.closeChannel(ctx);
    // FIXME not really sure
    // ctx.fireChannelRead(e);
    ctx.close();
}

From source file:org.atmosphere.nettosphere.BridgeRuntime.java

License:Apache License

private void handleWebSocketHandshake(final ChannelHandlerContext ctx, Object messageEvent)
        throws IOException, URISyntaxException {
    final HttpRequest request = (HttpRequest) messageEvent;

    // Allow only GET methods.
    if (request.getMethod() != GET) {
        sendHttpResponse(ctx, request, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN));
        return;/*w  ww .ja v  a  2 s .  co m*/
    }

    ctx.pipeline().addBefore(BridgeRuntime.class.getName(), "encoder", new HttpResponseEncoder());
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
            getWebSocketLocation(request), config.subProtocols(), false, maxWebSocketFrameSize);

    WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(request);

    if (handshaker == null) {
        wsFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        final NettyWebSocket webSocket = new NettyWebSocket(ctx.channel(), framework.getAtmosphereConfig(),
                config.noInternalAlloc(), config.binaryWrite());
        final AtmosphereRequest atmosphereRequest = createAtmosphereRequest(ctx, request, EMPTY);

        if (!webSocketProcessor.handshake(atmosphereRequest)) {
            sendError(ctx, HttpResponseStatus.BAD_REQUEST, null);
            return;
        }

        webSocketProcessor.notifyListener(webSocket,
                new WebSocketEventListener.WebSocketEvent("", HANDSHAKE, webSocket));

        handshaker.handshake(ctx.channel(), (FullHttpRequest) request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    future.channel().close();
                } else {
                    websocketChannels.add(ctx.channel());

                    ctx.channel().attr(ATTACHMENT).set(webSocket);
                    if (config.noInternalAlloc()) {
                        webSocket.resource(proxiedResource);
                    }

                    AtmosphereResponse response = config.noInternalAlloc() ? proxiedResponse
                            : AtmosphereResponseImpl.newInstance(framework.getAtmosphereConfig(),
                                    atmosphereRequest, webSocket);
                    webSocketProcessor.open(webSocket, atmosphereRequest, response);

                    if (webSocketTimeout > 0) {
                        webSocket.closeFuture(suspendTimer.scheduleAtFixedRate(new Runnable() {
                            @Override
                            public void run() {
                                if (webSocket.lastWriteTimeStampInMilliseconds() != 0
                                        && (System.currentTimeMillis() - webSocket
                                                .lastWriteTimeStampInMilliseconds() > webSocketTimeout)) {
                                    logger.debug("Timing out {}", webSocket);
                                    webSocket.close();
                                }
                            }
                        }, webSocketTimeout, webSocketTimeout, TimeUnit.MILLISECONDS));
                    }
                }
            }
        });
    }
}