Search in sources :

Example 1 with Command

use of com.akaxin.common.command.Command in project openzaly by akaxincom.

the class User2Notice method addFriendTextMessage.

/**
 * <pre>
 * 代发一条U2本文消息
 * AB成为好友,同时发送A/B一条消息
 * </pre>
 *
 * @param siteUserId
 * @param siteFriendId
 */
public void addFriendTextMessage(String siteUserId, String siteFriendId) {
    try {
        CoreProto.MsgText textMsg = CoreProto.MsgText.newBuilder().setMsgId(buildU2MsgId(siteUserId)).setSiteUserId(siteUserId).setSiteFriendId(siteFriendId).setText(ByteString.copyFromUtf8(NoticeText.USER_ADD_FRIEND)).setTime(System.currentTimeMillis()).build();
        ImCtsMessageProto.ImCtsMessageRequest request = ImCtsMessageProto.ImCtsMessageRequest.newBuilder().setType(MsgType.TEXT).setText(textMsg).build();
        Command command = new Command();
        command.setAction(RequestAction.IM_CTS_MESSAGE.getName());
        command.setSiteUserId(siteUserId);
        command.setSiteFriendId(siteFriendId);
        command.setParams(request.toByteArray());
        boolean result = u2MsgService.execute(command);
        logger.debug("add friend Text message siteUserId={} siteFriendId={} result={}", siteUserId, siteFriendId, result);
    } catch (Exception e) {
        logger.error(StringHelper.format("send add friend text message error. siteUserId={} siteFriendId={}", siteUserId, siteFriendId), e);
    }
    try {
        CoreProto.MsgText textMsg = CoreProto.MsgText.newBuilder().setMsgId(buildU2MsgId(siteFriendId)).setSiteUserId(siteFriendId).setSiteFriendId(siteUserId).setText(ByteString.copyFromUtf8(NoticeText.USER_ADD_FRIEND)).setTime(System.currentTimeMillis()).build();
        ImCtsMessageProto.ImCtsMessageRequest request = ImCtsMessageProto.ImCtsMessageRequest.newBuilder().setType(MsgType.TEXT).setText(textMsg).build();
        Command command = new Command();
        command.setAction(RequestAction.IM_CTS_MESSAGE.getName());
        command.setSiteUserId(siteFriendId);
        command.setSiteFriendId(siteUserId);
        command.setParams(request.toByteArray());
        boolean result = u2MsgService.execute(command);
        logger.debug("add friend Text message siteUserId={} siteFriendId={} result={}", siteFriendId, siteUserId, result);
    } catch (Exception e) {
        logger.error(StringHelper.format("send add friend text message error. siteUserId={} siteFriendId={}", siteFriendId, siteUserId), e);
    }
}
Also used : CoreProto(com.akaxin.proto.core.CoreProto) Command(com.akaxin.common.command.Command) ImCtsMessageProto(com.akaxin.proto.site.ImCtsMessageProto)

Example 2 with Command

use of com.akaxin.common.command.Command in project openzaly by akaxincom.

the class Bootstrap method startNettyServer.

/**
 * 启动Netty服务器,提供用户与站点服务之间的长链接功能
 *
 * @param address
 * @param port
 * @throws Exception
 */
private static void startNettyServer(String address, int port) throws Exception {
    new NettyServer() {

        @Override
        public void loadExecutor(AbstracteExecutor<Command, CommandResponse> executor) {
            executor.addChain(RequestAction.IM_SITE.getName(), new ImSiteAuthHandler());
            executor.addChain(RequestAction.IM.getName(), new ImMessageHandler());
            executor.addChain(RequestAction.API.getName(), new ApiRequestHandler());
        }
    }.start(address, port);
    logger.info("{} start netty server {}:{} ok.", AkxProject.PLN, address, port);
}
Also used : Command(com.akaxin.common.command.Command) ApiRequestHandler(com.akaxin.site.connector.handler.ApiRequestHandler) ImSiteAuthHandler(com.akaxin.site.connector.handler.ImSiteAuthHandler) CommandResponse(com.akaxin.common.command.CommandResponse) ImMessageHandler(com.akaxin.site.connector.handler.ImMessageHandler) NettyServer(com.akaxin.site.connector.netty.NettyServer)

Example 3 with Command

use of com.akaxin.common.command.Command in project openzaly by akaxincom.

