Monday, August 15, 2011

Working with Google Protobuf DynamicMessage

Google Protobuf is an stand out project with mixed quality documentation. A corporate cynic points working with DynamicMessage, an interesting Protobuf feature lacking official documentation beyond skeletal javadoc and a short blurb.

The key trick condenses down to:

public static Descriptor descriptorFor(
        final InputStream in, final String name)
        throws IOException, DescriptorValidationException {
    final FileDescriptorSet fileDescriptorSet
            = FileDescriptorSet.parseFrom(in);
    final FileDescriptorProto fileDescriptorProto
            = fileDescriptorSet.getFile(0);
    final FileDescriptor fileDescriptor = FileDescriptor.
            buildFrom(fileDescriptorProto, new FileDescriptor[0]);
    return fileDescriptor.findMessageTypeByName(name);

// Elsewhere

final InputStream in = Class.class.
        getResourceAsStream("... your descriptors from protoc ...");
final Descriptor descriptor = descriptorFor(in,
final DynamicMessage dynamicMessage = DynamicMessage.
        parseFrom(descriptor, outer.toByteArray());
System.out.println("dynamicMessage = " + dynamicMessage);

Note the baked-in assumption of "getFile(0)", etc. The cynic's example is more forthcoming. Caveat coder.

No comments: