Example usage for io.netty.channel ChannelHandlerContext channel

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

Introduction

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

Prototype

Channel channel();

Source Link

Document

Return the Channel which is bound to the ChannelHandlerContext .

Usage

From source file:com.alibaba.rocketmq.remoting.netty.NettyRemotingAbstract.java

License:Apache License

public void processRequestCommand(final ChannelHandlerContext ctx, final RemotingCommand cmd) {
    final Pair<NettyRequestProcessor, ExecutorService> matched = this.processorTable.get(cmd.getCode());
    final Pair<NettyRequestProcessor, ExecutorService> pair = null == matched ? this.defaultRequestProcessor
            : matched;/*  ww  w. j  a v  a2s . com*/

    if (pair != null) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    RPCHook rpcHook = NettyRemotingAbstract.this.getRPCHook();
                    if (rpcHook != null) {
                        rpcHook.doBeforeRequest(RemotingHelper.parseChannelRemoteAddr(ctx.channel()), cmd);
                    }

                    final RemotingCommand response = pair.getObject1().processRequest(ctx, cmd);
                    if (rpcHook != null) {
                        rpcHook.doAfterResponse(RemotingHelper.parseChannelRemoteAddr(ctx.channel()), cmd,
                                response);
                    }

                    if (!cmd.isOnewayRPC()) {
                        if (response != null) {
                            response.setOpaque(cmd.getOpaque());
                            response.markResponseType();
                            try {
                                ctx.writeAndFlush(response);
                            } catch (Throwable e) {
                                plog.error("process request over, but response failed", e);
                                plog.error(cmd.toString());
                                plog.error(response.toString());
                            }
                        } else {
                            // ?processRequest?
                        }
                    }
                } catch (Throwable e) {
                    plog.error("process request exception", e);
                    plog.error(cmd.toString());

                    if (!cmd.isOnewayRPC()) {
                        final RemotingCommand response = RemotingCommand.createResponseCommand(
                                RemotingSysResponseCode.SYSTEM_ERROR, //
                                RemotingHelper.exceptionSimpleDesc(e));
                        response.setOpaque(cmd.getOpaque());
                        ctx.writeAndFlush(response);
                    }
                }
            }
        };

        try {
            // ??????
            pair.getObject2().submit(run);
        } catch (RejectedExecutionException e) {
            // ?10s?
            if ((System.currentTimeMillis() % 10000) == 0) {
                plog.warn(RemotingHelper.parseChannelRemoteAddr(ctx.channel()) //
                        + ", too many requests and system thread pool busy, RejectedExecutionException " //
                        + pair.getObject2().toString() //
                        + " request code: " + cmd.getCode());
            }

            if (!cmd.isOnewayRPC()) {
                final RemotingCommand response = RemotingCommand.createResponseCommand(
                        RemotingSysResponseCode.SYSTEM_BUSY,
                        "too many requests and system thread pool busy, please try another server");
                response.setOpaque(cmd.getOpaque());
                ctx.writeAndFlush(response);
            }
        }
    } else {
        String error = " request type " + cmd.getCode() + " not supported";
        final RemotingCommand response = RemotingCommand
                .createResponseCommand(RemotingSysResponseCode.REQUEST_CODE_NOT_SUPPORTED, error);
        response.setOpaque(cmd.getOpaque());
        ctx.writeAndFlush(response);
        plog.error(RemotingHelper.parseChannelRemoteAddr(ctx.channel()) + error);
    }
}

From source file:com.alibaba.rocketmq.remoting.netty.NettyRemotingAbstract.java

License:Apache License

public void processResponseCommand(ChannelHandlerContext ctx, RemotingCommand cmd) {
    final ResponseFuture responseFuture = responseTable.get(cmd.getOpaque());
    if (responseFuture != null) {
        responseFuture.setResponseCommand(cmd);
        responseFuture.release();//from   ww  w  . j  av  a2s.c o m
        responseTable.remove(cmd.getOpaque());

        if (responseFuture.getInvokeCallback() != null) {
            boolean runInThisThread = false;
            ExecutorService executor = this.getCallbackExecutor();
            if (executor != null) {
                try {
                    executor.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                responseFuture.executeInvokeCallback();
                            } catch (Throwable e) {
                                plog.warn("excute callback in executor exception, and callback throw", e);
                            }
                        }
                    });
                } catch (Exception e) {
                    runInThisThread = true;
                    plog.warn("excute callback in executor exception, maybe executor busy", e);
                }
            } else {
                runInThisThread = true;
            }

            if (runInThisThread) {
                try {
                    responseFuture.executeInvokeCallback();
                } catch (Throwable e) {
                    plog.warn("executeInvokeCallback Exception", e);
                }
            }
        } else {
            responseFuture.putResponse(cmd);
        }
    } else {
        plog.warn("receive response, but not matched any request, "
                + RemotingHelper.parseChannelRemoteAddr(ctx.channel()));
        plog.warn(cmd.toString());
    }

}

