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.zextras.modules.chat.server.xmpp.netty.FirstTags.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    String xmlTag = (String) msg;
    ChatLog.log.debug("FirstTags: " + xmlTag);

    if (xmlTag.startsWith("<?xml")) {
        //TODO: parse new charset
        Charset newCharset = Charset.forName("UTF-8");

        ctx.pipeline().replace("SubTagTokenizer", "SubTagTokenizer", new XmlSubTagTokenizer(newCharset));
    } else {//from  w  w  w.j ava 2s .  c  om
        if (xmlTag.trim().startsWith("<stream:stream")) {
            ctx.pipeline().addLast("XmlTagTokenizer", new XmlTagTokenizer());

            ctx.pipeline().addLast("StanzaProcessor",
                    new StanzaProcessor(mXmppHandlerFactory, mEventManager, mSocketChannel, mSchemaProvider,
                            mZimbraSSLContext, mSsl, mChatProperties, mNettyService, mProxyAuthRequestEncoder,
                            mXmppEventFilter, mXmppFilterOut));
            ctx.fireChannelRead(xmlTag);
            // ctx.fireChannelRead("</stream:stream>");
            ctx.pipeline().remove("FirstTags");
        } else {
            throw new RuntimeException("Invalid first xml tag: " + xmlTag);
        }
    }
}

From source file:com.zhaopeng.timeserver.protocol.netty.client.HeartBeatReqHandler.java

License:Apache License

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;
    // ?????/*  w ww .j ava  2  s.c o m*/
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatTask(ctx), 0, 5000, TimeUnit.MILLISECONDS);
    } else if (message.getHeader() != null
            && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
        System.out.println("Client receive server heart beat message : ---> " + message);
    } else
        ctx.fireChannelRead(msg);
}

From source file:com.zhaopeng.timeserver.protocol.netty.client.LoginAuthReqHandler.java

License:Apache License

/**
 * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward to
 * the next {@link ChannelHandler} in the {@link ChannelPipeline}.
 * <p>/*from   www .  ja  v  a  2s  .co  m*/
 * Sub-classes may override this method to change behavior.
 */

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;

    // ??????
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        byte loginResult = (byte) message.getBody();
        if (loginResult != (byte) 0) {
            // ?
            ctx.close();
        } else {
            System.out.println("Login is ok : " + message);
            ctx.fireChannelRead(msg);
        }
    } else
        ctx.fireChannelRead(msg);
}

From source file:com.zz.learning.netty5.chap12.client.HeartBeatReqHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;
    // ?????/*from  w  ww .jav a 2s.  com*/
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 5000,
                TimeUnit.MILLISECONDS);
    } else if (message.getHeader() != null
            && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
        System.out.println("Client receive server heart beat message : ---> " + message);
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:com.zz.learning.netty5.chap12.client.LoginAuthReqHandler.java

License:Apache License

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

    // ??????
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        byte loginResult = (byte) message.getBody();
        if (loginResult != LoginResult.LOGIN_SUCCESS.value()) {
            // ?
            ctx.close();
        } else {
            System.out.println("Login is ok : " + message);
            ctx.fireChannelRead(msg);
        }
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:com.zz.learning.netty5.chap12.server.LoginAuthRespHandler.java

License:Apache License

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

    // ?????
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_REQ.value()) {
        String nodeIndex = ctx.channel().remoteAddress().toString();
        NettyMessage loginResp = null;
        // ???
        if (nodeCheck.containsKey(nodeIndex)) {
            loginResp = buildResponse(LoginResult.lOGIN_FAILED.value());
        } else {
            InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
            String ip = address.getAddress().getHostAddress();
            boolean isOK = false;
            for (String WIP : whitekList) {
                if (WIP.equals(ip)) {
                    isOK = true;
                    break;
                }
            }
            loginResp = isOK ? buildResponse(LoginResult.LOGIN_SUCCESS.value())
                    : buildResponse(LoginResult.lOGIN_FAILED.value());
            if (isOK) {
                nodeCheck.put(nodeIndex, true);
                clientChannels.put(nodeIndex, ctx.channel());
            }
        }
        System.out.println("The login response is : " + loginResp + " body [" + loginResp.getBody() + "]");
        ctx.writeAndFlush(loginResp);
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:de.unipassau.isl.evs.ssh.core.network.handler.SignatureChecker.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {/*from  w  w  w  . j  a  v a  2  s .  c  om*/
        if (msg instanceof ByteBuf) {
            final ByteBuf in = (ByteBuf) msg;
            final int dataLength = in.readInt();
            final ByteBuf data = in.readSlice(dataLength);
            final int signatureLength = in.readInt();
            final byte[] signature = new byte[signatureLength];
            in.readBytes(signature);

            verifySignature.update(data.nioBuffer());
            final boolean valid = verifySignature.verify(signature);
            //Log.v(TAG, "Read " + dataLength + "b of data with " + signatureLength + "b " +
            //        (valid ? "valid" : "invalid") + " signature" +
            //        (Log.isLoggable(TAG, Log.VERBOSE) ? ": " + Arrays.toString(signature) : ""));
            if (valid) {
                data.retain();
                ctx.fireChannelRead(data);
            } else {
                throw new SignatureException("Message has a broken signature, closing connection");
            }
        } else {
            throw new SignatureException("Can't check signature of message of type "
                    + (msg != null ? msg.getClass() : "null") + ", closing connection");
        }
    } catch (SignatureException | RuntimeException e) {
        ctx.close();
        throw e;
    }
}

