All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ys.artifact-network.1.0.5.source-code.client_java.btl Maven / Gradle / Ivy

package ${packageName};

import cn.hutool.core.util.IdUtil;
import lombok.Data;
import org.artifact.core.context.packet.NetworkPacket;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Supplier;

public class ClientNetworkProtocolForJava
{
    interface AbstractDTO {
        Map toMap(Map map);
        Object forMap(Map map);
    }
    <%
    for(struct in structs){
        var extends = false;
    	var extendConstant = "";
    	if(strutil.isNotBlank(struct.extendsName)){
    		extends = true;
    		extendConstant = "extends " + struct.extendsName;
    	}else{
    		extends = false;
    		extendConstant = "implements AbstractDTO";
    	}
    %>


    @Data
    /** ${struct.remark} */
    static class ${struct.structName} ${extendConstant}{
        <%
        for(field in struct.fields){
        %>
        /** ${field.key.remark} */
        public ${field.value.intact} ${uf(field.key.name)};
        <%}%>

        <%if(extends){%>
        public Map toMap(Map map){
            super.toMap(map);
        <%}else{%>
        public Map toMap(Map map){
        <%}%>
            <%
            var hashArray = [];
            for(field in struct.fields){
            hashCode = HashUtil.javaDefaultHash(field.key.name)+"";
            if(array.contain(hashArray,hashCode)){
                println("		"+field.key.name+":HashCode重复,请重命名");
                continue;
            }else{
                array.add(hashArray,hashCode);
            }
            %>
            <%if(field.value.type == "java.util.Map"){%>
            Map _${field.key.name} = new HashMap();
            for (Map.Entry<${field.value.generics[0]},${field.value.generics[1]}> kv : this.${uf(field.key.name)}.entrySet())
            {
                _${field.key.name}.put(DtoSerializationProvider.tryDecoder(kv.getKey()), DtoSerializationProvider.tryDecoder(kv.getValue()));
            }
            map.put(${hashCode}, _${field.key.name});
            <%}else if(field.value.type == "java.util.List"){%>
            List _${field.key.name} = new ArrayList();
            for (${field.value.generics[0]} obj : this.${uf(field.key.name)})
            {
                _${field.key.name}.add(DtoSerializationProvider.tryDecoder(obj));
            }
            map.put(${hashCode}, _${field.key.name});
            <%}else{%>
            map.put(${hashCode}, DtoSerializationProvider.tryEncoder(this.${uf(field.key.name)}));
            <%}%>
            <%}%>
            return map;
        }
        <%if(extends){%>
        public Object forMap(Map map){
            super.forMap(map);
        <%}else{%>
        public Object forMap(Map map){
        <%}%>
            <%
            for(field in struct.fields){
            hashCode = HashUtil.javaDefaultHash(field.key.name)+"";
            %>
            <%if(field.value.type == "java.util.Map"){%>
            //this.${uf(field.key.name)} = new ${field.value.intact}();
            this.${uf(field.key.name)} = new HashMap<>();
            for (Map.Entry kv : ((Map)map.get(${hashCode})).entrySet())
            {
                this.${uf(field.key.name)}.put((${field.value.generics[0]})DtoSerializationProvider.tryDecoder(kv.getKey()), (${field.value.generics[1]})DtoSerializationProvider.tryDecoder(kv.getValue()));
            }
            <%}else if(field.value.type == "java.util.List"){%>
            //this.${uf(field.key.name)} = new ${field.value.intact}();
            this.${uf(field.key.name)} = new ArrayList<>();
            for (Object obj : (List)map.get(${hashCode}))
            {
                this.${uf(field.key.name)}.add((${field.value.generics[0]})DtoSerializationProvider.tryDecoder(obj));
            }
            <%}else{%>
            this.${uf(field.key.name)} = (${field.value.intact})DtoSerializationProvider.tryDecoder(map.get(${hashCode}));
            <%}%>
            <%}%>
            return this;
        }
    }

    <%}%>








    <%for(module in modules){%>
    static class ${module.name}Module{
        <%for(send in module.protocolSends){%>
        public static final int ${ccu(send.requestName)} = ${ProtocolUtil.getCommandId(module.id,send.id)};
        <%}%>
        <%for(push in module.protocolPushs){%>
        public static final int ${ccu(push.pushName)} = ${ProtocolUtil.getCommandId(module.id,push.id)};
        <%}%>

        public static void disp(NetworkPacket packet) {
            int command = packet.getHeader(NetworkHeader.COMMAND);
            int module = command >> 16;
            int method = module << 16 ^ command;
            switch (method) {
                <%for(send in module.protocolSends){%>
                case ${send.id}:
                    _${send.requestName}(packet);
                    break;
                <%}%>
                <%for(push in module.protocolPushs){%>
                case ${push.id}:
                    _${push.pushName}(packet);
                    break;
                <%}%>
            }
        }

        <%
        for(send in module.protocolSends){
            var parameter = "";
            var values = "";
            var hashArray = [];
            for(rp in send.requestParameter){
                var hashCode = HashUtil.javaDefaultHash(rp.key)+"";
                if(array.contain(hashArray,hashCode)){
                    println("		"+rp.key+":HashCode重复,请重命名");
                    continue;
                }else{
                    array.add(hashArray,hashCode);
                }
                parameter = parameter + ", " + rp.value.intact + " " + rp.key;
                values = values + ", " + rp.key;
            }
        %>

        /// 
        /// ${send.remark}
        /// 
        public static void ${send.requestName}(NetClient client${parameter},${uf(send.requestName)}Listener listener) {
            NetworkPacket packet = new NetworkPacket();
            String messageId = IdUtil.simpleUUID();
            packet.setHeader(NetworkHeader.ID, messageId);
            packet.setHeader(NetworkHeader.COMMAND, ${ProtocolUtil.getCommandId(module.id,send.id)});
            packet.setHeader(NetworkHeader.MODULE, ${module.id});
            packet.setHeader(NetworkHeader.METHOD, ${send.id});
            packet.setHeader(NetworkHeader.TYPE, NetworkHeader.TYPE_DEFAULT);

            <%
            for(rp in send.requestParameter){
                var hashCode = HashUtil.javaDefaultHash(rp.key);
            %>
            <%if(rp.value.type == "java.util.Map"){%>
            Map _${rp.key} = new HashMap();
            for (Map.Entry<${rp.value.generics[0]},${rp.value.generics[1]}> kv : ${rp.key}.entrySet())
            {
                _${rp.key}.put(DtoSerializationProvider.tryDecoder(kv.getKey()), DtoSerializationProvider.tryDecoder(kv.getValue()));
            }
            packet.getBody().put(${hashCode}, _${rp.key});
            <%}else if(rp.value.type == "java.util.List"){%>
            List _${rp.key} = new ArrayList();
            for (${rp.value.generics[0]} obj : ${rp.key})
            {
                _${rp.key}.add(DtoSerializationProvider.tryDecoder(obj));
            }
            packet.getBody().put(${hashCode}, _${rp.key});
            <%}else{%>
            packet.getBody().put(${hashCode}, DtoSerializationProvider.tryEncoder(${rp.key}));
            <%}%>

            <%}%>
            client.AsyncSend(packet);

            // 注册监听
            if(listener!=null){
                ProtocolLListener.registerRequestListener(messageId,listener);
            }
        }

        /// 
        /// ${send.remark}-解码
        /// 
        private static void _${send.requestName}(NetworkPacket packet) {
            String messageId = (String)packet.getHeader(NetworkHeader.ID);
            MessageListener listener = ProtocolLListener.getRequestListener(messageId);
            if(listener!=null){
                int _code = (int)packet.getHeader(NetworkHeader.STATUS);
                <%for(rp in send.responseParameter){%>
                <%if(rp.value.intact == "int"){%>
                ${rp.value.intact} ${rp.key} = 0;
                <%}else if(rp.value.intact == "long"){%>
                ${rp.value.intact} ${rp.key} = 0;
                <%}else if(rp.value.intact == "string"){%>
                ${rp.value.intact} ${rp.key} = "";
                <%}else if(rp.value.intact == "bool"){%>
                ${rp.value.intact} ${rp.key} = false;
                <%}else{%>
                ${rp.value.intact} ${rp.key} = null;
                <%}%>
                <%}%>
                if(_code == 0)
                {
                    <%
                    values = "";
                    for(rp in send.responseParameter){
                    var hashCode = HashUtil.javaDefaultHash(rp.key);
                    values = values + ", " + rp.key;
                    %>
                    <%if(rp.value.type == "java.util.Map"){%>
                    //${rp.key} = new ${rp.value.intact}();
                    ${rp.key} = new HashMap<>();
                    for (Map.Entry kv : ((Map)packet.getBody().get(${hashCode})).entrySet())
                    {
                        ${rp.key}.put((${rp.value.generics[0]})DtoSerializationProvider.tryDecoder(kv.getKey()), (${rp.value.generics[1]})DtoSerializationProvider.tryDecoder(kv.getValue()));
                    }
                    <%}else if(rp.value.type == "java.util.List"){%>
                    //${rp.key} = new ${rp.value.intact}();
                    ${rp.key} = new ArrayList<>();
                    for (Object obj : (List)packet.getBody().get(${hashCode}))
                    {
                        ${rp.key}.add((${rp.value.generics[0]})DtoSerializationProvider.tryDecoder(obj));
                    }
                    <%}else{%>
                    ${rp.key} = (${rp.value.intact})DtoSerializationProvider.tryDecoder(packet.getBody().get(${hashCode}));
                    <%}%>
                    <%}%>
                }
                else
                {
                    ProtocolLListener.execErrorListener(_code, packet);
                }
                // 执行监听
                ((${uf(send.requestName)}Listener)listener).exec(_code${values});
                // 移除监听
                ProtocolLListener.removeRequestListener(messageId);
            }
        }

        <%
        parameter = "";
        for(rp in send.responseParameter){
        parameter = parameter + ", " + rp.value.intact + " " + rp.key;
        }
        %>
        /// 
        /// ${send.remark}-监听
        /// 
        //public delegate void ${uf(send.requestName)}Listener(int _code${parameter});
        @FunctionalInterface
        interface ${uf(send.requestName)}Listener  extends MessageListener {void exec(int _code${parameter});}
        <%}%>

        <%
        for(push in module.protocolPushs){
            var parameter = "";
            var values = "";
            var hashArray = [];
            for(rp in push.pushParameter){
                var hashCode = HashUtil.javaDefaultHash(rp.key)+"";
                if(array.contain(hashArray,hashCode)){
                    println("		"+rp.key+":HashCode重复,请重命名");
                    continue;
                }else{
                    array.add(hashArray,hashCode);
                }
                parameter = parameter + ", " + rp.value.intact + " " + rp.key;
                values = values + ", " + rp.key;
            }
        %>
        /// 
        /// ${push.remark}-解码
        /// 
        private static void _${push.pushName}(NetworkPacket packet) {
            int command = (int)packet.getHeader(NetworkHeader.COMMAND);
            MessageListener listener = ProtocolLListener.getNotifyListener(command);
            if(listener!=null){
                <%for(rp in push.pushParameter){%>
                <%if(rp.value.intact == "int"){%>
                ${rp.value.intact} ${rp.key} = 0;
                <%}else if(rp.value.intact == "long"){%>
                ${rp.value.intact} ${rp.key} = 0;
                <%}else if(rp.value.intact == "string"){%>
                ${rp.value.intact} ${rp.key} = "";
                <%}else if(rp.value.intact == "bool"){%>
                ${rp.value.intact} ${rp.key} = false;
                <%}else{%>
                ${rp.value.intact} ${rp.key} = null;
                <%}%>
                <%}%>

                <%
                values = "";
                for(rp in push.pushParameter){
                var hashCode = HashUtil.javaDefaultHash(rp.key);
                values = values + rp.key;
                if(!rpLP.last){
                    values = values + " ,";
                }
                %>
                <%if(rp.value.type == "java.util.Map"){%>
                //${rp.key} = new ${rp.value.intact}();
                ${rp.key} = new HashMap<>();
                for (Map.Entry kv : ((Map)packet.getBody().get(${hashCode})).entrySet())
                {
                    ${rp.key}.put((${rp.value.generics[0]})DtoSerializationProvider.tryDecoder(kv.getKey()), (${rp.value.generics[1]})DtoSerializationProvider.tryDecoder(kv.getValue()));
                }
                <%}else if(rp.value.type == "java.util.List"){%>
                //${rp.key} = new ${rp.value.intact}();
                ${rp.key} = new ArrayList<>();
                for (Object obj : (List)packet.getBody().get(${hashCode}))
                {
                    ${rp.key}.add((${rp.value.generics[0]})DtoSerializationProvider.tryDecoder(obj));
                }
                <%}else{%>
                ${rp.key} = (${rp.value.intact})DtoSerializationProvider.tryDecoder(packet.getBody().get(${hashCode}));
                <%}%>
                <%}%>
                // 执行监听
                ((${uf(push.pushName)}Listener)listener).exec(${values});
            }

        }

        <%
        parameter = "";
            for(rp in push.pushParameter){
                parameter = parameter + rp.value.intact + " " + rp.key;
                if(!rpLP.last){
                    parameter = parameter + " ,";
                }
            }
        %>

        /// 
        /// ${push.remark}-监听
        /// 
        //public delegate void ${uf(push.pushName)}Listener(${parameter});
        @FunctionalInterface
        interface ${uf(push.pushName)}Listener  extends MessageListener {void exec(${parameter});}
        <%}%>
    }
    <%}%>

    // 消息路由
    static class _Dispatcher {
        public static void disp(NetworkPacket packet) {
            // 取得模块ID
            int command = (int)packet.getHeader(NetworkHeader.COMMAND);
            int module = command >> 16;
            switch (module)
            {
                <%for(module in modules){%>
                case ${module.id}:
                    ${module.name}Module.disp(packet);
                    break;
                <%}%>
                default:
                    break;
            }
        }
    }


    static class DtoSerializationProvider{
        static Map> cache = new HashMap<>();
        static Map codes = new HashMap();
        static
        {
            <%
            for(struct in structs){
            var hashCode = HashUtil.javaDefaultHash(struct.structName)+"";
            %>
            // ${struct.remark}
            cache.put(${hashCode},() -> new ${struct.structName}());
            <%}%>

            <%
            for(struct in structs){
            hashCode = HashUtil.javaDefaultHash(struct.structName)+"";
            %>
            // ${struct.remark}
            codes.put("${struct.structName}",${hashCode});
            <%}%>
        }

        // 尝试编码
        public static Object tryEncoder(Object obj)
        {
            if (obj instanceof AbstractDTO)
            {
                String typeName = obj.getClass().getSimpleName();
                if(codes.containsKey(typeName)){
                    int structCode = codes.get(typeName);
                    Map dict = new HashMap<>();
                    dict.put(NetworkHeader.STRUCT_CODE,structCode);
                    return ((AbstractDTO)obj).toMap(dict);
                }
            }
            return obj;
        }

        // 尝试解码
        public static Object tryDecoder(Object obj)
        {
            if (obj instanceof Map)
            {
                Map dict = (Map)obj;
                if (dict.containsKey(NetworkHeader.STRUCT_CODE))
                {
                    int structCode = (int)dict.get(NetworkHeader.STRUCT_CODE);
                    if (DtoSerializationProvider.cache.containsKey(structCode))
                    {
                        AbstractDTO dto = cache.get(structCode).get();
                        return dto.forMap(dict);
                    }
                }
            }
            return obj;
        }
    }

    /**
    class ArtifactProtocolStreamBuffer : ArtifactStreamBuffer
    {
        public static final int STRUCT_CODE = 183928832;

        public ArtifactProtocolStreamBuffer(byte[] bytes = null) : base(bytes)
        {

        }

        public void WriteObject(object value)
        {
            if (value is AbstractDTO)
            {
                Map table = new HashMap();
                ((AbstractDTO)value).toMap(table);
                table.Add(STRUCT_CODE, DtoSerializationProvider.structCode(value.GetType().Name));
                WriteDict(table);
            }
            else
            {
                base.WriteObject(value);
            }
        }

        public object ReadObject()
        {
            MarkReaderIndex();
            byte tag = Read();
            ResetReaderIndex();
            if (tag == ArtifactBufferCoder.DICT || ArtifactBufferCoder.DICT_SUB_TYPE.ContainsVal(tag))
            {
                Map map = ReadDict();
                if (map.ContainsKey(STRUCT_CODE))
                {
                    int structCode = (int)map[STRUCT_CODE];
                    AbstractDTO dto = DtoSerializationProvider.create(structCode);
                    return dto.forMap(map);
                }
                else
                {
                    return map;
                }

            }
            else {
                return base.ReadObject();
            }
        }
    }

    class SimpleDecoder : Decoder
    {
        public NetworkPacket Handler(NetClient client, byte[] data)
        {
            using (ByteBuffer byteBuffer = new ArtifactProtocolStreamBuffer(data))
            {
                NetworkPacket packet = new NetworkPacket();
                packet.ForByteBuff(byteBuffer);
                return packet;
            }
        }
    }

    class SimpleEncoder : Encoder
    {
        public byte[] Handler(NetClient client, NetworkPacket packet)
        {
            using (ByteBuffer byteBuffer = new ArtifactProtocolStreamBuffer())
            {
                byteBuffer.MarkWriterIndex();
                byteBuffer.Write(new byte[4]);
                packet.ToByteBuff(byteBuffer);
                int length = (int)byteBuffer.GetLength();
                byteBuffer.ResetWriterIndex();
                byteBuffer.Write(BufferUtil.GetByte(length - 4));
                return byteBuffer.ToArray();
            }
        }
    }
    */
    class NetworkHeader
    {
        public static final int STRUCT_CODE = 183928832;


        /** 唯一表示 */
        public static final int ID = 0;
        /** 命令 */
        public static final int COMMAND = 1;
        /** 状态 */
        public static final int STATUS = 2;
        /** 模块 */
        public static final int MODULE = 3;
        /** 方法 */
        public static final int METHOD = 4;
        /** 类型 */
        public static final int TYPE = 5;
        /** 标签 */
        public static final int TAG = 6;

        /** 后续可扩展加密方式,验证方式、校验和等等 */












        /** 类型-默认包 */
        public static final int TYPE_DEFAULT = 1;
        /** 类型-心跳包 */
        public static final int TYPE_HEARTBEAT = 2;
        /** 类型-确认包 */
        public static final int TYPE_ACK = 3;
    }

    interface MessageListener{}

    interface NetClient{
        void AsyncSend(NetworkPacket packet);
    }

    static class ProtocolLListener
    {

        private static Map request = new HashMap();

        private static Map notify = new HashMap();

        private static BiConsumer errorListener = null;

        public static void registerErrorListener(BiConsumer errorListener)
        {
            ProtocolLListener.errorListener = errorListener;
        }

        public static void removeErrorListener()
        {
            ProtocolLListener.errorListener = null;
        }

        public static void execErrorListener(int _code, NetworkPacket packet) {
            if (errorListener != null) {
                errorListener.accept(_code, packet);
            }
        }

        public static void registerNotifyListener(int command, MessageListener listener)
        {
            notify.put(command, listener);
        }

        public static void registerRequestListener(String messageId, MessageListener listener)
        {
            request.put(messageId, listener);
        }

        public static void removeNotifyListener(int command)
        {
            notify.remove(command);
        }

        public static void removeRequestListener(String messageId)
        {
            request.remove(messageId);
        }

        public static MessageListener getNotifyListener(int command)
        {
            return (MessageListener)notify.get(command);
        }

        public static MessageListener getRequestListener(String messageId)
        {
            return (MessageListener)request.get(messageId);
        }

        public static void clearNotifyListener()
        {
            notify.clear();
        }

        public static void clearRequestListener()
        {
            request.clear();
        }
    }
}