mangusbrother
mangusbrother

Reputation: 4156

RabbitMQ in Java using Protobuf. Parse received data

I am currently using springAMQP to communicate between java and my RabbitMQ node. I am sending Protobuf data.

I would like to convert/cast/parse the received Message into the respective ProtoClass.

Here is the snippet from my Converter:

@Override
protected Message createMessage(Object object, MessageProperties messageProperties) {
    Preconditions.checkNotNull(object, "Object to send is null !");

    if (!com.google.protobuf.Message.class.isAssignableFrom(object.getClass())) {
        throw new MessageConversionException("Message wasn't a protobuf");
    } else {
        com.google.protobuf.Message protobuf = (com.google.protobuf.Message) object;
        byte[] byteArray = protobuf.toByteArray();

        messageProperties.setContentLength(byteArray.length);
        messageProperties.setContentType(ProtobufMessageConverter.CONTENT_TYPE_PROTOBUF);
        messageProperties.setHeader(ProtobufMessageConverter.MESSAGE_TYPE_NAME, protobuf.getDescriptorForType().getName());

        return new Message(byteArray, messageProperties);
    }
}

@Override
public Object fromMessage(Message message) throws MessageConversionException {

    com.google.protobuf.Message parsedMessage = null;
    try {
        if(ProtobufMessageConverter.CONTENT_TYPE_PROTOBUF.equals(message.getMessageProperties().getContentType())) {
            String typeName = getMessageTypeName(message);
            Descriptors.Descriptor messageType = fileDescriptor.findMessageTypeByName(typeName);
            parsedMessage = DynamicMessage.parseFrom(messageType, message.getBody());
        }
    } catch (Exception e) {
        throw new AmqpRejectAndDontRequeueException("Cannot convert, unknown message type %s".format(getMessageTypeName(message)));
    }
    return parsedMessage;
}

What do I have to do to be able to build the object?

Here is my proto file:

message queueReply {
    required string identifier = 1; cycle
    required uint32 keyId = 2;
    required bool success = 3; 
    required bytes result = 4; 
}

I would like to obtain the class queueReply from template.receiveAndConvert()

Upvotes: 4

Views: 5604

Answers (1)

mangusbrother
mangusbrother

Reputation: 4156

Found the solution.

DynamicMessage o = (DynamicMessage)template.receiveAndConvert("queueName");
ProtoObject request = ProtoObject.parseFrom(o.toByteArray()); 

Upvotes: 4

Related Questions