Example usage for io.netty.channel ChannelHandlerContext fireChannelRead

List of usage examples for io.netty.channel ChannelHandlerContext fireChannelRead

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext fireChannelRead.

Prototype

@Override
    ChannelHandlerContext fireChannelRead(Object msg);

Source Link

Usage

From source file:com.cloudhopper.smpp.channel.SmppSessionThreadRenamer.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // always rename the current thread and then rename it back
    String currentThreadName = Thread.currentThread().getName();
    Thread.currentThread().setName(threadName);
    ctx.fireChannelRead(msg);
    Thread.currentThread().setName(currentThreadName);
}

From source file:com.comphenix.protocol.compat.netty.independent.NettyChannelInjector.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public boolean inject() {
    synchronized (networkManager) {
        if (closed)
            return false;
        if (originalChannel instanceof Factory)
            return false;
        if (!originalChannel.isActive())
            return false;

        // Main thread? We should synchronize with the channel thread, otherwise we might see a
        // pipeline with only some of the handlers removed
        if (Bukkit.isPrimaryThread()) {
            // Just like in the close() method, we'll avoid blocking the main thread
            executeInChannelThread(new Runnable() {
                @Override// w w  w .  j a v  a2 s.com
                public void run() {
                    inject();
                }
            });
            return false; // We don't know
        }

        // Don't inject the same channel twice
        if (findChannelHandler(originalChannel, NettyChannelInjector.class) != null) {
            return false;
        }

        // Get the vanilla decoder, so we don't have to replicate the work
        vanillaDecoder = (ByteToMessageDecoder) originalChannel.pipeline().get("decoder");
        vanillaEncoder = (MessageToByteEncoder<Object>) originalChannel.pipeline().get("encoder");

        if (vanillaDecoder == null)
            throw new IllegalArgumentException(
                    "Unable to find vanilla decoder in " + originalChannel.pipeline());
        if (vanillaEncoder == null)
            throw new IllegalArgumentException(
                    "Unable to find vanilla encoder in " + originalChannel.pipeline());
        patchEncoder(vanillaEncoder);

        if (DECODE_BUFFER == null)
            DECODE_BUFFER = Accessors.getMethodAccessor(vanillaDecoder.getClass(), "decode",
                    ChannelHandlerContext.class, ByteBuf.class, List.class);
        if (ENCODE_BUFFER == null)
            ENCODE_BUFFER = Accessors.getMethodAccessor(vanillaEncoder.getClass(), "encode",
                    ChannelHandlerContext.class, Object.class, ByteBuf.class);

        // Intercept sent packets
        MessageToByteEncoder<Object> protocolEncoder = new MessageToByteEncoder<Object>() {
            @Override
            protected void encode(ChannelHandlerContext ctx, Object packet, ByteBuf output) throws Exception {
                if (packet instanceof WirePacket) {
                    // Special case for wire format
                    NettyChannelInjector.this.encodeWirePacket((WirePacket) packet, new NettyByteBuf(output));
                } else {
                    NettyChannelInjector.this.encode(ctx, packet, output);
                }
            }

            @Override
            public void write(ChannelHandlerContext ctx, Object packet, ChannelPromise promise)
                    throws Exception {
                super.write(ctx, packet, promise);
                NettyChannelInjector.this.finalWrite(ctx, packet, promise);
            }
        };

        // Intercept recieved packets
        ChannelInboundHandlerAdapter finishHandler = new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                // Execute context first
                ctx.fireChannelRead(msg);
                NettyChannelInjector.this.finishRead(ctx, msg);
            }
        };

        // Insert our handlers - note that we effectively replace the vanilla encoder/decoder
        originalChannel.pipeline().addBefore("decoder", "protocol_lib_decoder", this);
        originalChannel.pipeline().addBefore("protocol_lib_decoder", "protocol_lib_finish", finishHandler);
        originalChannel.pipeline().addAfter("encoder", "protocol_lib_encoder", protocolEncoder);

        // Intercept all write methods
        channelField.setValue(new NettyChannelProxy(originalChannel, MinecraftReflection.getPacketClass()) {
            // Compatibility with Spigot 1.8
            private final NettyPipelineProxy pipelineProxy = new NettyPipelineProxy(originalChannel.pipeline(),
                    this) {
                @Override
                public ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler) {
                    // Correct the position of the decoder
                    if ("decoder".equals(baseName)) {
                        if (super.get("protocol_lib_decoder") != null && guessCompression(handler)) {
                            super.addBefore("protocol_lib_decoder", name, handler);
                            return this;
                        }
                    }

                    return super.addBefore(baseName, name, handler);
                }
            };

            @Override
            public ChannelPipeline pipeline() {
                return pipelineProxy;
            }

            @Override
            protected <T> Callable<T> onMessageScheduled(final Callable<T> callable,
                    FieldAccessor packetAccessor) {
                final PacketEvent event = handleScheduled(callable, packetAccessor);

                // Handle cancelled events
                if (event != null && event.isCancelled())
                    return null;

                return new Callable<T>() {
                    @Override
                    public T call() throws Exception {
                        T result = null;

                        // This field must only be updated in the pipeline thread
                        currentEvent = event;
                        result = callable.call();
                        currentEvent = null;
                        return result;
                    }
                };
            }

            @Override
            protected Runnable onMessageScheduled(final Runnable runnable, FieldAccessor packetAccessor) {
                final PacketEvent event = handleScheduled(runnable, packetAccessor);

                // Handle cancelled events
                if (event != null && event.isCancelled())
                    return null;

                return new Runnable() {
                    @Override
                    public void run() {
                        currentEvent = event;
                        runnable.run();
                        currentEvent = null;
                    }
                };
            }

            protected PacketEvent handleScheduled(Object instance, FieldAccessor accessor) {
                // Let the filters handle this packet
                Object original = accessor.get(instance);

                // See if we've been instructed not to process packets
                if (!scheduleProcessPackets.get()) {
                    NetworkMarker marker = getMarker(original);

                    if (marker != null) {
                        PacketEvent result = new PacketEvent(NettyChannelInjector.class);
                        result.setNetworkMarker(marker);
                        return result;
                    } else {
                        return BYPASSED_PACKET;
                    }
                }
                PacketEvent event = processSending(original);

                if (event != null && !event.isCancelled()) {
                    Object changed = event.getPacket().getHandle();

                    // Change packet to be scheduled
                    if (original != changed)
                        accessor.set(instance, changed);
                }
                ;
                return event != null ? event : BYPASSED_PACKET;
            }
        });

        injected = true;
        return true;
    }
}

