use of org.infinispan.protostream.BaseMarshaller in project protostream by infinispan.
the class SerializationContextImplTest method testMarshallerProvider.
@Test
public void testMarshallerProvider() throws Exception {
SerializationContext ctx = createContext();
String file = "package test;\n" + "message X {\n" + " optional int32 f = 1;\n" + "}";
class X {
Integer f;
private X(Integer f) {
this.f = f;
}
}
FileDescriptorSource fileDescriptorSource = new FileDescriptorSource().addProtoFile("file.proto", file);
ctx.registerProtoFiles(fileDescriptorSource);
ctx.registerMarshallerProvider(new SerializationContext.MarshallerProvider() {
@Override
public BaseMarshaller<?> getMarshaller(String typeName) {
if (typeName.equals("test.X")) {
return makeMarshaller();
}
return null;
}
@Override
public BaseMarshaller<?> getMarshaller(Class<?> javaClass) {
if (javaClass == X.class) {
return makeMarshaller();
}
return null;
}
private BaseMarshaller<?> makeMarshaller() {
return new ProtobufTagMarshaller<X>() {
@Override
public X read(ReadContext ctx) throws IOException {
Integer f = null;
TagReader in = ctx.getReader();
if (in.readTag() == WireType.makeTag(1, WireType.WIRETYPE_VARINT)) {
f = in.readInt32();
}
return new X(f);
}
@Override
public void write(WriteContext ctx, X x) throws IOException {
ctx.getWriter().writeInt32(1, x.f);
}
@Override
public Class<X> getJavaClass() {
return X.class;
}
@Override
public String getTypeName() {
return "test.X";
}
};
}
});
byte[] bytes = ProtobufUtil.toWrappedByteArray(ctx, new X(1234));
Object out = ProtobufUtil.fromWrappedByteArray(ctx, bytes);
assertTrue(out instanceof X);
assertNotNull(((X) out).f);
assertEquals(1234, ((X) out).f.intValue());
}
Aggregations