the class HttpServerHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {
        /**
         * http-request包含: <br>
         * 1.请求行 ,Method Request-URI Http-Version CRLF<br>
         * 2.消息头 <br>
         * 3.请求正文 <br>
         */
        if (msg instanceof HttpRequest) {
            request = (HttpRequest) msg;
            if (!checkLegalRequest()) {
                logger.error("{} http request method error. please use post!", AkxProject.PLN);
                ctx.close();
                return;
            }
            String clientIp = request.headers().get(HttpConst.HTTP_H_FORWARDED);
            if (clientIp == null) {
                InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
                clientIp = address.getAddress().getHostAddress();
            }
            if (!checkLegalClientIp(clientIp)) {
                logger.error("{} http request illegal IP={}.", AkxProject.PLN, clientIp);
                ctx.close();
                return;
            }
            logger.debug("{} request uri:{} clientIp={}", AkxProject.PLN, request.uri(), clientIp);
        }
        /**
         * HttpContent:表示HTTP实体正文和内容标头的基类 <br>
         * method.name=POST 传输消息体存在内容
         */
        if (msg instanceof LastHttpContent) {
            HttpContent content = (HttpContent) msg;
            ByteBuf httpByteBuf = content.content();
            if (httpByteBuf == null) {
                return;
            }
            if (!checkLegalRequest()) {
                ctx.close();
                return;
            }
            String clientIp = request.headers().get(HttpConst.HTTP_H_FORWARDED);
            String sitePluginId = request.headers().get(PluginConst.SITE_PLUGIN_ID);
            byte[] contentBytes = new byte[httpByteBuf.readableBytes()];
            httpByteBuf.readBytes(contentBytes);
            httpByteBuf.release();
            // 查询扩展的auth——key
            String authKey = PluginSession.getInstance().getPluginAuthKey(sitePluginId);
            if (StringUtils.isNotEmpty(authKey)) {
                // byte[] tsk = AESCrypto.generateTSKey(authKey);
                byte[] tsk = authKey.getBytes(CharsetCoding.ISO_8859_1);
                byte[] decContent = AESCrypto.decrypt(tsk, contentBytes);
                contentBytes = decContent;
            }
            PluginProto.ProxyPluginPackage pluginPackage = PluginProto.ProxyPluginPackage.parseFrom(contentBytes);
            Map<Integer, String> proxyHeader = pluginPackage.getPluginHeaderMap();
            String requestTime = proxyHeader.get(PluginProto.PluginHeaderKey.PLUGIN_TIMESTAMP_VALUE);
            long currentTime = System.currentTimeMillis();
            boolean timeOut = true;
            if (StringUtils.isNotEmpty(requestTime)) {
                long timeMills = Long.valueOf(requestTime);
                if (currentTime - timeMills < 10 * 1000l) {
                    timeOut = false;
                }
            }
            logger.debug("{} client={} http request timeOut={} currTime={} reqTime={}", AkxProject.PLN, clientIp, timeOut, currentTime, requestTime);
            if (!timeOut) {
                Command command = new Command();
                command.setField(PluginConst.PLUGIN_AUTH_KEY, authKey);
                if (proxyHeader != null) {
                    command.setSiteUserId(proxyHeader.get(PluginProto.PluginHeaderKey.CLIENT_SITE_USER_ID_VALUE));
                }
                command.setChannelContext(ctx);
                command.setUri(request.uri());
                command.setParams(Base64.getDecoder().decode(pluginPackage.getData()));
                command.setClientIp(clientIp);
                command.setStartTime(System.currentTimeMillis());
                logger.debug("{} client={} http server handler command={}", AkxProject.PLN, clientIp, command.toString());
                CommandResponse response = this.executor.execute(HttpUriAction.HTTP_ACTION.getUri(), command);
                LogUtils.requestResultLog(logger, command, response);
            } else {
                // 超时10s,认为此请求失效,直接断开连接
                ctx.close();
                logger.error("{} client={} http request error.timeOut={} currTime={} reqTime={}", AkxProject.PLN, clientIp, timeOut, currentTime, requestTime);
            }
        }
    } catch (Exception e) {
        ctx.close();
        logger.error(StringHelper.format("{} http request error.", AkxProject.PLN), e);
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) InetSocketAddress(java.net.InetSocketAddress) PluginProto(com.akaxin.proto.core.PluginProto) CommandResponse(com.akaxin.common.command.CommandResponse) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ByteBuf(io.netty.buffer.ByteBuf) Command(com.akaxin.common.command.Command) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent)

Example 4 with Command

use of com.akaxin.common.command.Command in project openzaly by akaxincom.

