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:net.hasor.rsf.protocol.rsf.RsfDecoder.java

License:Apache License

protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    ByteBuf frame = (ByteBuf) super.decode(ctx, in);
    if (frame == null) {
        return null;
    }// ww  w .ja va 2  s  .  co m
    //
    byte rsfHead = frame.getByte(0);//??
    short status = this.doDecode(rsfHead, ctx, frame);//???
    if (status != ProtocolStatus.OK) {
        frame = frame.resetReaderIndex().skipBytes(1);
        long requestID = frame.readLong();
        ResponseInfo info = ProtocolUtils.buildResponseStatus(this.rsfEnvironment, requestID, status, null);
        ctx.pipeline().writeAndFlush(info);
    }
    return null;
}

From source file:net.hasor.rsf.remoting.transport.netty.RSFProtocolDecoder.java

License:Apache License

/**?? */
private void fireProtocolError(ChannelHandlerContext ctx, byte oriVersion, long requestID, short status) {
    byte version = ProtocolUtils.getVersion(oriVersion);
    ResponseMsg error = TransferUtils.buildStatus(//
            version, requestID, status, "BlackHole", null);
    ctx.pipeline().writeAndFlush(error);
}

From source file:net.hasor.rsf.remoting.transport.provider.RsfProviderHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof RequestMsg == false) {
        return;//from  www. java  2  s  .c  o m
    }
    //request?response
    RequestMsg requestMsg = (RequestMsg) msg;
    requestMsg.setReceiveTime(System.currentTimeMillis());
    LoggerHelper.logFinest("received request(%s) full = %s", requestMsg.getRequestID(), requestMsg);
    //
    try {
        Executor exe = this.rsfContext.getCallExecute(requestMsg.getServiceName());
        NetworkConnection conn = NetworkConnection.getConnection(ctx.channel());
        exe.execute(new InnerRequestHandler(this.rsfContext, requestMsg, conn));
        //
        ResponseMsg pack = TransferUtils.buildStatus(//
                requestMsg.getVersion(), //??
                requestMsg.getRequestID(), //ID
                ProtocolStatus.Accepted, //??
                this.serializeType, //?
                this.rsfContext.getSettings().getServerOption());//?
        ctx.pipeline().writeAndFlush(pack);
    } catch (RejectedExecutionException e) {
        ResponseMsg pack = TransferUtils.buildStatus(//
                requestMsg.getVersion(), //??
                requestMsg.getRequestID(), //ID
                ProtocolStatus.ChooseOther, //??
                this.serializeType, //?
                this.rsfContext.getSettings().getServerOption());//?
        ctx.pipeline().writeAndFlush(pack);
    }
}

From source file:net.ieldor.network.codec.handshake.HandshakeDecoder.java

License:Open Source License

@Override
public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    if (!in.readable())
        return;//from w  w  w .ja v a 2 s  .c  o m
    ctx.pipeline().remove(HandshakeDecoder.class);

    int incomingOpcode = in.readByte() & 0xFF;
    //System.out.println("Received handshake opcode: "+incomingOpcode);
    HandshakeState handshakeState = HandshakeState.forId(incomingOpcode);

    if (handshakeState == null)
        return;
    switch (handshakeState) {
    case HANDSHAKE_UPDATE:
        ctx.pipeline().addFirst(new UpdateEncoder(), new UpdateStatusEncoder(), new XorEncoder(),
                new UpdateDecoder());
        break;
    case HANDSHAKE_WORLD_LIST:
        ctx.pipeline().addFirst(new WorldListEncoder(), new WorldListDecoder());
        break;
    case HANDSHAKE_LOGIN:
        ctx.pipeline().addFirst(new LoginEncoder(), new LoginDataEncoder());
        ctx.pipeline().addFirst("decoder", new LoginDecoder());
        ctx.write(new LoginResponse(0));
        break;
    default:
        break;
    }

    ctx.nextInboundMessageBuffer().add(new HandshakeMessage(handshakeState));
    ctx.fireInboundBufferUpdated();

    if (in.readable()) {
        ChannelHandlerContext head = ctx.pipeline().firstContext();
        head.nextInboundByteBuffer().writeBytes(in.readBytes(in.readableBytes()));
        head.fireInboundBufferUpdated();
    }
}