From source file:com.comphenix.protocol.compat.netty.independent.NettyProtocolInjector.java

License:Open Source License

/**
 * Inject into the spigot connection class.
 *//* w  w w . j av a 2  s  .c  o  m*/
@Override
@SuppressWarnings("unchecked")
public synchronized void inject() {
    if (injected)
        throw new IllegalStateException("Cannot inject twice.");
    try {
        FuzzyReflection fuzzyServer = FuzzyReflection.fromClass(MinecraftReflection.getMinecraftServerClass());
        List<Method> serverConnectionMethods = fuzzyServer
                .getMethodListByParameters(MinecraftReflection.getServerConnectionClass(), new Class[] {});

        // Get the server connection
        Object server = fuzzyServer.getSingleton();
        Object serverConnection = null;

        for (Method method : serverConnectionMethods) {
            try {
                serverConnection = method.invoke(server);

                // Continue until we get a server connection
                if (serverConnection != null) {
                    break;
                }
            } catch (Exception e) {
                // Try the next though
                e.printStackTrace();
            }
        }

        // Handle connected channels
        final ChannelInboundHandler endInitProtocol = new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                try {
                    // This can take a while, so we need to stop the main thread from interfering
                    synchronized (networkManagers) {
                        injectionFactory.fromChannel(channel, NettyProtocolInjector.this, playerFactory)
                                .inject();
                    }
                } catch (Exception e) {
                    reporter.reportDetailed(NettyProtocolInjector.this, Report
                            .newBuilder(REPORT_CANNOT_INJECT_INCOMING_CHANNEL).messageParam(channel).error(e));
                }
            }
        };

        // This is executed before Minecraft's channel handler
        final ChannelInboundHandler beginInitProtocol = new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                // Our only job is to add init protocol
                channel.pipeline().addLast(endInitProtocol);
            }
        };

        // Add our handler to newly created channels
        final ChannelHandler connectionHandler = new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                Channel channel = (Channel) msg;

                // Prepare to initialize ths channel
                channel.pipeline().addFirst(beginInitProtocol);
                ctx.fireChannelRead(msg);
            }
        };

        // Get the current NetworkMananger list
        networkManagers = (List<Object>) FuzzyReflection.fromObject(serverConnection, true).invokeMethod(null,
                "getNetworkManagers", List.class, serverConnection);

        // Insert ProtocolLib's connection interceptor
        bootstrapFields = getBootstrapFields(serverConnection);

        for (VolatileField field : bootstrapFields) {
            final List<Object> list = (List<Object>) field.getValue();

            // We don't have to override this list
            if (list == networkManagers) {
                continue;
            }

            // Synchronize with each list before we attempt to replace them.
            field.setValue(new NettyBootstrapList(list, connectionHandler));
        }

        injected = true;

    } catch (Exception e) {
        throw new RuntimeException("Unable to inject channel futures.", e);
    }
}

