Search code examples
javac++thrift

Java Thrift Client and Binary data


So by my understanding for thrift, Java is the only language supported that does not have binary-safe Strings, hence the thrift binary type. My problem is it doesn't seem to work.

My definition File is:

service myService {
     int myMethod(1:binary input)
}

My Java client builds a ByteBuffer from binary data that is observed to have positive length, and printable bytes prior to calling myMethod.

Immediately inside the C++ implementation of myMethod (from the thrift generated server skeleton), attempts to print input show it as always being empty of size 0.

Any ideas what I'm missing here? Changing binary to string makes everything work like a charm, minus the fact that I don't want the unsafe java-converted string to deal with later...


Solution

  • Most likely you're having problem because ByteBuffer in Java has mutable state. So, any read operation actually modifies ByteBuffer, since it modifies read position.

    The simpliest (whereas not the most effective) way to work with thrift binaries in java is creating binaries as byte arrays and using wrapping them info buffers immidiately before invocation, i.e.:

    byte[] input = ....;
    myService.myMethod(ByteBuffer.wrap(input));
    

    Another possible solution is to use ByteBuffer.duplicate to keep original buffer safe, i.e.:

    ByteBuffer input = ....;
    dump(input.duplicate());// dump function may change buffer position
    myService.myMethod(input);