From source file:net.minecrell.quartz.mixin.network.MixinLegacyPingHandler.java

License:MIT License

@Override
@Overwrite//from   w  w  w  . j a va  2 s.c om
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf m = (ByteBuf) msg;
    this.buf.writeBytes(m);
    m.release();

    this.buf.markReaderIndex();
    boolean result = false;

    try {
        result = readLegacy(ctx, this.buf);
    } finally {
        this.buf.resetReaderIndex();
        if (!result) {
            ByteBuf buf = this.buf;
            this.buf = null;

            ctx.pipeline().remove("legacy_query");
            ctx.fireChannelRead(buf);
        }
    }
}

From source file:net.NettyEngine4.file.HttpStaticFileServerHandler.java

License:Apache License

/**
 * <strong>Please keep in mind that this method will be renamed to
 * {@code messageReceived(ChannelHandlerContext, I)} in 5.0.</strong>
 * <p/>//from   ww  w.  jav  a  2 s. c  o  m
 * Is called for each message of type {@link SimpleChannelInboundHandler#channelRead0(io.netty.channel.ChannelHandlerContext, Object)}.
 *
 * @param ctx     the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
 *                belongs to
 * @param request the message to handle
 * @throws Exception is thrown if an error occurred
 */
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);
        return;
    }

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

    final String uri = request.getUri();
    final String path = 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;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
    } else {
        sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
    }

    /**
     *
     */
    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                LOGGER.debug(future.channel() + " Transfer progress: " + progress);
            } else {
                LOGGER.debug(future.channel() + " Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            LOGGER.debug(future.channel() + " Transfer complete.");
        }
    });

    // Write the end marker
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // 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:net.sourceforge.entrainer.socket.PortUnificationHandler.java

License:Open Source License

private void switchToWebSockets(ChannelHandlerContext ctx) throws Exception {
    ChannelPipeline pipeline = ctx.pipeline();

    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("handler", webSocketHandler);
    webSocketHandler.channelActive(ctx);

    pipeline.remove(this);
}

From source file:net.sourceforge.entrainer.socket.PortUnificationHandler.java

License:Open Source License

private void switchToJava(ChannelHandlerContext ctx) throws Exception {
    ChannelPipeline pipeline = ctx.pipeline();

    pipeline.addLast(new LengthFieldBasedFrameDecoder(10000, 0, 4, 0, 4));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new LengthFieldPrepender(4));
    pipeline.addLast(new StringEncoder());
    pipeline.addLast(nettyConnectionHandler);
    nettyConnectionHandler.channelActive(ctx);

    pipeline.remove(this);
}

From source file:net.tridentsdk.server.window.TridentWindow.java

License:Apache License

@Volatile(policy = "DO NOT INVOKE OUTSIDE OF THIS CLASS", reason = "Extremely unsafe and causes unspecified behavior without proper handling", fix = "Do not use reflection on this method")
private void addClosedListener(Player player) {
    final PlayerConnection connection = ((TridentPlayer) player).getConnection();
    connection.getChannel().pipeline().addLast(new ChannelHandlerAdapter() {
        @Override/*from  w  w  w. j  a v a2 s  .c  o  m*/
        // Occurs after the message should be decoded
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof PacketPlayInPlayerCloseWindow) {
                PacketPlayInPlayerCloseWindow windowClose = (PacketPlayInPlayerCloseWindow) msg;
                if (windowClose.getWindowId() == getId())
                    for (Player player1 : users)
                        if (connection.getChannel().equals(ctx.channel())) {
                            users.remove(player1);
                            ctx.pipeline().remove(this);
                        }
            }

            // Pass to the next channel handler
            super.channelRead(ctx, msg);
        }
    });
}

From source file:netkernel.HttpRequestResponseAdapterChannelHandler.java

License:Apache License

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    super.channelReadComplete(ctx);
    ctx.pipeline().flush();
}