From source file:com.comphenix.protocol.injector.netty.ChannelInjector.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public boolean inject() {
    synchronized (networkManager) {
        if (closed)
            return false;
        if (originalChannel instanceof Factory)
            return false;
        if (!originalChannel.isActive())
            return false;

        // Main thread? We should synchronize with the channel thread, otherwise we might see a
        // pipeline with only some of the handlers removed
        if (Bukkit.isPrimaryThread()) {
            // Just like in the close() method, we'll avoid blocking the main thread
            executeInChannelThread(new Runnable() {
                @Override/*from  w w w  . j  av  a2s  . c  o  m*/
                public void run() {
                    inject();
                }
            });
            return false; // We don't know
        }

        // Don't inject the same channel twice
        if (findChannelHandler(originalChannel, ChannelInjector.class) != null) {
            return false;
        }

        // Get the vanilla decoder, so we don't have to replicate the work
        vanillaDecoder = (ByteToMessageDecoder) originalChannel.pipeline().get("decoder");
        vanillaEncoder = (MessageToByteEncoder<Object>) originalChannel.pipeline().get("encoder");

        if (vanillaDecoder == null)
            throw new IllegalArgumentException(
                    "Unable to find vanilla decoder in " + originalChannel.pipeline());
        if (vanillaEncoder == null)
            throw new IllegalArgumentException(
                    "Unable to find vanilla encoder in " + originalChannel.pipeline());
        patchEncoder(vanillaEncoder);

        if (DECODE_BUFFER == null)
            DECODE_BUFFER = Accessors.getMethodAccessor(vanillaDecoder.getClass(), "decode",
                    ChannelHandlerContext.class, ByteBuf.class, List.class);
        if (ENCODE_BUFFER == null)
            ENCODE_BUFFER = Accessors.getMethodAccessor(vanillaEncoder.getClass(), "encode",
                    ChannelHandlerContext.class, Object.class, ByteBuf.class);

        // Intercept sent packets
        MessageToByteEncoder<Object> protocolEncoder = new MessageToByteEncoder<Object>() {
            @Override
            protected void encode(ChannelHandlerContext ctx, Object packet, ByteBuf output) throws Exception {
                if (packet instanceof WirePacket) {
                    // Special case for wire format
                    ChannelInjector.this.encodeWirePacket((WirePacket) packet, output);
                } else {
                    ChannelInjector.this.encode(ctx, packet, output);
                }
            }

            @Override
            public void write(ChannelHandlerContext ctx, Object packet, ChannelPromise promise)
                    throws Exception {
                super.write(ctx, packet, promise);
                ChannelInjector.this.finalWrite(ctx, packet, promise);
            }
        };

        // Intercept recieved packets
        ChannelInboundHandlerAdapter finishHandler = new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                // Execute context first
                ctx.fireChannelRead(msg);
                ChannelInjector.this.finishRead(ctx, msg);
            }
        };

        // Insert our handlers - note that we effectively replace the vanilla encoder/decoder
        originalChannel.pipeline().addBefore("decoder", "protocol_lib_decoder", this);
        originalChannel.pipeline().addBefore("protocol_lib_decoder", "protocol_lib_finish", finishHandler);
        originalChannel.pipeline().addAfter("encoder", "protocol_lib_encoder", protocolEncoder);

        // Intercept all write methods
        channelField.setValue(new ChannelProxy(originalChannel, MinecraftReflection.getPacketClass()) {
            // Compatibility with Spigot 1.8
            private final PipelineProxy pipelineProxy = new PipelineProxy(originalChannel.pipeline(), this) {
                @Override
                public ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler) {
                    // Correct the position of the decoder
                    if ("decoder".equals(baseName)) {
                        if (super.get("protocol_lib_decoder") != null && guessCompression(handler)) {
                            super.addBefore("protocol_lib_decoder", name, handler);
                            return this;
                        }
                    }

                    return super.addBefore(baseName, name, handler);
                }
            };

            @Override
            public ChannelPipeline pipeline() {
                return pipelineProxy;
            }

            @Override
            protected <T> Callable<T> onMessageScheduled(final Callable<T> callable,
                    FieldAccessor packetAccessor) {
                final PacketEvent event = handleScheduled(callable, packetAccessor);

                // Handle cancelled events
                if (event != null && event.isCancelled())
                    return null;

                return new Callable<T>() {
                    @Override
                    public T call() throws Exception {
                        T result = null;

                        // This field must only be updated in the pipeline thread
                        currentEvent = event;
                        result = callable.call();
                        currentEvent = null;
                        return result;
                    }
                };
            }

            @Override
            protected Runnable onMessageScheduled(final Runnable runnable, FieldAccessor packetAccessor) {
                final PacketEvent event = handleScheduled(runnable, packetAccessor);

                // Handle cancelled events
                if (event != null && event.isCancelled())
                    return null;

                return new Runnable() {
                    @Override
                    public void run() {
                        currentEvent = event;
                        runnable.run();
                        currentEvent = null;
                    }
                };
            }

            protected PacketEvent handleScheduled(Object instance, FieldAccessor accessor) {
                // Let the filters handle this packet
                Object original = accessor.get(instance);

                // See if we've been instructed not to process packets
                if (!scheduleProcessPackets.get()) {
                    NetworkMarker marker = getMarker(original);

                    if (marker != null) {
                        PacketEvent result = new PacketEvent(ChannelInjector.class);
                        result.setNetworkMarker(marker);
                        return result;
                    } else {
                        return BYPASSED_PACKET;
                    }
                }
                PacketEvent event = processSending(original);

                if (event != null && !event.isCancelled()) {
                    Object changed = event.getPacket().getHandle();

                    // Change packet to be scheduled
                    if (original != changed)
                        accessor.set(instance, changed);
                }
                ;
                return event != null ? event : BYPASSED_PACKET;
            }
        });

        injected = true;
        return true;
    }
}

