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:me.bigteddy98.movingmotd.ClientSideConnection.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    this.networkManager.incomingChannel = ctx.channel();
    this.networkManager.clientsidePipeline = ctx.pipeline();

    Bootstrap bootstrab = new Bootstrap();
    bootstrab.group(networkManager.incomingChannel.eventLoop());
    bootstrab.channel(ctx.channel().getClass());
    bootstrab.handler(new ServerSideConnectionInitialization(networkManager));
    bootstrab.option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = bootstrab.connect(this.toHostname, this.toPort);
    f.addListener(new ChannelFutureListener() {
        @Override//from  w  w  w  .  ja  va 2s  . c  o  m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                networkManager.incomingChannel.read();
            } else {
                networkManager.incomingChannel.close();
            }
        }
    });
    this.outgoingChannel = f.channel();
}

From source file:me.bigteddy98.movingmotd.ServerSideConnection.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ctx.read();//  www.  j  ava 2s. c om
    ctx.write(Unpooled.EMPTY_BUFFER);
    this.networkManager.serversidePipeline = ctx.pipeline();
}

From source file:me.ferrybig.javacoding.teamspeakconnector.internal.handler.HandshakeListener.java

License:Open Source License

@Override
protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
    if (headerReceived) {
        if (!TS_HEADER_2.equals(msg)) {
            throw new DecoderException(
                    "Line 2 of magic header mismatch, expected: " + TS_HEADER_2 + "; got:" + msg);
        }//from  www  .j a  va  2s .c  om
        ctx.pipeline().remove(ReadTimeoutHandler.class);
        TeamspeakConnection con = new TeamspeakConnection(new TeamspeakIO(ctx.channel()));
        con.start();
        if (!prom.trySuccess(con)) {
            ctx.channel().close();
        }
        ctx.pipeline().remove(this);
    } else {
        headerReceived = true;
        if (TS_HEADER_1.equals(msg)) {
            return;
        }
        throw new DecoderException(
                "Line 1 of magic header mismatch, expected: " + TS_HEADER_1 + "; got:" + msg);
    }
}

From source file:me.jesonlee.jjfsserver.httpserver.HttpStaticFileServerHandler.java

License:Apache License

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

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

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

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

    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            sendListing(ctx, file);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        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;
        }
    }

    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);
    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() {
        @Override
        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);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            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:me.netty.http.handler.Http2OrHttpHandler.java

License:Apache License

@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
        ctx.pipeline().addLast(new Http2Codec(true, new HelloWorldHttp2Handler()));
        return;//from w  w w  . j  a v a2 s .co m
    }

    if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
        ctx.pipeline().addLast(new HttpServerCodec(), new HttpObjectAggregator(MAX_CONTENT_LENGTH),
                new Http1Handler());
        return;
    }

    throw new IllegalStateException("unknown protocol: " + protocol);
}

From source file:me.netty.http.Http2ServerInitializer.java

License:Apache License

/**
 * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0
 *///from  w  w w.  jav a  2 s.  c o  m
private void configureClearText(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    final HttpServerCodec sourceCodec = new HttpServerCodec();

    p.addLast(sourceCodec);
    p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory));
    p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
            // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP.
            ChannelPipeline pipeline = ctx.pipeline();
            ChannelHandlerContext thisCtx = pipeline.context(this);
            pipeline.addAfter(thisCtx.name(), null, new Http1Handler());
            pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength));
            ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
        }
    });

    p.addLast(new UserEventLogger());
}

From source file:mmo.server.RouteHandler.java

License:Open Source License

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    ctx.pipeline().addLast(dataToHttpEncoder);
    ctx.pipeline().addLast(PAGE_HANDLER_NAME, pageNotFoundHandler);
    ctx.pipeline().addLast(new ChannelHandlerAdapter() {
        @Override//from   w w  w  . j  a v  a2  s .c o  m
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            L.error("exception", cause);
        }
    });
    super.handlerAdded(ctx);
}

From source file:mmo.server.RouteHandler.java

License:Open Source License

private void installWebSocketHandler(ChannelHandlerContext ctx, String playerName, FullHttpRequest request) {
    L.debug("upgrading request {} to websocket", request.getUri());

    if (playerName == null || playerName.isEmpty()) {
        playerName = "anonymous";
    }/*from  www . j ava 2s .c o m*/

    // we replace all handlers, web socket will not be downgraded
    while (ctx.pipeline().last() != this) {
        ctx.pipeline().removeLast();
    }

    // add websocket handlers
    ctx.pipeline().addLast(new WebSocketServerProtocolHandler(request.getUri()),
            webSocketMessageHandlerProvider.get(), messageReceiverFactory.create(new Player(playerName)));

    // do handshake
    ctx.fireChannelRead(request);

    // route handler is not needed either
    ctx.pipeline().remove(this);
}

From source file:mmo.server.RouteHandler.java

License:Open Source License

private void installHandler(ChannelHandlerContext ctx, ChannelInboundHandler newHandler) {
    ctx.pipeline().replace(PAGE_HANDLER_NAME, PAGE_HANDLER_NAME, newHandler);
}

From source file:net.anyflow.menton.http.HttpRequestRouter.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (HttpHeaderValues.WEBSOCKET.toString().equalsIgnoreCase(request.headers().get(HttpHeaderNames.UPGRADE))
            && HttpHeaderValues.UPGRADE.toString()
                    .equalsIgnoreCase(request.headers().get(HttpHeaderNames.CONNECTION))) {

        if (ctx.pipeline().get(WebsocketFrameHandler.class) == null) {
            logger.error("No WebSocket Handler available.");

            ctx.channel()//w  w w  . ja v  a 2  s.  c  o  m
                    .writeAndFlush(
                            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN))
                    .addListener(ChannelFutureListener.CLOSE);
            return;
        }

        ctx.fireChannelRead(request.retain());
        return;
    }

    if (HttpUtil.is100ContinueExpected(request)) {
        ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
        return;
    }

    HttpResponse response = HttpResponse.createServerDefault(request.headers().get(HttpHeaderNames.COOKIE));

    String requestPath = new URI(request.uri()).getPath();

    if (isWebResourcePath(requestPath)) {
        handleWebResourceRequest(ctx, request, response, requestPath);
    } else {
        try {
            processRequest(ctx, request, response);
        } catch (URISyntaxException e) {
            response.setStatus(HttpResponseStatus.NOT_FOUND);
            logger.info("unexcepted URI : {}", request.uri());
        } catch (Exception e) {
            response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
            logger.error("Unknown exception was thrown in business logic handler.\r\n" + e.getMessage(), e);
        }
    }
}