From source file:deathcap.wsmc.web.HTTPHandler.java

License:Apache License

public void httpRequest(ChannelHandlerContext context, FullHttpRequest request) throws IOException {
    if (!request.getDecoderResult().isSuccess()) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//from   ww  w . j  av a 2s.  c  o  m
    }
    if (request.getUri().equals("/server")) {
        context.fireChannelRead(request);
        return;
    }

    if ((request.getMethod() == OPTIONS || request.getMethod() == HEAD) && request.getUri().equals("/chunk")) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
        response.headers().add("Access-Control-Allow-Origin", "*");
        response.headers().add("Access-Control-Allow-Methods", "POST");
        if (request.getMethod() == OPTIONS) {
            response.headers().add("Access-Control-Allow-Headers", "origin, content-type, accept");
        }
        sendHttpResponse(context, request, response);
    }

    if (request.getMethod() != GET) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // TODO: send browserified page
    if (request.getUri().equals("/")) {
        request.setUri("/index.html");
    }

    InputStream stream = null;
    /*
    if (request.getUri().startsWith("/resources/")) {
    File file = new File(
            plugin.getResourceDir(),
            request.getUri().substring("/resources/".length())
    );
    stream = new FileInputStream(file);
    } else {
    */
    stream = this.getClass().getClassLoader().getResourceAsStream("www" + request.getUri());
    if (stream == null) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
        return;
    }
    ByteBufOutputStream out = new ByteBufOutputStream(Unpooled.buffer());
    copyStream(stream, out);
    stream.close();
    out.close();

    ByteBuf buffer = out.buffer();
    if (request.getUri().equals("/index.html")) {
        String page = buffer.toString(CharsetUtil.UTF_8);
        page = page.replaceAll("%SERVERPORT%", Integer.toString(this.port));
        buffer.release();
        buffer = Unpooled.wrappedBuffer(page.getBytes(CharsetUtil.UTF_8));
    }

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer);
    if (request.getUri().startsWith("/resources/")) {
        response.headers().add("Access-Control-Allow-Origin", "*");
    }

    String ext = request.getUri().substring(request.getUri().lastIndexOf('.') + 1);
    String type = mimeTypes.containsKey(ext) ? mimeTypes.get(ext) : "text/plain";
    if (type.startsWith("text/")) {
        type += "; charset=UTF-8";
    }
    response.headers().set(CONTENT_TYPE, type);
    setContentLength(response, response.content().readableBytes());
    sendHttpResponse(context, request, response);

}

From source file:discord4j.common.close.CloseHandlerAdapter.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof CloseWebSocketFrame && ((CloseWebSocketFrame) msg).isFinalFragment()) {
        CloseWebSocketFrame close = (CloseWebSocketFrame) msg;
        log.debug("Close status: {} {}", close.statusCode(), close.reasonText());
        closeStatus.set(new CloseStatus(close.statusCode(), close.reasonText()));
    }//  w w w .  ja  v  a  2 s . co  m
    ctx.fireChannelRead(msg);
}

From source file:divconq.net.ByteToMessageDecoder.java

License:Apache License

@Override
public final void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    ByteBuf buf = internalBuffer();/*from w w w . ja  v  a2 s .  com*/
    int readable = buf.readableBytes();
    if (buf.isReadable()) {
        ByteBuf bytes = buf.readBytes(readable);
        buf.release();
        ctx.fireChannelRead(bytes);
    } else {
        buf.release();
    }
    this.cumulation = null;
    ctx.fireChannelReadComplete();
    this.handlerRemoved0(ctx);
}