From source file:com.comphenix.protocol.injector.netty.ProtocolInjector.java

License:Open Source License

/**
 * Inject into the spigot connection class.
 *//*from   w  ww  .  j  a  va  2  s .  c o m*/
@SuppressWarnings("unchecked")
public synchronized void inject() {
    if (injected)
        throw new IllegalStateException("Cannot inject twice.");
    try {
        FuzzyReflection fuzzyServer = FuzzyReflection.fromClass(MinecraftReflection.getMinecraftServerClass());
        List<Method> serverConnectionMethods = fuzzyServer
                .getMethodListByParameters(MinecraftReflection.getServerConnectionClass(), new Class[] {});

        // Get the server connection
        Object server = fuzzyServer.getSingleton();
        Object serverConnection = null;

        for (Method method : serverConnectionMethods) {
            try {
                serverConnection = method.invoke(server);

                // Continue until we get a server connection
                if (serverConnection != null) {
                    break;
                }
            } catch (Exception e) {
                // Try the next though
                e.printStackTrace();
            }
        }

        // Handle connected channels
        final ChannelInboundHandler endInitProtocol = new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(final Channel channel) throws Exception {
                try {
                    synchronized (networkManagers) {
                        // For some reason it needs to be delayed on 1.12, but the delay breaks 1.11 and below
                        // TODO I see this more as a temporary hotfix than a permanent solution
                        if (MinecraftVersion.getCurrentVersion().getMinor() >= 12) {
                            channel.eventLoop().submit(() -> injectionFactory
                                    .fromChannel(channel, ProtocolInjector.this, playerFactory).inject());
                        } else {
                            injectionFactory.fromChannel(channel, ProtocolInjector.this, playerFactory)
                                    .inject();
                        }
                    }
                } catch (Exception e) {
                    reporter.reportDetailed(ProtocolInjector.this, Report
                            .newBuilder(REPORT_CANNOT_INJECT_INCOMING_CHANNEL).messageParam(channel).error(e));
                }
            }
        };

        // This is executed before Minecraft's channel handler
        final ChannelInboundHandler beginInitProtocol = new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                // Our only job is to add init protocol
                channel.pipeline().addLast(endInitProtocol);
            }
        };

        // Add our handler to newly created channels
        final ChannelHandler connectionHandler = new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                Channel channel = (Channel) msg;

                // Prepare to initialize ths channel
                channel.pipeline().addFirst(beginInitProtocol);
                ctx.fireChannelRead(msg);
            }
        };

        FuzzyReflection fuzzy = FuzzyReflection.fromObject(serverConnection, true);

        try {
            List<Field> fields = fuzzy.getFieldListByType(List.class);
            for (Field field : fields) {
                ParameterizedType param = (ParameterizedType) field.getGenericType();
                if (param.getActualTypeArguments()[0].equals(MinecraftReflection.getNetworkManagerClass())) {
                    field.setAccessible(true);
                    networkManagers = (List<Object>) field.get(serverConnection);
                }
            }
        } catch (Exception ex) {
            networkManagers = (List<Object>) fuzzy
                    .getMethodByParameters("getNetworkManagers", List.class, serverConnection.getClass())
                    .invoke(null, serverConnection);
        }

        if (networkManagers == null) {
            throw new RuntimeException("Failed to obtain list of network managers.");
        }

        // Insert ProtocolLib's connection interceptor
        bootstrapFields = getBootstrapFields(serverConnection);

        for (VolatileField field : bootstrapFields) {
            final List<Object> list = (List<Object>) field.getValue();

            // We don't have to override this list
            if (list == networkManagers) {
                continue;
            }

            // Synchronize with each list before we attempt to replace them.
            field.setValue(new BootstrapList(list, connectionHandler));
        }

        injected = true;
    } catch (Exception e) {
        throw new RuntimeException("Unable to inject channel futures.", e);
    }
}

