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.witjit.game.server.communication.netty.handler.NodeChannelInitializer.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!bindNode(ctx.channel(), (ByteBuf) msg)) {
        return;//  w ww .j  a  v  a 2s  .c  o m
    }
    initChannel(ctx.channel());
    ctx.pipeline().remove(this);
    ctx.fireChannelRead(msg);
}

From source file:com.xmpp.push.androidpn.server.xmpp.handler.XMLElementDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {

    if (LOG.isTraceEnabled()) {
        LOG.trace("receive msg=[{}], channel=[{}]", new Object[] { msg, ctx.channel() });
    }/*from   ww w . j  a  v  a2 s .  c o  m*/

    if (msg instanceof XMLEventObj) {

        XMLEventObj obj = (XMLEventObj) msg;
        if (obj.isEmpty()) {
            LOG.warn("xmlEventObj is empty.");
            return;
        }

        List<XMLEvent> events = obj.getEvents();

        Document document = XMLUtil.newDocument();
        DOMResult result = new DOMResult(document);
        XMLEventWriter writer = XMLOUTPUTFACTORY.createXMLEventWriter(result);
        if (null == writer || null == document) {
            LOG.warn("writer is null or document is null.");
            return;
        }

        for (XMLEvent event : events) {

            try {
                if (null != writer)
                    writer.add(event);
            } catch (Exception ex) {
                //
            }

            if (event.getEventType() == AsyncXMLStreamReader.EVENT_INCOMPLETE) {
                try {
                    if (null != writer && null != document) {
                        writer.flush();
                        Element element = document.getDocumentElement();
                        XMLElement xelement = XMLElementImpl.fromElement(element);
                        ctx.fireChannelRead(xelement);
                    }
                } catch (Exception ex) {
                    // LOG.error("xml element decoder has execptor: " + ex);
                } finally {
                    if (null != writer) {
                        writer.close();
                        writer = null;
                    }
                    result = null;
                    document = null;
                }
            }

        }

        return;
    }

}

From source file:com.xmpp.push.androidpn.server.xmpp.handler.XMPPDecodeHandler.java

License:Apache License

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

    if (LOG.isDebugEnabled()) {
        LOG.debug("received msg=[{}]", msg);
    }//from  w w  w  . j  a v a2  s .  c  om

    Channel channel = ctx.channel();

    if (msg instanceof XMLElement) {
        final XMLElement element = (XMLElement) msg;

        switch (status) {

        // 1. 
        case CONNECT:

            if ("stream:stream".equals(element.getTagName())) {

                // // to=""
                // if (!serverName.equals(element.getAttributeByName(
                // new QName("to")).getValue())) {
                // throw new Exception("server name mismatch");
                // }

                status = Status.STARTEDTLS;
                // status = Status.READY;

                // client?tls,?????
                channel.writeAndFlush(startResp());

                if (LOG.isDebugEnabled())
                    LOG.debug("client channel=[{}] connect ok", channel);
            }
            break;

        // 2. ?starttls
        case STARTEDTLS:

            if ("starttls".equals(element.getTagName())) {

                status = Status.TLSCONNECT;
                starttls = false;

                // ??
                String xml = "<proceed xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>";
                channel.writeAndFlush(xml);

                // add tls handler
                channel.pipeline().addFirst("tls", sslHandler);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("client start tls ok. channel=[{}]", channel);
                }

                // ctx.sendUpstream(e);
                ctx.fireChannelRead(msg);
                break;
            }

        // ?tls?
        {
            if (LOG.isDebugEnabled()) {
                LOG.debug("client request msg by channel=[{}]", channel);
            }

            status = Status.READY;

            final Packet stanza = Packet.fromElement(element);
            if (stanza == null)
                throw new Exception("Unknown stanza");

            ctx.fireChannelRead(stanza);
            break;
        }

        // 3.?tlstls?
        case TLSCONNECT:

            if ("stream:stream".equals(element.getTagName())) {

                status = Status.READY;

                // client
                channel.writeAndFlush(tlsNegotiated());

                if (LOG.isDebugEnabled()) {
                    LOG.debug("client tls connect ok. channel=[{}]", channel);
                }
            }
            break;

        // 4.tls?iq
        case READY:

            if (LOG.isDebugEnabled()) {
                LOG.debug("client request msg by channel=[{}]", channel);
            }

            final Packet stanza = Packet.fromElement(element);
            if (stanza == null)
                throw new Exception("Unknown stanza");

            // handler?
            ctx.fireChannelRead(stanza);
            break;

        default:
            throw new Exception("unexpected handleElement");
        }
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:com.xmpp.push.androidpn.server.xmpp.handler.XMPPHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof Packet)) {
        ctx.fireChannelRead(msg);
        return;/*from  w  w  w .j  ava 2 s .  c  o m*/
    }

    // router the xmpp request
    Channel channel = ctx.channel();
    final Packet stanza = (Packet) msg;
    if (stanza instanceof Message) {

        Message message = (Message) stanza;

        if (LOG.isDebugEnabled())
            LOG.debug("message: [{}]", message);

        messageRouter.route(channel, message);

    } else if (stanza instanceof Presence) {

        // 
        Presence presence = (Presence) stanza;

        if (LOG.isDebugEnabled())
            LOG.debug("presence: [{}], from: [{}], to: [{}], type: [{}]",
                    new Object[] { presence.getId(), presence.getFrom(), presence.getType() });

        presenceRouter.route(channel, presence);
    } else if (stanza instanceof IQ) {

        IQ iq = (IQ) stanza;

        if (LOG.isDebugEnabled())
            LOG.debug("iq: [{}]", iq);

        iqRouter.route(channel, iq);
    }
}

