Oliver Yasuna
unread,Nov 10, 2023, 11:47:35 AM11/10/23Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Protocol Buffers
I am having trouble de-serializing a protobuf. I am confident that it is serialized properly, as serialization works in all other cases.
Here's a simplified proto file:
```proto3
syntax = "proto3";
message Request {
oneof request {
LoginRequest login = 1;
SyncRequest sync = 2;
PushRequest push = 3;
}
}
message LoginRequest {
string username = 1;
string password = 2;
}
message SyncRequest {
}
message PushRequest {
message Item {
int64 id = 1;
string value = 2;
string date = 3;
}
repeated Item items = 1;
}
```
I read and de-serialize the protobuf in the `doPost` method of an `HttpServlet`:
```java
@Override
protected void doPost(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) throws ServletException, IOException {
final BufferedReader reader = httpRequest.getReader();
final byte[] buffer = IOUtils.toByteArray(reader, StandardCharsets.UTF_8);
final Request request;
try {
// TODO: Read from input stream directly.
request = Request.parseFrom(buffer);
} catch(final Exception e) {
throw new ServletException("Failed to deserialize request body.", e);
}
// Never reaches this line.
// ...
}
```
I get the following error:
```
11:44:23.199 [qtp1165303897-24] WARN o.e.j.ee10.servlet.ServletChannel - handleException /api com.google.protobuf.InvalidProtocolBufferException: While parsing a protocol message, the input ended unexpectedly in the middle of a field. This could mean either that the input has been truncated or that an embedded message misreported its own length.
```
If I sent `Request.login` or `Request.sync`, it successfully de-serializes. The error only occurs for `Request.push`.