From source file:com.corundumstudio.socketio.handler.AuthorizeHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    SchedulerKey key = new SchedulerKey(Type.PING_TIMEOUT, ctx.channel());
    disconnectScheduler.cancel(key);/*  w w w . j av a  2s  . c o  m*/

    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        Channel channel = ctx.channel();
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());

        if (!configuration.isAllowCustomRequests() && !queryDecoder.path().startsWith(connectPath)) {
            HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
            channel.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
            req.release();
            log.warn("Blocked wrong request! url: {}, ip: {}", queryDecoder.path(), channel.remoteAddress());
            return;
        }

        List<String> sid = queryDecoder.parameters().get("sid");
        if (queryDecoder.path().equals(connectPath) && sid == null) {
            String origin = req.headers().get(HttpHeaders.Names.ORIGIN);
            if (!authorize(ctx, channel, origin, queryDecoder.parameters(), req)) {
                req.release();
                return;
            }
            // forward message to polling or websocket handler to bind channel
        }
    }
    ctx.fireChannelRead(msg);
}

From source file:com.corundumstudio.socketio.handler.ResourceHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        URL resUrl = resources.get(queryDecoder.path());
        if (resUrl != null) {
            URLConnection fileUrl = resUrl.openConnection();
            long lastModified = fileUrl.getLastModified();
            // check if file has been modified since last request
            if (isNotModified(req, lastModified)) {
                sendNotModified(ctx);//from  ww w.j  a v  a 2  s  . c  o  m
                req.release();
                return;
            }
            // create resource input-stream and check existence
            final InputStream is = fileUrl.getInputStream();
            if (is == null) {
                sendError(ctx, NOT_FOUND);
                return;
            }
            // create ok response
            HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
            // set Content-Length header
            setContentLength(res, fileUrl.getContentLength());
            // set Content-Type header
            setContentTypeHeader(res, fileUrl);
            // set Date, Expires, Cache-Control and Last-Modified headers
            setDateAndCacheHeaders(res, lastModified);
            // write initial response header
            ctx.write(res);

            // write the content stream
            ctx.pipeline().addBefore(SocketIOChannelInitializer.RESOURCE_HANDLER, "chunkedWriter",
                    new ChunkedWriteHandler());
            ChannelFuture writeFuture = ctx.channel().write(new ChunkedStream(is, fileUrl.getContentLength()));
            // add operation complete listener so we can close the channel and the input stream
            writeFuture.addListener(ChannelFutureListener.CLOSE);
            return;
        }
    }
    ctx.fireChannelRead(msg);
}

