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.maodian.flyingcat.xmpp.state.DefaultElementVisitor.java

License:Apache License

@Override
public State handleTLS(XmppContext xmppCtx, TLS tls) throws XMLStreamException {
    ChannelHandlerContext ctx = xmppCtx.getNettyChannelHandlerContext();
    SSLEngine engine = SecureSslContextFactory.getServerContext().createSSLEngine();
    engine.setUseClientMode(false);/*w  w  w .  jav  a  2 s  .co m*/
    SslHandler sslHandler = new SslHandler(engine, true);
    sslHandler.sslCloseFuture().addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            log.info("Close the socket since SSL connection has been closed by client");
            future.channel().close();
        }
    });
    ctx.pipeline().addFirst("ssl", sslHandler);

    StringWriter writer = new StringWriter();
    XMLStreamWriter xmlsw = XMLOutputFactoryHolder.getXMLOutputFactory().createXMLStreamWriter(writer);
    xmlsw.writeEmptyElement("", "proceed", XmppNamespace.TLS);
    xmlsw.setPrefix("", XmppNamespace.TLS);
    xmlsw.writeNamespace("", XmppNamespace.TLS);
    xmlsw.writeEndDocument();
    xmppCtx.flush(writer.toString());
    return xmppCtx.getGlobalContext().getTlsStreamState();
}

From source file:org.mp4parser.rtp2dash.DashServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);//from  w  w w.j  a  va2 s. c o  m
        return;
    }

    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    final String uri = request.getUri();

    if ("/Manifest.mpd".equals(uri)) {
        try {
            sendManifest(ctx);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }

    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    File file = new File(path);
    if (file.isHidden() || file.isDirectory() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }

    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = file.lastModified() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }

    final RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

    HttpHeaders.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    response.headers().set("Access-Control-Allow-Origin", "*");
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {

        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println(future.channel() + " Transfer progress: " + progress);
            } else {
                System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
            }
        }

        public void operationComplete(ChannelProgressiveFuture future) {
            try {
                raf.close();
            } catch (IOException e) {
                LOG.severe("Cannot close " + raf.toString());
            }
            System.err.println(future.channel() + " Transfer complete.");
        }
    });

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:org.msgpack.rpc.extension.socks.SocksProxyHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, SocksResponse response) throws Exception {

    SocksResponseType rt = response.responseType();

    switch (rt) {

    case INIT://from  w  w  w. j  a  v a  2s. c  o m
        ctx.pipeline().addFirst("socks-cmd-decoder", new SocksCmdResponseDecoder());
        InetSocketAddress addr = ((IPAddress) session.getAddress()).getInetSocketAddress();
        SocksCmdRequest cmdSocks = new SocksCmdRequest(SocksCmdType.CONNECT, SocksAddressType.DOMAIN,
                addr.getHostName(), addr.getPort());
        ctx.writeAndFlush(cmdSocks);
        break;

    case AUTH:
        break;
    case CMD:
        SocksCmdResponse scr = (SocksCmdResponse) response;
        ctx.pipeline().remove(this);
        ctx.pipeline().remove("socks-encode");
        if (scr.cmdStatus() != SocksCmdStatus.SUCCESS) {
            throw new ChannelException("Socks faild.");
        }
        clientTransport.onSocksConnected(ctx.channel());
        break;
    case UNKNOWN:
    default:
        throw new ChannelException("No support Socks Command.");
    }
}

From source file:org.neo4j.bolt.transport.TransportSelectionHandler.java

License:Open Source License

private void enableSsl(ChannelHandlerContext ctx) {
    ChannelPipeline p = ctx.pipeline();
    p.addLast(sslCtx.newHandler(ctx.alloc()));
    p.addLast(new TransportSelectionHandler(null, true, logging, protocolVersions));
    p.remove(this);
}

From source file:org.neo4j.bolt.transport.TransportSelectionHandler.java

License:Open Source License

private void switchToSocket(ChannelHandlerContext ctx) {
    ChannelPipeline p = ctx.pipeline();
    p.addLast(new SocketTransportHandler(
            new SocketTransportHandler.ProtocolChooser(protocolVersions, isEncrypted), logging));
    p.remove(this);
}

From source file:org.neo4j.bolt.transport.TransportSelectionHandler.java

License:Open Source License

private void switchToWebsocket(ChannelHandlerContext ctx) {
    ChannelPipeline p = ctx.pipeline();
    p.addLast(new HttpServerCodec(), new HttpObjectAggregator(MAX_WEBSOCKET_HANDSHAKE_SIZE),
            new WebSocketServerProtocolHandler(""), new WebSocketFrameTranslator(), new SocketTransportHandler(
                    new SocketTransportHandler.ProtocolChooser(protocolVersions, isEncrypted), logging));
    p.remove(this);
}

From source file:org.nepu.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.
    ///*  w ww .j a v a 2  s .co  m*/
    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.nosceon.titanite.WebsocketHandler.java

License:Apache License

public void handshake(HttpRequest rawRequest, Request request, ChannelHandlerContext ctx, WebSocket webSocket) {
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
            getWebSocketLocation(request), null, false);
    wsHandshaker = wsFactory.newHandshaker(rawRequest);
    if (wsHandshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {//  w  w  w  .  ja v a2 s.  c o m
        this.wsChannel = new WChannel(ctx.channel());
        this.wsHandshaker.handshake(ctx.channel(), toFullHttpRequest(rawRequest)).addListener(cf -> {
            ctx.pipeline().addLast(wsChannel);
            webSocket.onReady(wsChannel);
        });
    }
}

From source file:org.onesec.raven.rtp.InboundChannelInitializator.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof DatagramPacket) {
        final InetSocketAddress senderSocket = ((DatagramPacket) msg).sender();
        if (logger.isTraceEnabled())
            logger.debug("Received initial packet from ({})", senderSocket.toString());
        if (sender == null || sender.equals(senderSocket.getAddress())) {
            initChannel(senderSocket, ctx.channel());
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(msg);/*  w  w  w  .j a v  a 2  s  .co m*/
        }
    }
}

From source file:org.opendaylight.openflowjava.protocol.impl.core.TlsDetector.java

License:Open Source License

private static void enableSsl(ChannelHandlerContext ctx) {
    if (ctx.pipeline().get(COMPONENT_NAMES.SSL_HANDLER.name()) == null) {
        LOGGER.trace("Engaging TLS handler");
        ChannelPipeline p = ctx.channel().pipeline();
        SSLEngine engine = SslContextFactory.getServerContext().createSSLEngine();
        engine.setUseClientMode(false);/*ww  w. j a  v  a2  s .  com*/
        p.addAfter(COMPONENT_NAMES.TLS_DETECTOR.name(), COMPONENT_NAMES.SSL_HANDLER.name(),
                new SslHandler(engine));
    }
}