use of org.infinispan.protostream.EnumMarshaller in project kogito-runtimes by kiegroup.
the class AbstractMarshallerGenerator method generate.
public List<CompilationUnit> generate(FileDescriptorSource proto) throws IOException {
List<CompilationUnit> units = new ArrayList<>();
TemplatedGenerator generator = TemplatedGenerator.builder().withFallbackContext(JavaKogitoBuildContext.CONTEXT_NAME).withTemplateBasePath(TEMPLATE_PERSISTENCE_FOLDER).build(context, "MessageMarshaller");
Predicate<String> typeExclusions = ExclusionTypeUtils.createTypeExclusions();
// filter types that don't require to create a marshaller
Predicate<Descriptor> packagePredicate = (msg) -> !msg.getFileDescriptor().getPackage().equals("kogito");
Predicate<Descriptor> jacksonPredicate = (msg) -> !typeExclusions.test(packageFromOption(msg.getFileDescriptor(), msg) + "." + msg.getName());
Predicate<Descriptor> predicate = packagePredicate.and(jacksonPredicate);
CompilationUnit parsedClazzFile = generator.compilationUnitOrThrow();
SerializationContext serializationContext = new SerializationContextImpl(Configuration.builder().build());
FileDescriptorSource kogitoTypesDescriptor = new FileDescriptorSource().addProtoFile("kogito-types.proto", context.getClassLoader().getResourceAsStream("META-INF/kogito-types.proto"));
serializationContext.registerProtoFiles(kogitoTypesDescriptor);
serializationContext.registerProtoFiles(proto);
Map<String, FileDescriptor> descriptors = serializationContext.getFileDescriptors();
for (Entry<String, FileDescriptor> entry : descriptors.entrySet()) {
FileDescriptor d = entry.getValue();
List<Descriptor> messages = d.getMessageTypes().stream().filter(predicate).collect(Collectors.toList());
for (Descriptor msg : messages) {
CompilationUnit clazzFile = parsedClazzFile.clone();
units.add(clazzFile);
String javaType = packageFromOption(d, msg) + "." + msg.getName();
clazzFile.setPackageDeclaration(d.getPackage());
ClassOrInterfaceDeclaration clazz = clazzFile.findFirst(ClassOrInterfaceDeclaration.class, sl -> true).orElseThrow(() -> new InvalidTemplateException(generator, "No class found"));
clazz.setName(msg.getName() + "MessageMarshaller");
clazz.getImplementedTypes(0).setTypeArguments(NodeList.nodeList(new ClassOrInterfaceType(null, javaType)));
MethodDeclaration getJavaClassMethod = clazz.findFirst(MethodDeclaration.class, md -> md.getNameAsString().equals("getJavaClass")).orElseThrow(() -> new InvalidTemplateException(generator, "No getJavaClass method found"));
getJavaClassMethod.setType(new ClassOrInterfaceType(null, new SimpleName(Class.class.getName()), NodeList.nodeList(new ClassOrInterfaceType(null, javaType))));
BlockStmt getJavaClassMethodBody = new BlockStmt();
getJavaClassMethodBody.addStatement(new ReturnStmt(new NameExpr(javaType + ".class")));
getJavaClassMethod.setBody(getJavaClassMethodBody);
MethodDeclaration getTypeNameMethod = clazz.findFirst(MethodDeclaration.class, md -> md.getNameAsString().equals("getTypeName")).orElseThrow(() -> new InvalidTemplateException(generator, "No getTypeName method found"));
BlockStmt getTypeNameMethodBody = new BlockStmt();
getTypeNameMethodBody.addStatement(new ReturnStmt(new StringLiteralExpr(msg.getFullName())));
getTypeNameMethod.setBody(getTypeNameMethodBody);
MethodDeclaration readFromMethod = clazz.findFirst(MethodDeclaration.class, md -> md.getNameAsString().equals("readFrom")).orElseThrow(() -> new InvalidTemplateException(generator, "No readFrom method found"));
readFromMethod.setType(javaType);
readFromMethod.setBody(new BlockStmt());
MethodDeclaration writeToMethod = clazz.findFirst(MethodDeclaration.class, md -> md.getNameAsString().equals("writeTo")).orElseThrow(() -> new InvalidTemplateException(generator, "No writeTo method found"));
writeToMethod.getParameter(1).setType(javaType);
writeToMethod.setBody(new BlockStmt());
ClassOrInterfaceType classType = new ClassOrInterfaceType(null, javaType);
// read method
VariableDeclarationExpr instance = new VariableDeclarationExpr(new VariableDeclarator(classType, "value", new ObjectCreationExpr(null, classType, NodeList.nodeList())));
readFromMethod.getBody().ifPresent(b -> b.addStatement(instance));
for (FieldDescriptor field : msg.getFields()) {
String protoStreamMethodType = protoStreamMethodType(field.getTypeName());
Expression write = null;
Expression read = null;
if (protoStreamMethodType != null && !field.isRepeated()) {
// has a mapped type
read = new MethodCallExpr(new NameExpr("reader"), "read" + protoStreamMethodType).addArgument(new StringLiteralExpr(field.getName()));
String accessor = protoStreamMethodType.equals("Boolean") ? "is" : "get";
write = new MethodCallExpr(new NameExpr("writer"), "write" + protoStreamMethodType).addArgument(new StringLiteralExpr(field.getName())).addArgument(new MethodCallExpr(new NameExpr("t"), accessor + StringUtils.ucFirst(field.getName())));
} else {
// custom types
String customTypeName = javaTypeForMessage(d, field.getTypeName(), serializationContext);
if (field.isRepeated()) {
if (null == customTypeName || customTypeName.isEmpty()) {
customTypeName = primaryTypeClassName(field.getTypeName());
}
String writeMethod;
if (isArray(javaType, field)) {
writeMethod = "writeArray";
read = new MethodCallExpr(new NameExpr("reader"), "readArray").addArgument(new StringLiteralExpr(field.getName())).addArgument(new NameExpr(customTypeName + ".class"));
} else {
writeMethod = "writeCollection";
read = new MethodCallExpr(new NameExpr("reader"), "readCollection").addArgument(new StringLiteralExpr(field.getName())).addArgument(new ObjectCreationExpr(null, new ClassOrInterfaceType(null, ArrayList.class.getCanonicalName()), NodeList.nodeList())).addArgument(new NameExpr(customTypeName + ".class"));
}
write = new MethodCallExpr(new NameExpr("writer"), writeMethod).addArgument(new StringLiteralExpr(field.getName())).addArgument(new MethodCallExpr(new NameExpr("t"), "get" + StringUtils.ucFirst(field.getName()))).addArgument(new NameExpr(customTypeName + ".class"));
} else {
read = new MethodCallExpr(new NameExpr("reader"), "readObject").addArgument(new StringLiteralExpr(field.getName())).addArgument(new NameExpr(customTypeName + ".class"));
write = new MethodCallExpr(new NameExpr("writer"), "writeObject").addArgument(new StringLiteralExpr(field.getName())).addArgument(new MethodCallExpr(new NameExpr("t"), "get" + StringUtils.ucFirst(field.getName()))).addArgument(new NameExpr(customTypeName + ".class"));
}
if (customTypeName.equals(Serializable.class.getName())) {
String fieldClazz = (String) field.getOptionByName(KOGITO_JAVA_CLASS_OPTION);
if (fieldClazz == null) {
throw new IllegalArgumentException(format("Serializable proto field '%s' is missing value for option %s", field.getName(), KOGITO_JAVA_CLASS_OPTION));
} else {
read = new CastExpr().setExpression(new EnclosedExpr(read)).setType(fieldClazz);
}
}
}
MethodCallExpr setter = new MethodCallExpr(new NameExpr("value"), "set" + StringUtils.ucFirst(field.getName())).addArgument(read);
readFromMethod.getBody().ifPresent(b -> b.addStatement(setter));
// write method
writeToMethod.getBody().orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!")).addStatement(write);
}
readFromMethod.getBody().ifPresent(b -> b.addStatement(new ReturnStmt(new NameExpr("value"))));
clazz.getMembers().sort(new BodyDeclarationComparator());
}
for (EnumDescriptor msg : d.getEnumTypes()) {
CompilationUnit compilationUnit = new CompilationUnit();
units.add(compilationUnit);
String javaType = packageFromOption(d, msg) + "." + msg.getName();
ClassOrInterfaceDeclaration classDeclaration = compilationUnit.setPackageDeclaration(d.getPackage()).addClass(msg.getName() + "EnumMarshaller").setPublic(true);
classDeclaration.addImplementedType(EnumMarshaller.class).getImplementedTypes(0).setTypeArguments(NodeList.nodeList(new ClassOrInterfaceType(null, javaType)));
classDeclaration.addMethod("getTypeName", PUBLIC).setType(String.class).setBody(new BlockStmt().addStatement(new ReturnStmt(new StringLiteralExpr(msg.getFullName()))));
classDeclaration.addMethod("getJavaClass", PUBLIC).setType(new ClassOrInterfaceType(null, new SimpleName(Class.class.getName()), NodeList.nodeList(new ClassOrInterfaceType(null, javaType)))).setBody(new BlockStmt().addStatement(new ReturnStmt(new ClassExpr(new ClassOrInterfaceType(null, javaType)))));
BlockStmt encodeBlock = new BlockStmt().addStatement(new IfStmt(new BinaryExpr(new NullLiteralExpr(), new NameExpr(STATE_PARAM), EQUALS), new ThrowStmt(new ObjectCreationExpr(null, new ClassOrInterfaceType(null, IllegalArgumentException.class.getName()), NodeList.nodeList(new StringLiteralExpr("Invalid value provided to enum")))), null)).addStatement(new ReturnStmt(new MethodCallExpr(new NameExpr(STATE_PARAM), "ordinal")));
classDeclaration.addMethod("encode", PUBLIC).setType("int").addParameter(javaType, STATE_PARAM).setBody(encodeBlock);
MethodDeclaration decode = classDeclaration.addMethod("decode", PUBLIC).setType(javaType).addParameter("int", "value");
SwitchStmt decodeSwitch = new SwitchStmt().setSelector(new NameExpr("value"));
msg.getValues().forEach(v -> {
SwitchEntry dEntry = new SwitchEntry();
dEntry.getLabels().add(new IntegerLiteralExpr(v.getNumber()));
dEntry.addStatement(new ReturnStmt(new NameExpr(javaType + "." + v.getName())));
decodeSwitch.getEntries().add(dEntry);
});
decodeSwitch.getEntries().add(new SwitchEntry().addStatement(new ThrowStmt(new ObjectCreationExpr(null, new ClassOrInterfaceType(null, IllegalArgumentException.class.getName()), NodeList.nodeList(new StringLiteralExpr("Invalid value provided to enum"))))));
decode.setBody(new BlockStmt().addStatement(decodeSwitch));
}
}
return units;
}
use of org.infinispan.protostream.EnumMarshaller in project infinispan by infinispan.
the class QueryOperation method getNamedParameters.
private List<QueryRequest.NamedParameter> getNamedParameters() {
Map<String, Object> namedParameters = remoteQuery.getParameters();
if (namedParameters == null || namedParameters.isEmpty()) {
return null;
}
final SerializationContext serCtx = remoteQuery.getSerializationContext();
List<QueryRequest.NamedParameter> params = new ArrayList<>(namedParameters.size());
for (Map.Entry<String, Object> e : namedParameters.entrySet()) {
Object value = e.getValue();
// only if we're using protobuf, some simple types need conversion
if (serCtx != null) {
// todo [anistor] not the most elegant way of doing conversion
if (value instanceof Enum) {
EnumMarshaller encoder = (EnumMarshaller) serCtx.getMarshaller(value.getClass());
value = encoder.encode((Enum) value);
} else if (value instanceof Boolean) {
value = value.toString();
} else if (value instanceof Date) {
value = ((Date) value).getTime();
} else if (value instanceof Instant) {
value = ((Instant) value).toEpochMilli();
}
}
params.add(new QueryRequest.NamedParameter(e.getKey(), value));
}
return params;
}
use of org.infinispan.protostream.EnumMarshaller in project protostream by infinispan.
the class ImportedProtoTypeMetadata method getEnumMemberByName.
@Override
public ProtoEnumValueMetadata getEnumMemberByName(String name) {
if (!isEnum()) {
throw new IllegalStateException(getFullName() + " is not an enum");
}
EnumValueDescriptor evd = ((EnumDescriptor) descriptor).findValueByName(name);
if (evd == null) {
return null;
}
Enum<?> enumConstant = ((EnumMarshaller) marshaller).decode(evd.getNumber());
return new ProtoEnumValueMetadata(evd.getNumber(), name, enumConstant.ordinal(), enumConstant.getDeclaringClass().getCanonicalName() + '.' + enumConstant.name(), null);
}
use of org.infinispan.protostream.EnumMarshaller in project protostream by infinispan.
the class MarshallerByteCodeGenerator method generateEnumMarshaller.
/**
* Generates an implementation of EnumMarshaller as a static nested class in the Enum class to be marshalled. The
* InnerClasses attribute of the outer class is not altered, so this is not officially considered a nested class.
*/
private Class<EnumMarshaller> generateEnumMarshaller(ProtoEnumTypeMetadata petm) throws NotFoundException, CannotCompileException {
String marshallerClassName = makeUniqueMarshallerClassName();
CtClass annotatedClass = cp.get(petm.getAnnotatedClass().getName());
CtClass marshallerImpl = annotatedClass.makeNestedClass(marshallerClassName, true);
if (log.isTraceEnabled()) {
log.tracef("Generating enum marshaller %s for %s", marshallerImpl.getName(), petm.getJavaClass().getName());
}
marshallerImpl.addInterface(enumMarshallerInterface);
marshallerImpl.setModifiers(marshallerImpl.getModifiers() & ~Modifier.ABSTRACT | Modifier.FINAL);
marshallerImpl.addMethod(CtNewMethod.make("public final Class getJavaClass() { return " + petm.getJavaClassName() + ".class; }", marshallerImpl));
marshallerImpl.addMethod(CtNewMethod.make("public final String getTypeName() { return \"" + makeQualifiedTypeName(petm.getFullName()) + "\"; }", marshallerImpl));
CtMethod ctDecodeMethod = new CtMethod(decodeMethod, marshallerImpl, null);
ctDecodeMethod.setModifiers(ctDecodeMethod.getModifiers() | Modifier.FINAL);
String decodeSrc = generateEnumDecodeMethodBody(petm);
if (log.isTraceEnabled()) {
log.tracef("%s %s", ctDecodeMethod.getLongName(), decodeSrc);
}
ctDecodeMethod.setBody(decodeSrc);
marshallerImpl.addMethod(ctDecodeMethod);
CtMethod ctEncodeMethod = new CtMethod(encodeMethod, marshallerImpl, null);
ctEncodeMethod.setModifiers(ctEncodeMethod.getModifiers() | Modifier.FINAL);
String encodeSrc = generateEnumEncodeMethodBody(petm);
if (log.isTraceEnabled()) {
log.tracef("%s %s", ctEncodeMethod.getLongName(), encodeSrc);
}
ctEncodeMethod.setBody(encodeSrc);
marshallerImpl.addMethod(ctEncodeMethod);
Class<EnumMarshaller> generatedMarshallerClass = (Class<EnumMarshaller>) toClass(marshallerImpl, petm.getAnnotatedClass());
marshallerImpl.detach();
return generatedMarshallerClass;
}
Aggregations