From source file:com.corundumstudio.socketio.transport.FlashPolicyHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof ByteBuf) {
        ByteBuf message = (ByteBuf) msg;
        ByteBuf data = message.slice(0, requestBuffer.readableBytes());
        if (data.equals(requestBuffer)) {
            message.release();//  w  w  w .  ja  v a 2  s.  c  om
            ChannelFuture f = ctx.writeAndFlush(Unpooled.copiedBuffer(responseBuffer));
            f.addListener(ChannelFutureListener.CLOSE);
            return;
        }
        ctx.pipeline().remove(this);
    }
    ctx.fireChannelRead(msg);
}

From source file:com.corundumstudio.socketio.transport.FlashUrlLoaderPolicyHandler.java

License:Apache License

/**
 * Channel read callback/*from w  ww .  j av  a  2 s  .  c  o m*/
 *
 * @param ctx
 * @param msg
 * @throws Exception
 */
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        final FullHttpRequest request = (FullHttpRequest) msg;
        if (request.getUri().contains("crossdomain.xml")) {
            writeCrossdomainDotXml(ctx, request);
            request.release();
            ctx.pipeline().remove(this);
            return;
        }
        ctx.pipeline().remove(this);
    }
    ctx.fireChannelRead(msg);
}

From source file:com.corundumstudio.socketio.transport.PollingTransport.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());

        List<String> transport = queryDecoder.parameters().get("transport");

        if (transport != null && NAME.equals(transport.get(0))) {
            List<String> sid = queryDecoder.parameters().get("sid");
            List<String> j = queryDecoder.parameters().get("j");
            List<String> b64 = queryDecoder.parameters().get("b64");

            String origin = req.headers().get(HttpHeaders.Names.ORIGIN);
            ctx.channel().attr(EncoderHandler.ORIGIN).set(origin);

            String userAgent = req.headers().get(HttpHeaders.Names.USER_AGENT);
            ctx.channel().attr(EncoderHandler.USER_AGENT).set(userAgent);

            if (j != null && j.get(0) != null) {
                Integer index = Integer.valueOf(j.get(0));
                ctx.channel().attr(EncoderHandler.JSONP_INDEX).set(index);
            }/*from  w w  w .jav  a 2 s  .c o m*/
            if (b64 != null && b64.get(0) != null) {
                Integer enable = Integer.valueOf(b64.get(0));
                ctx.channel().attr(EncoderHandler.B64).set(enable == 1);
            }

            try {
                if (sid != null && sid.get(0) != null) {
                    final UUID sessionId = UUID.fromString(sid.get(0));
                    handleMessage(req, sessionId, queryDecoder, ctx);
                } else {
                    // first connection
                    ClientHead client = ctx.channel().attr(ClientHead.CLIENT).get();
                    handleMessage(req, client.getSessionId(), queryDecoder, ctx);
                }
            } finally {
                req.release();
            }
            return;
        }
    }
    ctx.fireChannelRead(msg);
}