Protocol buffer failed to parse single codeInputStream having multiple large size of message

Here is the message schema:>

message ServerResponse {
optional string ReferenceCode = 1;
optional NestedMessageProto.NestedMessage NestedMessage = 2;//Huge size data in response
optional bool Success = 3 [default = false];
repeated Errors Errors = 4;
}

Below is code for getting the response from serve and calling the proto response method.

 String apiResponse = Server Response
    protoResponseClass.parseFrom(apiResponse.getBytes())

its failing when reading the NestedMessage  response on below bold line

    public int pushLimit(int byteLimit) throws InvalidProtocolBufferException {
    if (byteLimit < 0) {
        throw InvalidProtocolBufferException.negativeSize();
    }
    byteLimit += totalBytesRetired + bufferPos;
    if (byteLimit > currentLimit) {
        currentLimit = byteLimit + currentLimit;
    }
    final int oldLimit = currentLimit;
    **if (byteLimit > oldLimit) {
        throw InvalidProtocolBufferException.truncatedMessage();
    }**
    currentLimit = byteLimit;
    recomputeBufferSizeAfterLimit();
    return oldLimit;
}

When its reading nested message the byte limit becoming greater than old limit. What could be the solution?

Thanks

Jon Skeet
people
quotationmark

This is almost certainly the problem:

String apiResponse = Server Response
protoResponseClass.parseFrom(apiResponse.getBytes())

Protocol buffer messages are binary data. They're not text, and shouldn't be handled as text. You're taking the binary response from the server, interpreting it as text in some way (we can't tell how), then converting it back to a byte array using the platform default encoding (which is almost always a bad idea - never call getBytes() without specifying a charset, even when calling getBytes() is appropriate, which it's not here). The conversion to text and back is almost certainly losing information - quite possibly making the parsing code expect more data than is actually present in the message.

You should be handling the server response as binary data from the start - ideally just passing an InputStream from the server response into parseFrom, but at least reading it as a byte array instead of a String.

people

See more on this question at Stackoverflow