From source file:com.xx_dev.apn.proxy.ApnProxySchemaHandler.java

License:Apache License

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

    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        String originalHost = HostNamePortUtil.getHostName(httpRequest);
        int originalPort = HostNamePortUtil.getPort(httpRequest);

        ApnProxyRemote apnProxyRemote = ApnProxyRemoteChooser.chooseRemoteAddr(originalHost, originalPort);

        Channel uaChannel = uaChannelCtx.channel();

        ApnProxyConnectionAttribute apnProxyConnectionAttribute = ApnProxyConnectionAttribute.build(
                uaChannel.remoteAddress().toString(), httpRequest.getMethod().name(), httpRequest.getUri(),
                httpRequest.getProtocolVersion().text(),
                httpRequest.headers().get(HttpHeaders.Names.USER_AGENT), apnProxyRemote);

        uaChannelCtx.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute);
        uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute);

        if (httpRequest.getMethod().equals(HttpMethod.CONNECT)) {
            if (uaChannelCtx.pipeline().get(ApnProxyUserAgentForwardHandler.HANDLER_NAME) != null) {
                uaChannelCtx.pipeline().remove(ApnProxyUserAgentForwardHandler.HANDLER_NAME);
            }//from  ww  w  .j  av  a2 s  . c o  m
            if (uaChannelCtx.pipeline().get(ApnProxyUserAgentTunnelHandler.HANDLER_NAME) == null) {
                uaChannelCtx.pipeline().addLast(ApnProxyUserAgentTunnelHandler.HANDLER_NAME,
                        new ApnProxyUserAgentTunnelHandler());
            }
        } else {
            if (uaChannelCtx.pipeline().get(ApnProxyUserAgentForwardHandler.HANDLER_NAME) == null) {
                uaChannelCtx.pipeline().addLast(ApnProxyUserAgentForwardHandler.HANDLER_NAME,
                        new ApnProxyUserAgentForwardHandler());
            }
        }
    }

    LoggerUtil.debug(logger, uaChannelCtx.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "UA msg", msg);

    uaChannelCtx.fireChannelRead(msg);
}