From source file:com.alibaba.rocketmq.remoting.NettyConnectionTest.java

License:Apache License

public static RemotingServer createRemotingServer() throws InterruptedException {
    NettyServerConfig config = new NettyServerConfig();
    RemotingServer server = new NettyRemotingServer(config);
    server.registerProcessor(0, new NettyRequestProcessor() {
        private AtomicInteger i = new AtomicInteger();

        @Override//from   w  w  w. java  2s.  c  om
        public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) {
            System.out.println("processRequest=" + request + " " + (i.incrementAndGet()));
            request.setRemark("hello, I am response " + ctx.channel().remoteAddress());
            return request;
        }

        @Override
        public boolean rejectRequest() {
            return false;
        }
    }, Executors.newCachedThreadPool());
    server.start();
    return server;
}

From source file:com.alltobid.quotabid.BidServerHandler.java

License:Apache License

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    channels.add(ctx.channel());
}

From source file:com.alltobid.quotabid.BidServerHandler.java

License:Apache License

@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    channels.remove(ctx.channel());
}

From source file:com.andrewkroh.cisco.xmlservices.XmlResponseChannelHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    IpPhone phone = ctx.channel().attr(phoneAttributeKey).get();

    if (msg instanceof HttpResponse && LOGGER.isDebugEnabled()) {
        HttpResponse response = (HttpResponse) msg;

        StringBuilder responseInfo = new StringBuilder();
        responseInfo.append("Source=");
        responseInfo.append(phone.getHostname());
        responseInfo.append(", ");
        responseInfo.append("Status=");
        responseInfo.append(response.getStatus());
        responseInfo.append(", ");
        responseInfo.append("Version=");
        responseInfo.append(response.getProtocolVersion());

        for (String name : response.headers().names()) {
            for (String value : response.headers().getAll(name)) {
                responseInfo.append(", ");
                responseInfo.append(name);
                responseInfo.append('=');
                responseInfo.append(value);
            }/*from ww  w  .j a v  a 2s  . co m*/
        }

        LOGGER.debug(responseInfo.toString());
    }

    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;

        SettableFuture<XmlPushResponse> responseFuture = ctx.channel().attr(responseAttributeKey).get();

        // The default charset for HTTP is ISO-8859-1. None
        // of the Cisco phones I've seen to date were actually
        // setting the charset so use the default. We could
        // improve here by checking the header for the value.
        String xmlContent = content.content().toString(CharsetUtil.ISO_8859_1);

        CiscoIPPhoneResponse xmlResponse = XmlMarshaller.unmarshal(xmlContent, CiscoIPPhoneResponse.class);
        responseFuture.set(new DefaultXmlPushResponse(phone, xmlResponse));

        // Cleanup:
        ctx.close();
        ctx.channel().close();
    }
}

From source file:com.andrewkroh.cisco.xmlservices.XmlResponseChannelHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (LOGGER.isWarnEnabled()) {
        IpPhone phone = ctx.channel().attr(phoneAttributeKey).get();
        LOGGER.warn("Exception in handler for {}.", phone.getHostname());
    }//from w ww .j  a  v  a  2 s.c  o  m

    SettableFuture<XmlPushResponse> responseFuture = ctx.channel().attr(responseAttributeKey).get();
    responseFuture.setException(cause);

    // Cleanup:
    ctx.close();
    ctx.channel().close();
}

From source file:com.andy.grpc.proxy.HexDumpProxyBackendHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
    inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
        @Override/*ww  w .j a v a2  s. co  m*/
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ctx.channel().read();
            } else {
                future.channel().close();
            }
        }
    });
}

From source file:com.andy.grpc.proxy.HexDumpProxyBackendHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();/* w  w w . ja va 2s.  c o m*/
    HexDumpProxyFrontendHandler.closeOnFlush(ctx.channel());
}

From source file:com.antsdb.saltedfish.server.mysql.MysqlClientHandler.java

License:Open Source License

public void close(ChannelHandlerContext ctx) {
    ctx.channel().close();
}