the class NettyServerHandler method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, RedisCommand redisCmd) throws Exception {
    InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
    String clientIp = socketAddress.getAddress().getHostAddress();
    ChannelSession channelSession = ctx.channel().attr(ParserConst.CHANNELSESSION).get();
    // disconnect tcp connection as channel is unavailable
    if (channelSession.getChannel() == null || !channelSession.getChannel().isActive()) {
        // 断开连接事件(与对方的连接断开)
        ctx.disconnect();
        logger.warn("{} close client={} as its channel is not active ", AkxProject.PLN, clientIp);
    }
    String version = redisCmd.getParameterByIndex(0);
    String action = redisCmd.getParameterByIndex(1);
    byte[] params = redisCmd.getBytesParamByIndex(2);
    CoreProto.TransportPackageData packageData = CoreProto.TransportPackageData.parseFrom(params);
    Command command = new Command();
    command.setClientIp(clientIp);
    command.setSiteUserId(channelSession.getUserId());
    command.setDeviceId(channelSession.getDeviceId());
    command.setAction(action);
    command.setHeader(packageData.getHeaderMap());
    command.setParams(packageData.getData().toByteArray());
    command.setChannelSession(channelSession);
    command.setStartTime(System.currentTimeMillis());
    if (!RequestAction.IM_CTS_PING.getName().equalsIgnoreCase(command.getAction())) {
        logger.debug("{} client={} -> site version={} action={} params-length={}", AkxProject.PLN, clientIp, version, action, params.length);
    } else {
        logger.trace("{} client={} ping -> site", AkxProject.PLN, clientIp);
    }
    if (RequestAction.IM.getName().equals(command.getRety())) {
        // 如果是syncFinish,则这里需要修改channel中的syncFinTime
        channelSession.setActionForPsn(action);
        // 单独处理im.site.hello && im.site.auth
        if (RequestAction.SITE.getName().equalsIgnoreCase(command.getService())) {
            String anoRequest = command.getRety() + "." + command.getService();
            command.setRety(anoRequest);
        }
        CommandResponse response = this.executor.execute(command.getRety(), command);
        if (!RequestAction.IM_CTS_PING.getName().equals(command.getAction())) {
            // 输出IM请求结果
            LogUtils.requestResultLog(logger, command, response);
        }
    } else if (RequestAction.API.getName().equalsIgnoreCase(command.getRety())) {
        CommandResponse response = this.executor.execute(command.getRety(), command);
        // 输出API请求结果
        LogUtils.requestResultLog(logger, command, response);
    } else {
        /**
         * <pre>
         *
         * pipeline.addLast("A", new AHandler());
         * pipeline.addLast("B", new BHandler());
         * pipeline.addLast("C", new CHandler());
         *
         * ctx.close() && channel().close();
         * 		ctx.close(): close the channel in current handler,will start from the tail of the ChannelPipeline
         * 				do A.close() ,B.close(),C.close();
         * 		channel().close():close channel in all handler from pointer
         * 				do C.close() , B.close(), A.close();
         * </pre>
         */
        // 关闭channel事件(关闭自己的连接)
        ctx.channel().close();
        logger.error("{} client={} siteUserId={} action={} unknow request method", AkxProject.PLN, command.getClientIp(), command.getSiteUserId(), command.getAction());
        return;
    }
}
Also used : CoreProto(com.akaxin.proto.core.CoreProto) ChannelSession(com.akaxin.common.channel.ChannelSession) Command(com.akaxin.common.command.Command) RedisCommand(com.akaxin.common.command.RedisCommand) InetSocketAddress(java.net.InetSocketAddress) CommandResponse(com.akaxin.common.command.CommandResponse)

Example 5 with Command

use of com.akaxin.common.command.Command in project openzaly by akaxincom.

the class MethodReflectHandler method handle.

@SuppressWarnings("unchecked")
public R handle(T t) {
    try {
        Command cmd = (Command) t;
        String methodName = cmd.getMethod();
        Method m = this.getClass().getDeclaredMethod(methodName, cmd.getClass());
        Object result = m.invoke(this, t);
        if (result != null) {
            return (R) result;
        }
    } catch (NoSuchMethodException e) {
        logger.error("method handler NoSuchMethod error.", e);
    } catch (SecurityException e) {
        logger.error("method handler Security error.", e);
    } catch (IllegalAccessException e) {
        logger.error("method handler IllegalAccess error.", e);
    } catch (IllegalArgumentException e) {
        logger.error("method handler IllegalArgument error.", e);
    } catch (InvocationTargetException e) {
        logger.error("method handler InvocationTarget error.", e);
    }
    return null;
}
Also used : Command(com.akaxin.common.command.Command) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

Command (com.akaxin.common.command.Command)8 CommandResponse (com.akaxin.common.command.CommandResponse)4 CoreProto (com.akaxin.proto.core.CoreProto)4 RedisCommand (com.akaxin.common.command.RedisCommand)2 ImCtsMessageProto (com.akaxin.proto.site.ImCtsMessageProto)2 InetSocketAddress (java.net.InetSocketAddress)2 ChannelSession (com.akaxin.common.channel.ChannelSession)1 PluginProto (com.akaxin.proto.core.PluginProto)1 ApiRequestHandler (com.akaxin.site.connector.handler.ApiRequestHandler)1 HttpRequestHandler (com.akaxin.site.connector.handler.HttpRequestHandler)1 ImMessageHandler (com.akaxin.site.connector.handler.ImMessageHandler)1 ImSiteAuthHandler (com.akaxin.site.connector.handler.ImSiteAuthHandler)1 HttpServer (com.akaxin.site.connector.http.HttpServer)1 NettyServer (com.akaxin.site.connector.netty.NettyServer)1 ByteBuf (io.netty.buffer.ByteBuf)1 HttpContent (io.netty.handler.codec.http.HttpContent)1 HttpRequest (io.netty.handler.codec.http.HttpRequest)1 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1