feat[protocol]: java protocol with no dependency

This commit is contained in:
godotg
2024-07-05 10:07:02 +08:00
parent 73aee5c7de
commit 38e80a800f
25 changed files with 2615 additions and 10 deletions
@@ -82,6 +82,9 @@ public abstract class GenerateProtocolNote {
private static String formatNote(CodeLanguage language, String note) {
switch (language) {
case Cpp:
case Java:
case Kotlin:
case Scala:
case Golang:
case JavaScript:
case EcmaScript:
@@ -17,6 +17,7 @@ import com.zfoo.protocol.serializer.csharp.CodeGenerateCsharp;
import com.zfoo.protocol.serializer.ecmascript.CodeGenerateEcmaScript;
import com.zfoo.protocol.serializer.gdscript.CodeGenerateGdScript;
import com.zfoo.protocol.serializer.golang.CodeGenerateGolang;
import com.zfoo.protocol.serializer.java.CodeGenerateJava;
import com.zfoo.protocol.serializer.javascript.CodeGenerateJavaScript;
import com.zfoo.protocol.serializer.lua.CodeGenerateLua;
import com.zfoo.protocol.serializer.python.CodeGeneratePython;
@@ -32,23 +33,29 @@ public enum CodeLanguage {
*/
Enhance(1, null),
Cpp(1 << 1, CodeGenerateCpp.class),
Java(1<<1, CodeGenerateJava.class),
Golang(1 << 2, CodeGenerateGolang.class),
Kotlin(1<<2, null),
JavaScript(1 << 3, CodeGenerateJavaScript.class),
Scala(1<<3, null),
EcmaScript(1 << 4, CodeGenerateEcmaScript.class),
Cpp(1 << 7, CodeGenerateCpp.class),
TypeScript(1 << 5, CodeGenerateTypeScript.class),
Golang(1 << 9, CodeGenerateGolang.class),
Lua(1 << 10, CodeGenerateLua.class),
JavaScript(1 << 10, CodeGenerateJavaScript.class),
CSharp(1 << 11, CodeGenerateCsharp.class),
EcmaScript(1 << 11, CodeGenerateEcmaScript.class),
GdScript(1 << 12, CodeGenerateGdScript.class),
TypeScript(1 << 12, CodeGenerateTypeScript.class),
Python(1 << 13, CodeGeneratePython.class),
Lua(1 << 15, CodeGenerateLua.class),
CSharp(1 << 18, CodeGenerateCsharp.class),
GdScript(1 << 20, CodeGenerateGdScript.class),
Python(1 << 22, CodeGeneratePython.class),
Protobuf(1 << 30, null);
@@ -12,6 +12,7 @@
package com.zfoo.protocol.serializer;
import com.zfoo.protocol.exception.RunException;
import com.zfoo.protocol.util.FileUtils;
import com.zfoo.protocol.util.StringUtils;
@@ -73,6 +74,9 @@ public enum CodeTemplatePlaceholder {
// calculate the tab length
var startSpace = StringUtils.substringBeforeFirst(line, startPlaceholder.placeholder);
var startPlaceholderValue = placeholderMap.get(startPlaceholder);
if (startPlaceholderValue == null) {
throw new RunException("placeholder:[{}] not exist, and add [{}] to your placeholderMap", startPlaceholder, startPlaceholder);
}
var startPlaceholderValueLines = Arrays.stream(startPlaceholderValue.split(FileUtils.LS_REGEX)).map(it -> startSpace + it).toList();
// add tab length to start placeholder
@@ -83,7 +87,11 @@ public enum CodeTemplatePlaceholder {
for (var codeTemplatePlaceholder : CodeTemplatePlaceholder.values()) {
if (formatLine.contains(codeTemplatePlaceholder.placeholder)) {
formatLine = formatLine.replace(codeTemplatePlaceholder.placeholder, placeholderMap.get(codeTemplatePlaceholder));
var placeholder = placeholderMap.get(codeTemplatePlaceholder);
if (placeholder == null) {
throw new RunException("placeholder:[{}] not exist, and add [{}] to your placeholderMap", placeholder, placeholder);
}
formatLine = formatLine.replace(codeTemplatePlaceholder.placeholder, placeholder);
}
}
@@ -0,0 +1,343 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.anno.Compatible;
import com.zfoo.protocol.generate.GenerateOperation;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.generate.GenerateProtocolNote;
import com.zfoo.protocol.generate.GenerateProtocolPath;
import com.zfoo.protocol.registration.ProtocolAnalysis;
import com.zfoo.protocol.registration.ProtocolRegistration;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.serializer.CodeLanguage;
import com.zfoo.protocol.serializer.CodeTemplatePlaceholder;
import com.zfoo.protocol.serializer.ICodeGenerate;
import com.zfoo.protocol.serializer.enhance.EnhanceObjectProtocolSerializer;
import com.zfoo.protocol.serializer.reflect.*;
import com.zfoo.protocol.util.ClassUtils;
import com.zfoo.protocol.util.FileUtils;
import com.zfoo.protocol.util.ReflectionUtils;
import com.zfoo.protocol.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.zfoo.protocol.util.FileUtils.LS;
import static com.zfoo.protocol.util.StringUtils.TAB;
/**
* @author godotg
*/
public class CodeGenerateJava implements ICodeGenerate {
private static final Logger logger = LoggerFactory.getLogger(CodeGenerateJava.class);
// custom configuration
public static String protocolOutputRootPath = "zfoojava";
private static String protocolOutputPath = StringUtils.EMPTY;
public static String protocolPackage = "com.zfoo.java";
private static final Map<ISerializer, IJavaSerializer> javaSerializerMap = new HashMap<>();
public static IJavaSerializer javaSerializer(ISerializer serializer) {
return javaSerializerMap.get(serializer);
}
@Override
public void init(GenerateOperation generateOperation) {
protocolOutputPath = FileUtils.joinPath(generateOperation.getProtocolPath(), protocolOutputRootPath);
FileUtils.deleteFile(new File(protocolOutputPath));
javaSerializerMap.put(BooleanSerializer.INSTANCE, new JavaBooleanSerializer());
javaSerializerMap.put(ByteSerializer.INSTANCE, new JavaByteSerializer());
javaSerializerMap.put(ShortSerializer.INSTANCE, new JavaShortSerializer());
javaSerializerMap.put(IntSerializer.INSTANCE, new JavaIntSerializer());
javaSerializerMap.put(LongSerializer.INSTANCE, new JavaLongSerializer());
javaSerializerMap.put(FloatSerializer.INSTANCE, new JavaFloatSerializer());
javaSerializerMap.put(DoubleSerializer.INSTANCE, new JavaDoubleSerializer());
javaSerializerMap.put(StringSerializer.INSTANCE, new JavaStringSerializer());
javaSerializerMap.put(ArraySerializer.INSTANCE, new JavaArraySerializer());
javaSerializerMap.put(ListSerializer.INSTANCE, new JavaListSerializer());
javaSerializerMap.put(SetSerializer.INSTANCE, new JavaSetSerializer());
javaSerializerMap.put(MapSerializer.INSTANCE, new JavaMapSerializer());
javaSerializerMap.put(ObjectProtocolSerializer.INSTANCE, new JavaObjectProtocolSerializer());
}
@Override
public void mergerProtocol(List<ProtocolRegistration> registrations) throws IOException {
createTemplateFile();
var protocol_root_path = StringUtils.format("package {};", protocolPackage);
var protocolManagerTemplate = ClassUtils.getFileFromClassPathToString("java/ProtocolManagerTemplate.java");
var protocol_manager_registrations = new StringBuilder();
for (var registration : registrations) {
var protocol_id = registration.protocolId();
var protocol_name = registration.protocolConstructor().getDeclaringClass().getSimpleName();
protocol_manager_registrations.append(StringUtils.format("protocols[{}] = Protocols.registration{};", protocol_id, protocol_name)).append(LS);
protocol_manager_registrations.append(StringUtils.format("protocolIdMap.put(Protocols.{}.class, (short){});", protocol_name, protocol_id)).append(LS);
}
var placeholderMap = Map.of(CodeTemplatePlaceholder.protocol_root_path, protocol_root_path
, CodeTemplatePlaceholder.protocol_imports, StringUtils.EMPTY
, CodeTemplatePlaceholder.protocol_manager_registrations, protocol_manager_registrations.toString());
var formatProtocolManagerTemplate = CodeTemplatePlaceholder.formatTemplate(protocolManagerTemplate, placeholderMap);
var protocolManagerFile = new File(StringUtils.format("{}/{}", protocolOutputRootPath, "ProtocolManager.java"));
FileUtils.writeStringToFile(protocolManagerFile, formatProtocolManagerTemplate, true);
logger.info("Generated Java protocol manager file:[{}] is in path:[{}]", protocolManagerFile.getName(), protocolManagerFile.getAbsolutePath());
var protocol_class = new StringBuilder();
var protocol_registration = new StringBuilder();
for (var registration : GenerateProtocolFile.subProtocolFirst(registrations)) {
var protocol_id = registration.protocolId();
// protocol
protocol_class.append(protocol_class(registration)).append(LS);
// registration
protocol_registration.append(protocol_registration(registration)).append(LS);
}
var protocolTemplate = ClassUtils.getFileFromClassPathToString("java/ProtocolsTemplate.java");
var formatProtocolTemplate = CodeTemplatePlaceholder.formatTemplate(protocolTemplate, Map.of(
CodeTemplatePlaceholder.protocol_root_path, protocol_root_path
, CodeTemplatePlaceholder.protocol_imports, StringUtils.EMPTY
, CodeTemplatePlaceholder.protocol_class, protocol_class.toString().replace("public class", "public static class")
, CodeTemplatePlaceholder.protocol_registration, protocol_registration.toString()
));
var outputPath = StringUtils.format("{}/Protocols.java", protocolOutputPath);
var file = new File(outputPath);
FileUtils.writeStringToFile(file, formatProtocolTemplate, true);
logger.info("Generated Java protocol file:[{}] is in path:[{}]", file.getName(), file.getAbsolutePath());
}
@Override
public void foldProtocol(List<ProtocolRegistration> registrations) throws IOException {
createTemplateFile();
var protocolManagerTemplate = ClassUtils.getFileFromClassPathToString("java/ProtocolManagerTemplate.java");
var protocol_manager_registrations = new StringBuilder();
var protocol_imports = new StringBuilder();
for (var registration : registrations) {
var protocol_id = registration.protocolId();
var protocol_name = registration.protocolConstructor().getDeclaringClass().getSimpleName();
protocol_imports.append(StringUtils.format("import {}.{}.{};", protocolPackage, GenerateProtocolPath.protocolPathPeriod(protocol_id), protocol_name)).append(LS);
protocol_manager_registrations.append(StringUtils.format("protocols[{}] = {}.registration{};", protocol_id, protocol_name, protocol_name)).append(LS);
protocol_manager_registrations.append(StringUtils.format("protocolIdMap.put({}.class, (short){});", protocol_name, protocol_id)).append(LS);
}
var placeholderMap = Map.of(CodeTemplatePlaceholder.protocol_root_path, StringUtils.format("package {};", protocolPackage)
, CodeTemplatePlaceholder.protocol_imports, protocol_imports.toString()
, CodeTemplatePlaceholder.protocol_manager_registrations, protocol_manager_registrations.toString());
var formatProtocolManagerTemplate = CodeTemplatePlaceholder.formatTemplate(protocolManagerTemplate, placeholderMap);
var protocolManagerFile = new File(StringUtils.format("{}/{}", protocolOutputRootPath, "ProtocolManager.java"));
FileUtils.writeStringToFile(protocolManagerFile, formatProtocolManagerTemplate, true);
logger.info("Generated Java protocol manager file:[{}] is in path:[{}]", protocolManagerFile.getName(), protocolManagerFile.getAbsolutePath());
for (var registration : registrations) {
var protocol_id = registration.protocolId();
var protocol_name = registration.protocolConstructor().getDeclaringClass().getSimpleName();
var protocolTemplate = ClassUtils.getFileFromClassPathToString("java/ProtocolTemplate.java");
var protocol_root_path = StringUtils.format("package {}.{};", protocolPackage, GenerateProtocolPath.protocolPathPeriod(protocol_id));
var formatProtocolTemplate = CodeTemplatePlaceholder.formatTemplate(protocolTemplate, Map.of(
CodeTemplatePlaceholder.protocol_root_path, protocol_root_path
, CodeTemplatePlaceholder.protocol_imports, protocol_imports_fold(registration)
, CodeTemplatePlaceholder.protocol_note, GenerateProtocolNote.protocol_note(protocol_id, CodeLanguage.Java)
, CodeTemplatePlaceholder.protocol_name, protocol_name
, CodeTemplatePlaceholder.protocol_field_definition, protocol_field_definition(registration)
, CodeTemplatePlaceholder.protocol_registration, protocol_registration(registration)
));
var outputPath = StringUtils.format("{}/{}/{}.java", protocolOutputPath, GenerateProtocolPath.protocolPathPeriod(protocol_id), protocol_name);
var file = new File(outputPath);
FileUtils.writeStringToFile(file, formatProtocolTemplate, true);
logger.info("Generated Java protocol file:[{}] is in path:[{}]", file.getName(), file.getAbsolutePath());
}
}
@Override
public void defaultProtocol(List<ProtocolRegistration> registrations) throws IOException {
createTemplateFile();
var protocol_root_path = StringUtils.format("package {};", protocolPackage);
var protocolManagerTemplate = ClassUtils.getFileFromClassPathToString("java/ProtocolManagerTemplate.java");
var protocol_manager_registrations = new StringBuilder();
for (var registration : registrations) {
var protocol_id = registration.protocolId();
var protocol_name = registration.protocolConstructor().getDeclaringClass().getSimpleName();
protocol_manager_registrations.append(StringUtils.format("protocols[{}] = {}.registration{};", protocol_id, protocol_name, protocol_name)).append(LS);
protocol_manager_registrations.append(StringUtils.format("protocolIdMap.put({}.class, (short){});", protocol_name, protocol_id)).append(LS);
}
var placeholderMap = Map.of(CodeTemplatePlaceholder.protocol_root_path, protocol_root_path
, CodeTemplatePlaceholder.protocol_imports, StringUtils.EMPTY
, CodeTemplatePlaceholder.protocol_manager_registrations, protocol_manager_registrations.toString());
var formatProtocolManagerTemplate = CodeTemplatePlaceholder.formatTemplate(protocolManagerTemplate, placeholderMap);
var protocolManagerFile = new File(StringUtils.format("{}/{}", protocolOutputRootPath, "ProtocolManager.java"));
FileUtils.writeStringToFile(protocolManagerFile, formatProtocolManagerTemplate, true);
logger.info("Generated Java protocol manager file:[{}] is in path:[{}]", protocolManagerFile.getName(), protocolManagerFile.getAbsolutePath());
for (var registration : registrations) {
var protocol_id = registration.protocolId();
var protocol_name = registration.protocolConstructor().getDeclaringClass().getSimpleName();
var protocolTemplate = ClassUtils.getFileFromClassPathToString("java/ProtocolTemplate.java");
var formatProtocolTemplate = CodeTemplatePlaceholder.formatTemplate(protocolTemplate, Map.of(
CodeTemplatePlaceholder.protocol_root_path, protocol_root_path
, CodeTemplatePlaceholder.protocol_imports, StringUtils.EMPTY
, CodeTemplatePlaceholder.protocol_note, GenerateProtocolNote.protocol_note(protocol_id, CodeLanguage.Java)
, CodeTemplatePlaceholder.protocol_name, protocol_name
, CodeTemplatePlaceholder.protocol_field_definition, protocol_field_definition(registration)
, CodeTemplatePlaceholder.protocol_registration, protocol_registration(registration)
));
var outputPath = StringUtils.format("{}/{}.java", protocolOutputPath, protocol_name);
var file = new File(outputPath);
FileUtils.writeStringToFile(file, formatProtocolTemplate, true);
logger.info("Generated Java protocol file:[{}] is in path:[{}]", file.getName(), file.getAbsolutePath());
}
}
private void createTemplateFile() {
var rootPackage = StringUtils.format("package {};", protocolPackage);
var list = List.of("java/IProtocolRegistration.java"
, "java/ByteBuffer.java");
for (var fileName : list) {
// IProtocolRegistration
var template = ClassUtils.getFileFromClassPathToString(fileName);
var formatTemplate = CodeTemplatePlaceholder.formatTemplate(template, Map.of(
CodeTemplatePlaceholder.protocol_root_path, rootPackage
, CodeTemplatePlaceholder.protocol_imports, StringUtils.EMPTY
));
var createFile = new File(StringUtils.format("{}/{}", protocolOutputPath, StringUtils.substringAfterFirst(fileName, "java/")));
FileUtils.writeStringToFile(createFile, formatTemplate, false);
}
}
private String protocol_class(ProtocolRegistration registration) {
var protocol_id = registration.protocolId();
var protocol_name = registration.protocolConstructor().getDeclaringClass().getSimpleName();
var protocolTemplate = ClassUtils.getFileFromClassPathToString("java/ProtocolClassTemplate.java");
var formatProtocolTemplate = CodeTemplatePlaceholder.formatTemplate(protocolTemplate, Map.of(
CodeTemplatePlaceholder.protocol_note, GenerateProtocolNote.protocol_note(protocol_id, CodeLanguage.Java)
, CodeTemplatePlaceholder.protocol_name, protocol_name
, CodeTemplatePlaceholder.protocol_id, String.valueOf(protocol_id)
, CodeTemplatePlaceholder.protocol_field_definition, protocol_field_definition(registration)
, CodeTemplatePlaceholder.protocol_registration, protocol_registration(registration)
));
return formatProtocolTemplate;
}
private String protocol_registration(ProtocolRegistration registration) {
var protocol_id = registration.protocolId();
var protocol_name = registration.protocolConstructor().getDeclaringClass().getSimpleName();
var protocolTemplate = ClassUtils.getFileFromClassPathToString("java/ProtocolRegistrationTemplate.java");
var formatProtocolTemplate = CodeTemplatePlaceholder.formatTemplate(protocolTemplate, Map.of(
CodeTemplatePlaceholder.protocol_name, protocol_name
, CodeTemplatePlaceholder.protocol_id, String.valueOf(protocol_id)
, CodeTemplatePlaceholder.protocol_write_serialization, protocol_write_serialization(registration)
, CodeTemplatePlaceholder.protocol_read_deserialization, protocol_read_deserialization(registration)
));
return formatProtocolTemplate;
}
private String protocol_imports_fold(ProtocolRegistration registration) {
var protocolId = registration.getId();
var subProtocols = ProtocolAnalysis.getAllSubProtocolIds(protocolId);
var javaBuilder = new StringBuilder();
for (var subProtocolId : subProtocols) {
var protocolName = EnhanceObjectProtocolSerializer.getProtocolClassSimpleName(subProtocolId);
var subProtocolPath = StringUtils.format("import {}.{}.{};", protocolPackage, GenerateProtocolPath.protocolPathPeriod(subProtocolId), protocolName);
javaBuilder.append(subProtocolPath).append(LS);
}
javaBuilder.append(StringUtils.format("import {}.IProtocolRegistration;", protocolPackage)).append(LS);
javaBuilder.append(StringUtils.format("import {}.ByteBuffer;", protocolPackage)).append(LS);
return javaBuilder.toString();
}
private String protocol_field_definition(ProtocolRegistration registration) {
var protocolId = registration.getId();
var fields = registration.getFields();
var fieldRegistrations = registration.getFieldRegistrations();
var javaBuilder = new StringBuilder();
var sequencedFields = ReflectionUtils.notStaticAndTransientFields(registration.getConstructor().getDeclaringClass());
for (int i = 0; i < sequencedFields.size(); i++) {
var field = sequencedFields.get(i);
IFieldRegistration fieldRegistration = fieldRegistrations[GenerateProtocolFile.indexOf(fields, field)];
var fieldName = field.getName();
var propertyType = toJavaClassName(field.getGenericType().getTypeName());
var propertyFullName = StringUtils.format("public {} {};", propertyType, fieldName);
// 生成注释
var fieldNotes = GenerateProtocolNote.fieldNotes(protocolId, fieldName, CodeLanguage.Java);
for (var fieldNote : fieldNotes) {
javaBuilder.append(fieldNote).append(LS);
}
javaBuilder.append(propertyFullName).append(LS);
}
return javaBuilder.toString();
}
private String protocol_write_serialization(ProtocolRegistration registration) {
GenerateProtocolFile.localVariableId = 0;
var fields = registration.getFields();
var fieldRegistrations = registration.getFieldRegistrations();
var javaBuilder = new StringBuilder();
if (registration.isCompatible()) {
javaBuilder.append("int beforeWriteIndex = buffer.writeOffset();").append(LS);
javaBuilder.append(StringUtils.format("buffer.writeInt({});", registration.getPredictionLength())).append(LS);
} else {
javaBuilder.append("buffer.writeInt(-1);").append(LS);
}
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
var fieldRegistration = fieldRegistrations[i];
javaSerializer(fieldRegistration.serializer()).writeObject(javaBuilder, "message." + field.getName(), 0, field, fieldRegistration);
}
if (registration.isCompatible()) {
javaBuilder.append(StringUtils.format("buffer.adjustPadding({}, beforeWriteIndex);", registration.getPredictionLength())).append(LS);
}
return javaBuilder.toString();
}
private String protocol_read_deserialization(ProtocolRegistration registration) {
GenerateProtocolFile.localVariableId = 0;
var fields = registration.getFields();
var fieldRegistrations = registration.getFieldRegistrations();
var javaBuilder = new StringBuilder();
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
var fieldRegistration = fieldRegistrations[i];
if (field.isAnnotationPresent(Compatible.class)) {
javaBuilder.append("if (buffer.compatibleRead(beforeReadIndex, length)) {").append(LS);
var compatibleReadObject = javaSerializer(fieldRegistration.serializer()).readObject(javaBuilder, 1, field, fieldRegistration);
javaBuilder.append(TAB).append(StringUtils.format("packet.{} = {};", field.getName(), compatibleReadObject)).append(LS);
javaBuilder.append("}").append(LS);
continue;
}
var readObject = javaSerializer(fieldRegistration.serializer()).readObject(javaBuilder, 0, field, fieldRegistration);
javaBuilder.append(StringUtils.format("packet.{} = {};", field.getName(), readObject)).append(LS);
}
return javaBuilder.toString();
}
public static String toJavaClassName(String typeName) {
typeName = typeName.replaceAll("java.util.|java.lang.", StringUtils.EMPTY);
typeName = typeName.replaceAll("[a-zA-Z0-9_.]*\\.", StringUtils.EMPTY);
return typeName;
}
}
@@ -0,0 +1,29 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import java.lang.reflect.Field;
/**
* @author godotg
*/
public interface IJavaSerializer {
void writeObject(StringBuilder builder, String objectStr, int deep, Field field, IFieldRegistration fieldRegistration);
String readObject(StringBuilder builder, int deep, Field field, IFieldRegistration fieldRegistration);
}
@@ -0,0 +1,108 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.registration.field.ArrayField;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.serializer.CodeLanguage;
import com.zfoo.protocol.serializer.CutDownArraySerializer;
import com.zfoo.protocol.util.StringUtils;
import java.lang.reflect.Field;
import static com.zfoo.protocol.util.FileUtils.LS;
/**
* @author godotg
*/
public class JavaArraySerializer implements IJavaSerializer {
@Override
public void writeObject(StringBuilder builder, String objectStr, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
if (CutDownArraySerializer.getInstance().writeObject(builder, objectStr, field, fieldRegistration, CodeLanguage.Java)) {
return;
}
ArrayField arrayField = (ArrayField) fieldRegistration;
builder.append(StringUtils.format("if (({} == null) || ({}.length == 0)) {", objectStr, objectStr)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append("buffer.writeInt(0);").append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append("} else {").append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append(StringUtils.format("buffer.writeInt({}.length);", objectStr)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
String length = "length" + GenerateProtocolFile.localVariableId++;
builder.append(StringUtils.format("int {} = {}.length;", length, objectStr)).append(LS);
String i = "i" + GenerateProtocolFile.localVariableId++;
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append(StringUtils.format("for (int {} = 0; {} < {}; {}++) {", i, i, length, i)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 2);
String element = "element" + GenerateProtocolFile.localVariableId++;
builder.append(StringUtils.format("{} {} = {}[{}];", CodeGenerateJava.toJavaClassName(arrayField.getType().getSimpleName()), element, objectStr, i)).append(LS);
CodeGenerateJava.javaSerializer(arrayField.getArrayElementRegistration().serializer())
.writeObject(builder, element, deep + 2, field, arrayField.getArrayElementRegistration());
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append("}").append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append("}").append(LS);
}
@Override
public String readObject(StringBuilder builder, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
var cutDown = CutDownArraySerializer.getInstance().readObject(builder, field, fieldRegistration, CodeLanguage.Java);
if (cutDown != null) {
return cutDown;
}
var arrayField = (ArrayField) fieldRegistration;
var result = "result" + GenerateProtocolFile.localVariableId++;
var typeName = CodeGenerateJava.toJavaClassName(arrayField.getType().getSimpleName());
var i = "index" + GenerateProtocolFile.localVariableId++;
var size = "size" + GenerateProtocolFile.localVariableId++;
builder.append(StringUtils.format("int {} = buffer.readInt();", size)).append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("{}[] {} = new {}[{}];", typeName, result, typeName, size)).append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("if ({} > 0) {", size)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append(StringUtils.format("for (int {} = 0; {} < {}; {}++) {", i, i, size, i)).append(LS);
var readObject = CodeGenerateJava.javaSerializer(arrayField.getArrayElementRegistration().serializer())
.readObject(builder, deep + 2, field, arrayField.getArrayElementRegistration());
GenerateProtocolFile.addTab(builder, deep + 2);
builder.append(StringUtils.format("{}[{}] = {};", result, i, readObject));
builder.append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append("}").append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append("}").append(LS);
return result;
}
}
@@ -0,0 +1,43 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.util.StringUtils;
import java.lang.reflect.Field;
import static com.zfoo.protocol.util.FileUtils.LS;
/**
* @author godotg
*/
public class JavaBooleanSerializer implements IJavaSerializer {
@Override
public void writeObject(StringBuilder builder, String objectStr, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("buffer.writeBool({});", objectStr)).append(LS);
}
@Override
public String readObject(StringBuilder builder, int deep, Field field, IFieldRegistration fieldRegistration) {
String result = "result" + GenerateProtocolFile.localVariableId++;
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("boolean {} = buffer.readBool();", result)).append(LS);
return result;
}
}
@@ -0,0 +1,44 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.util.StringUtils;
import java.lang.reflect.Field;
import static com.zfoo.protocol.util.FileUtils.LS;
/**
* @author godotg
*/
public class JavaByteSerializer implements IJavaSerializer {
@Override
public void writeObject(StringBuilder builder, String objectStr, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("buffer.writeByte({});", objectStr)).append(LS);
}
@Override
public String readObject(StringBuilder builder, int deep, Field field, IFieldRegistration fieldRegistration) {
String result = "result" + GenerateProtocolFile.localVariableId++;
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("byte {} = buffer.readByte();", result)).append(LS);
return result;
}
}
@@ -0,0 +1,44 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.util.StringUtils;
import java.lang.reflect.Field;
import static com.zfoo.protocol.util.FileUtils.LS;
/**
* @author godotg
*/
public class JavaDoubleSerializer implements IJavaSerializer {
@Override
public void writeObject(StringBuilder builder, String objectStr, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("buffer.writeDouble({});", objectStr)).append(LS);
}
@Override
public String readObject(StringBuilder builder, int deep, Field field, IFieldRegistration fieldRegistration) {
String result = "result" + GenerateProtocolFile.localVariableId++;
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("double {} = buffer.readDouble();", result)).append(LS);
return result;
}
}
@@ -0,0 +1,44 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.util.StringUtils;
import java.lang.reflect.Field;
import static com.zfoo.protocol.util.FileUtils.LS;
/**
* @author godotg
*/
public class JavaFloatSerializer implements IJavaSerializer {
@Override
public void writeObject(StringBuilder builder, String objectStr, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("buffer.writeFloat({});", objectStr)).append(LS);
}
@Override
public String readObject(StringBuilder builder, int deep, Field field, IFieldRegistration fieldRegistration) {
String result = "result" + GenerateProtocolFile.localVariableId++;
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("float {} = buffer.readFloat();", result)).append(LS);
return result;
}
}
@@ -0,0 +1,43 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.util.StringUtils;
import java.lang.reflect.Field;
import static com.zfoo.protocol.util.FileUtils.LS;
/**
* @author godotg
*/
public class JavaIntSerializer implements IJavaSerializer {
@Override
public void writeObject(StringBuilder builder, String objectStr, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("buffer.writeInt({});", objectStr)).append(LS);
}
@Override
public String readObject(StringBuilder builder, int deep, Field field, IFieldRegistration fieldRegistration) {
String result = "result" + GenerateProtocolFile.localVariableId++;
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("int {} = buffer.readInt();", result)).append(LS);
return result;
}
}
@@ -0,0 +1,107 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.registration.field.ListField;
import com.zfoo.protocol.serializer.CodeLanguage;
import com.zfoo.protocol.serializer.CutDownListSerializer;
import com.zfoo.protocol.util.StringUtils;
import java.lang.reflect.Field;
import static com.zfoo.protocol.util.FileUtils.LS;
/**
* @author godotg
*/
public class JavaListSerializer implements IJavaSerializer {
@Override
public void writeObject(StringBuilder builder, String objectStr, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
if (CutDownListSerializer.getInstance().writeObject(builder, objectStr, field, fieldRegistration, CodeLanguage.Java)) {
return;
}
ListField listField = (ListField) fieldRegistration;
builder.append(StringUtils.format("if ({} == null) {", objectStr)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append("buffer.writeInt(0);").append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append("}").append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append("else {").append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append(StringUtils.format("buffer.writeInt({}.size());", objectStr)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
String length = "length" + GenerateProtocolFile.localVariableId++;
builder.append(StringUtils.format("int {} = {}.size();", length, objectStr)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
String element = "element" + GenerateProtocolFile.localVariableId++;
builder.append(StringUtils.format("for (var {} : {}) {", element, objectStr)).append(LS);
CodeGenerateJava.javaSerializer(listField.getListElementRegistration().serializer())
.writeObject(builder, element, deep + 2, field, listField.getListElementRegistration());
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append("}").append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append("}").append(LS);
}
@Override
public String readObject(StringBuilder builder, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
var cutDown = CutDownListSerializer.getInstance().readObject(builder, field, fieldRegistration, CodeLanguage.Java);
if (cutDown != null) {
return cutDown;
}
var listField = (ListField) fieldRegistration;
var result = "result" + GenerateProtocolFile.localVariableId++;
var typeName = CodeGenerateJava.toJavaClassName(listField.getType().toString());
var i = "index" + GenerateProtocolFile.localVariableId++;
var size = "size" + GenerateProtocolFile.localVariableId++;
builder.append(StringUtils.format("int {} = buffer.readInt();", size)).append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("var {} = new Array{}({});", result, typeName, size)).append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("if ({} > 0) {", size)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append(StringUtils.format("for (int {} = 0; {} < {}; {}++) {", i, i, size, i)).append(LS);
var readObject = CodeGenerateJava.javaSerializer(listField.getListElementRegistration().serializer())
.readObject(builder, deep + 2, field, listField.getListElementRegistration());
GenerateProtocolFile.addTab(builder, deep + 2);
builder.append(StringUtils.format("{}.add({});", result, readObject)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append("}").append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append("}").append(LS);
return result;
}
}
@@ -0,0 +1,44 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.util.StringUtils;
import java.lang.reflect.Field;
import static com.zfoo.protocol.util.FileUtils.LS;
/**
* @author godotg
*/
public class JavaLongSerializer implements IJavaSerializer {
@Override
public void writeObject(StringBuilder builder, String objectStr, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("buffer.writeLong({});", objectStr)).append(LS);
}
@Override
public String readObject(StringBuilder builder, int deep, Field field, IFieldRegistration fieldRegistration) {
String result = "result" + GenerateProtocolFile.localVariableId++;
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("long {} = buffer.readLong();", result)).append(LS);
return result;
}
}
@@ -0,0 +1,119 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.registration.field.MapField;
import com.zfoo.protocol.serializer.CodeLanguage;
import com.zfoo.protocol.serializer.CutDownMapSerializer;
import com.zfoo.protocol.util.StringUtils;
import java.lang.reflect.Field;
import static com.zfoo.protocol.util.FileUtils.LS;
/**
* @author godotg
*/
public class JavaMapSerializer implements IJavaSerializer {
@Override
public void writeObject(StringBuilder builder, String objectStr, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
if (CutDownMapSerializer.getInstance().writeObject(builder, objectStr, field, fieldRegistration, CodeLanguage.Java)) {
return;
}
MapField mapField = (MapField) fieldRegistration;
builder.append(StringUtils.format("if ({} == null) {", objectStr, objectStr)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append("buffer.writeInt(0);").append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append("} else {").append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append(StringUtils.format("buffer.writeInt({}.size());", objectStr)).append(LS);
String i = "i" + GenerateProtocolFile.localVariableId++;
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append(StringUtils.format("for (var {} : {}.entrySet()) {", i, objectStr)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 2);
String key = "keyElement" + GenerateProtocolFile.localVariableId++;
String value = "valueElement" + GenerateProtocolFile.localVariableId++;
builder.append(StringUtils.format("var {} = {}.getKey();", key, i)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 2);
builder.append(StringUtils.format("var {} = {}.getValue();", value, i)).append(LS);
CodeGenerateJava.javaSerializer(mapField.getMapKeyRegistration().serializer())
.writeObject(builder, key, deep + 2, field, mapField.getMapKeyRegistration());
CodeGenerateJava.javaSerializer(mapField.getMapValueRegistration().serializer())
.writeObject(builder, value, deep + 2, field, mapField.getMapValueRegistration());
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append("}").append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append("}").append(LS);
}
@Override
public String readObject(StringBuilder builder, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
var cutDown = CutDownMapSerializer.getInstance().readObject(builder, field, fieldRegistration, CodeLanguage.Java);
if (cutDown != null) {
return cutDown;
}
MapField mapField = (MapField) fieldRegistration;
String result = "result" + GenerateProtocolFile.localVariableId++;
var typeName = CodeGenerateJava.toJavaClassName(mapField.getType().toString());
String size = "size" + GenerateProtocolFile.localVariableId++;
builder.append(StringUtils.format("int {} = buffer.readInt();", size)).append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("var {} = new Hash{}({});", result, typeName, size)).append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("if ({} > 0) {", size)).append(LS);
String i = "index" + GenerateProtocolFile.localVariableId++;
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append(StringUtils.format("for (var {} = 0; {} < {}; {}++) {", i, i, size, i)).append(LS);
String keyObject = CodeGenerateJava.javaSerializer(mapField.getMapKeyRegistration().serializer())
.readObject(builder, deep + 2, field, mapField.getMapKeyRegistration());
String valueObject = CodeGenerateJava.javaSerializer(mapField.getMapValueRegistration().serializer())
.readObject(builder, deep + 2, field, mapField.getMapValueRegistration());
GenerateProtocolFile.addTab(builder, deep + 2);
builder.append(StringUtils.format("{}.put({}, {});", result, keyObject, valueObject)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append("}").append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append("}").append(LS);
return result;
}
}
@@ -0,0 +1,53 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.registration.field.ObjectProtocolField;
import com.zfoo.protocol.serializer.enhance.EnhanceObjectProtocolSerializer;
import com.zfoo.protocol.util.StringUtils;
import java.lang.reflect.Field;
import static com.zfoo.protocol.util.FileUtils.LS;
/**
* @author godotg
*/
public class JavaObjectProtocolSerializer implements IJavaSerializer {
@Override
public void writeObject(StringBuilder builder, String objectStr, int deep, Field field, IFieldRegistration fieldRegistration) {
ObjectProtocolField objectProtocolField = (ObjectProtocolField) fieldRegistration;
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("buffer.writePacket({}, (short){});", objectStr, objectProtocolField.getProtocolId()))
.append(LS);
}
@Override
public String readObject(StringBuilder builder, int deep, Field field, IFieldRegistration fieldRegistration) {
ObjectProtocolField objectProtocolField = (ObjectProtocolField) fieldRegistration;
String result = "result" + GenerateProtocolFile.localVariableId++;
var protocolSimpleName = EnhanceObjectProtocolSerializer.getProtocolClassSimpleName(objectProtocolField.getProtocolId());
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("{} {} = ({}) buffer.readPacket((short){});", protocolSimpleName, result, protocolSimpleName, objectProtocolField.getProtocolId()))
.append(LS);
return result;
}
}
@@ -0,0 +1,103 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.registration.field.SetField;
import com.zfoo.protocol.serializer.CodeLanguage;
import com.zfoo.protocol.serializer.CutDownSetSerializer;
import com.zfoo.protocol.util.StringUtils;
import java.lang.reflect.Field;
import static com.zfoo.protocol.util.FileUtils.LS;
/**
* @author godotg
*/
public class JavaSetSerializer implements IJavaSerializer {
@Override
public void writeObject(StringBuilder builder, String objectStr, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
if (CutDownSetSerializer.getInstance().writeObject(builder, objectStr, field, fieldRegistration, CodeLanguage.Java)) {
return;
}
SetField setField = (SetField) fieldRegistration;
builder.append(StringUtils.format("if ({} == null) {", objectStr)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append("buffer.writeInt(0);").append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append("} else {").append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append(StringUtils.format("buffer.writeInt({}.size());", objectStr)).append(LS);
String element = "i" + GenerateProtocolFile.localVariableId++;
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append(StringUtils.format("for (var {} : {}) {", element, objectStr)).append(LS);
CodeGenerateJava.javaSerializer(setField.getSetElementRegistration().serializer())
.writeObject(builder, element, deep + 2, field, setField.getSetElementRegistration());
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append("}").append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append("}").append(LS);
}
@Override
public String readObject(StringBuilder builder, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
var cutDown = CutDownSetSerializer.getInstance().readObject(builder, field, fieldRegistration, CodeLanguage.Java);
if (cutDown != null) {
return cutDown;
}
SetField setField = (SetField) fieldRegistration;
var result = "result" + GenerateProtocolFile.localVariableId++;
var typeName = CodeGenerateJava.toJavaClassName(setField.getType().toString());
var i = "index" + GenerateProtocolFile.localVariableId++;
var size = "size" + GenerateProtocolFile.localVariableId++;
builder.append(StringUtils.format("int {} = buffer.readInt();", size)).append(LS);
GenerateProtocolFile.addTab(builder, deep);
// unity里不支持HashSet的初始化大小
// builder.append("var " + result + " = new " + typeName + "(" + size + ");" + LS);
builder.append(StringUtils.format("var {} = new Hash{}();", result, typeName)).append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("if ({} > 0) {", size)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append(StringUtils.format("for (int {} = 0; {} < {}; {}++) {", i, i, size, i)).append(LS);
var readObject = CodeGenerateJava.javaSerializer(setField.getSetElementRegistration().serializer())
.readObject(builder, deep + 2, field, setField.getSetElementRegistration());
GenerateProtocolFile.addTab(builder, deep + 2);
builder.append(StringUtils.format("{}.add({});", result, readObject)).append(LS);
GenerateProtocolFile.addTab(builder, deep + 1);
builder.append("}").append(LS);
GenerateProtocolFile.addTab(builder, deep);
builder.append("}").append(LS);
return result;
}
}
@@ -0,0 +1,44 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.util.StringUtils;
import java.lang.reflect.Field;
import static com.zfoo.protocol.util.FileUtils.LS;
/**
* @author godotg
*/
public class JavaShortSerializer implements IJavaSerializer {
@Override
public void writeObject(StringBuilder builder, String objectStr, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("buffer.writeShort({});", objectStr)).append(LS);
}
@Override
public String readObject(StringBuilder builder, int deep, Field field, IFieldRegistration fieldRegistration) {
String result = "result" + GenerateProtocolFile.localVariableId++;
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("short {} = buffer.readShort();", result)).append(LS);
return result;
}
}
@@ -0,0 +1,45 @@
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.java;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.util.StringUtils;
import java.lang.reflect.Field;
import static com.zfoo.protocol.util.FileUtils.LS;
/**
* @author godotg
*/
public class JavaStringSerializer implements IJavaSerializer {
@Override
public void writeObject(StringBuilder builder, String objectStr, int deep, Field field, IFieldRegistration fieldRegistration) {
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("buffer.writeString({});", objectStr)).append(LS);
}
@Override
public String readObject(StringBuilder builder, int deep, Field field, IFieldRegistration fieldRegistration) {
String result = "result" + GenerateProtocolFile.localVariableId++;
GenerateProtocolFile.addTab(builder, deep);
builder.append(StringUtils.format("String {} = buffer.readString();", result)).append(LS);
return result;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,10 @@
${protocol_root_path}
public interface IProtocolRegistration {
short protocolId();
void write(ByteBuffer buffer, Object packet);
Object read(ByteBuffer buffer);
}
@@ -0,0 +1,4 @@
${protocol_note}
public class ${protocol_name} {
${protocol_field_definition}
}
@@ -0,0 +1,44 @@
${protocol_root_path}
import java.util.HashMap;
import java.util.Map;
${protocol_imports}
public class ProtocolManager {
public static final short MAX_PROTOCOL_NUM = Short.MAX_VALUE;
public static final IProtocolRegistration[] protocols = new IProtocolRegistration[MAX_PROTOCOL_NUM];
public static Map<Class<?>, Short> protocolIdMap = new HashMap<>();
public static void initProtocol() {
// initProtocol
${protocol_manager_registrations}
}
public static short getProtocolId(Class<?> clazz) {
return protocolIdMap.get(clazz);
}
public static IProtocolRegistration getProtocol(short protocolId) {
var protocol = protocols[protocolId];
if (protocol == null) {
throw new RuntimeException("[protocolId:" + protocolId + "] not exist");
}
return protocol;
}
public static void write(ByteBuffer buffer, Object packet) {
var protocolId = getProtocolId(packet.getClass());
// write protocol id to buffer
buffer.writeShort(protocolId);
// write packet
getProtocol(protocolId).write(buffer, packet);
}
public static Object read(ByteBuffer buffer) {
var protocolId = buffer.readShort();
return getProtocol(protocolId).read(buffer);
}
}
@@ -0,0 +1,31 @@
public static final IProtocolRegistration registration${protocol_name} = new IProtocolRegistration() {
@Override
public short protocolId() {
return ${protocol_id};
}
@Override
public void write(ByteBuffer buffer, Object packet) {
if (packet == null) {
buffer.writeInt(0);
return;
}
${protocol_name} message = (${protocol_name}) packet;
${protocol_write_serialization}
}
@Override
public Object read(ByteBuffer buffer) {
var length = buffer.readInt();
if (length == 0) {
return null;
}
var beforeReadIndex = buffer.readOffset();
var packet = new ${protocol_name}();
${protocol_read_deserialization}
if (length > 0) {
buffer.setReadOffset(beforeReadIndex + length);
}
return packet;
}
};
@@ -0,0 +1,9 @@
${protocol_root_path}
${protocol_imports}
import java.util.*;
${protocol_note}
public class ${protocol_name} {
${protocol_field_definition}
${protocol_registration}
}
@@ -0,0 +1,10 @@
${protocol_root_path}
${protocol_imports}
import java.util.*;
public class Protocols {
${protocol_class}
// -----------------------------------------------------------------------------------------------------------------
${protocol_registration}
}