From source file:com.xx_dev.apn.socks.remote.SocksServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, SocksRequest socksRequest) throws Exception {
    switch (socksRequest.requestType()) {
    case INIT: {/*  w  w w  .j a  v  a2 s. co  m*/
        // auth support example
        //ctx.pipeline().addFirst(new SocksAuthRequestDecoder());
        //ctx.write(new SocksInitResponse(SocksAuthScheme.AUTH_PASSWORD));
        ctx.pipeline().addAfter("log", "cmdRequstDecoder", new SocksCmdRequestDecoder());
        ctx.write(new SocksInitResponse(SocksAuthScheme.NO_AUTH));
        break;
    }
    case AUTH:
        ctx.pipeline().addAfter("log", "cmdRequstDecoder", new SocksCmdRequestDecoder());
        ctx.write(new SocksAuthResponse(SocksAuthStatus.SUCCESS));
        break;
    case CMD:
        SocksCmdRequest req = (SocksCmdRequest) socksRequest;
        if (req.cmdType() == SocksCmdType.CONNECT) {
            ctx.pipeline().addLast(new SocksServerConnectHandler());
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(socksRequest);
        } else {
            ctx.close();
        }
        break;
    case UNKNOWN:
        ctx.close();
        break;
    }
}

From source file:com.yea.dispatcher.netty.handle.DispatchClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    Message message = (Message) msg;//w w w . j  a va 2 s.c  o  m
    if (message.getHeader() != null
            && message.getHeader().getType() == RemoteConstants.MessageType.CONSUMER_REGISTER_RESULT.value()) {
        SocketAddress address = (SocketAddress) message.getBody();
        mapConsumer.put(address, message.getHeader().getSessionID());
    } else if (message.getHeader() != null
            && message.getHeader().getType() == RemoteConstants.MessageType.CONSUMER_LOGOUT_RESULT.value()) {
        SocketAddress address = (SocketAddress) message.getBody();
        byte[] sessionID = mapConsumer.get(address);
        mapConsumer.remove(address);
        notifyObservers(sessionID, message.getHeader(), address);
    } else if (message.getHeader() != null
            && message.getHeader().getType() == RemoteConstants.MessageType.PROVIDER_DISCOVER_RESULT.value()) {
        notifyObservers(message.getHeader().getSessionID(), message.getHeader(), message.getBody());
    } else if (message.getHeader() != null
            && message.getHeader().getType() == RemoteConstants.MessageType.PROVIDER_REGISTER_NOTIFY.value()) {
        Object[] params = (Object[]) message.getBody();
        byte[] sessionID = mapConsumer.get(params[0]);
        if (sessionID != null) {
            notifyObservers(sessionID, message.getHeader(), params[1]);
        }
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:com.yea.dispatcher.netty.handle.DispatchServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    Message message = (Message) msg;/*from w ww  .  j  av  a 2 s. c  o  m*/
    Object[] params = (Object[]) message.getBody();
    if (message.getHeader() != null && (message.getHeader()
            .getType() == RemoteConstants.MessageType.CONSUMER_REGISTER.value()
            || message.getHeader().getType() == RemoteConstants.MessageType.PROVIDER_REGISTER.value())) {
        if (!mapDispatch.containsKey(params[0])) {
            // ????
            Map<String, List<SocketAddress>> map = new ConcurrentHashMap<String, List<SocketAddress>>();
            map.put(RemoteConstants.DispatchType.CONSUMER.value(), new CopyOnWriteArrayList<SocketAddress>());
            map.put(RemoteConstants.DispatchType.PROVIDER.value(), new CopyOnWriteArrayList<SocketAddress>());
            mapDispatch.put((String) params[0], map);
        }
        if (message.getHeader().getType() == RemoteConstants.MessageType.CONSUMER_REGISTER.value()) {
            LOGGER.info(
                    "[" + params[1] + "]??[" + params[0] + "]");
            mapChannel.put((SocketAddress) params[1], ctx.channel());
            mapDispatch.get(params[0]).get(RemoteConstants.DispatchType.CONSUMER.value())
                    .add((SocketAddress) params[1]);
            //????
            Message resp = buildResp(RemoteConstants.MessageType.CONSUMER_REGISTER_RESULT,
                    message.getHeader().getSessionID(), params[1]);
            ctx.writeAndFlush(resp);
        } else {
            LOGGER.info("[" + params[1] + "]?????[" + params[0]
                    + "]");
            mapDispatch.get(params[0]).get(RemoteConstants.DispatchType.PROVIDER.value())
                    .add((SocketAddress) params[1]);
            //??????
            List<SocketAddress> listConsumer = mapDispatch.get(params[0])
                    .get(RemoteConstants.DispatchType.CONSUMER.value());
            for (SocketAddress address : listConsumer) {
                Channel channel = mapChannel.get(address);
                Object[] obj = new Object[] { address, params[1] };
                Message resp = buildResp(RemoteConstants.MessageType.PROVIDER_REGISTER_NOTIFY,
                        UUIDGenerator.generate(), obj);
                channel.writeAndFlush(resp);
            }
        }
    } else if (message.getHeader() != null
            && (message.getHeader().getType() == RemoteConstants.MessageType.CONSUMER_LOGOUT.value()
                    || message.getHeader().getType() == RemoteConstants.MessageType.PROVIDER_LOGOUT.value())) {
        if (mapDispatch.containsKey(params[0])) {
            if (message.getHeader().getType() == RemoteConstants.MessageType.CONSUMER_LOGOUT.value()) {
                LOGGER.info("[" + params[1] + "]??[" + params[0]
                        + "]");
                mapChannel.remove((SocketAddress) params[1]);
                mapDispatch.get(params[0]).get(RemoteConstants.DispatchType.CONSUMER.value())
                        .remove((SocketAddress) params[1]);
                //????
                Message resp = buildResp(RemoteConstants.MessageType.CONSUMER_LOGOUT_RESULT,
                        message.getHeader().getSessionID(), params[1]);
                ctx.writeAndFlush(resp);
            } else {
                LOGGER.info("[" + params[1] + "]?????["
                        + params[0] + "]");
                mapDispatch.get(params[0]).get(RemoteConstants.DispatchType.PROVIDER.value())
                        .remove((SocketAddress) params[1]);
            }
        }
    } else if (message.getHeader() != null
            && message.getHeader().getType() == RemoteConstants.MessageType.PROVIDER_DISCOVER.value()) {
        if (mapDispatch.containsKey(params[0])) {
            List<SocketAddress> listProvider = mapDispatch.get(params[0])
                    .get(RemoteConstants.DispatchType.PROVIDER.value());
            LOGGER.info("??[" + params[0] + "]??" + listProvider.size()
                    + "??" + listProvider + "");
            Message resp = buildResp(RemoteConstants.MessageType.PROVIDER_DISCOVER_RESULT,
                    message.getHeader().getSessionID(), listProvider);
            ctx.writeAndFlush(resp);
        } else {
            LOGGER.info("??[" + params[0] + "]??0");
            Message resp = buildResp(RemoteConstants.MessageType.PROVIDER_DISCOVER_RESULT,
                    message.getHeader().getSessionID(), new ArrayList<SocketAddress>());
            ctx.writeAndFlush(resp);
        }
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:com.yea.remote.netty.client.handle.LoginAuthClientHandler.java

License:Apache License

/**
 * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward to
 * the next {@link ChannelHandler} in the {@link ChannelPipeline}.
 * /* w ww  . ja v a  2 s . c  o m*/
 * Sub-classes may override this method to change behavior.
 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Message message = (Message) msg;

    // ??????
    if (message.getHeader() != null
            && message.getHeader().getType() == RemoteConstants.MessageType.LOGIN_RESP.value()) {
        Byte loginResult = (Byte) message.getHeader().getResult();
        if (loginResult.byteValue() != RemoteConstants.MessageResult.SUCCESS.value()) {
            // ?
            ctx.channel().close();
            ctx.close();
        }
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:com.yea.remote.netty.client.handle.ServiceClientHandler.java

License:Apache License

@Override
protected void execute(ChannelHandlerContext ctx, Message message) throws Exception {
    // TODO Auto-generated method stub
    if (message.getHeader().getType() == RemoteConstants.MessageType.SERVICE_RESP.value()) {
        long times = new Date().getTime() - ((Date) message.getHeader().getAttachment()
                .get(NettyConstants.MessageHeaderAttachment.REQUEST_DATE.value())).getTime();
        if (times > NettyConstants.SLOW_LIMIT) {
            LOGGER.warn(/*from   w w w.j a  v a  2 s  . co m*/
                    "{}{}?[:{}], {}(){}(:{})?{}?{}(:{}),?:{}",
                    ctx.channel().localAddress(), ctx.channel().remoteAddress(),
                    UUIDGenerator.restore(message.getHeader().getSessionID()), times,
                    ((Date) message.getHeader().getAttachment()
                            .get(NettyConstants.MessageHeaderAttachment.REQUEST_RECIEVE_DATE.value())).getTime()
                            - ((Date) message.getHeader().getAttachment()
                                    .get(NettyConstants.MessageHeaderAttachment.REQUEST_DATE.value()))
                                            .getTime(),
                    ((Date) message.getHeader().getAttachment()
                            .get(NettyConstants.MessageHeaderAttachment.REQUEST_RECIEVE_DATE.value())).getTime()
                            - ((Date) message.getHeader().getAttachment()
                                    .get(NettyConstants.MessageHeaderAttachment.REQUEST_SEND_DATE.value()))
                                            .getTime(),
                    ((Date) message.getHeader().getAttachment()
                            .get(NettyConstants.MessageHeaderAttachment.HEADER_DATE.value())).getTime()
                            - ((Date) message.getHeader().getAttachment()
                                    .get(NettyConstants.MessageHeaderAttachment.REQUEST_RECIEVE_DATE.value()))
                                            .getTime(),
                    new Date().getTime() - ((Date) message.getHeader().getAttachment()
                            .get(NettyConstants.MessageHeaderAttachment.HEADER_DATE.value())).getTime(),
                    new Date().getTime() - ((Date) message.getHeader().getAttachment()
                            .get(NettyConstants.MessageHeaderAttachment.SEND_DATE.value())).getTime(),
                    message.getHeader().getLength());
        } else {
            LOGGER.info(
                    "{}{}?[:{}], {}{}(:{})?{}?{}(:{}),?:{}",
                    ctx.channel().localAddress(), ctx.channel().remoteAddress(),
                    UUIDGenerator.restore(message.getHeader().getSessionID()), times,
                    ((Date) message.getHeader().getAttachment()
                            .get(NettyConstants.MessageHeaderAttachment.REQUEST_RECIEVE_DATE.value())).getTime()
                            - ((Date) message.getHeader().getAttachment()
                                    .get(NettyConstants.MessageHeaderAttachment.REQUEST_DATE.value()))
                                            .getTime(),
                    ((Date) message.getHeader().getAttachment()
                            .get(NettyConstants.MessageHeaderAttachment.REQUEST_RECIEVE_DATE.value())).getTime()
                            - ((Date) message.getHeader().getAttachment()
                                    .get(NettyConstants.MessageHeaderAttachment.REQUEST_SEND_DATE.value()))
                                            .getTime(),
                    ((Date) message.getHeader().getAttachment()
                            .get(NettyConstants.MessageHeaderAttachment.HEADER_DATE.value())).getTime()
                            - ((Date) message.getHeader().getAttachment()
                                    .get(NettyConstants.MessageHeaderAttachment.REQUEST_RECIEVE_DATE.value()))
                                            .getTime(),
                    new Date().getTime() - ((Date) message.getHeader().getAttachment()
                            .get(NettyConstants.MessageHeaderAttachment.HEADER_DATE.value())).getTime(),
                    new Date().getTime() - ((Date) message.getHeader().getAttachment()
                            .get(NettyConstants.MessageHeaderAttachment.SEND_DATE.value())).getTime(),
                    message.getHeader().getLength());
        }

        if (message.getHeader().getAttachment()
                .get(NettyConstants.MessageHeaderAttachment.CALL_ACT.value()) != null) {
            pool.execute(new InnerTask(this.getApplicationContext(), message));
        }

        notifyObservers(message.getHeader().getSessionID(), message.getHeader(), message.getBody());
    } else {
        ctx.fireChannelRead(message);
    }
}