Examples and tests incorrectly use ByteBuffer.array()

Description

For example, when reading a stream event, sample apps do:

String eventBody = new String(event.getBody().array());

This is incorrect, because it ignores the offset and limit of the byte buffer within its underlying array. This also does not specify any encoding and is therefore susceptible to failure based on the system encoding. Better assure it is UTF8.

Instead, it should be

String eventBody = new String(event.getBody().array(), event.getBody().arrayOffset(), event.getBody().limit(), "UTF-8");

We should add a utility method to common.Bytes and use that everywhere.

Release Notes

None

Activity

Show:

Alex Baranau November 11, 2014 at 7:37 AM

I think it is great addition to Bytes - it can be used in many places. At same time - it may makes sense to have in StreamEvent too - as it will make it much more straightforward (better experience) for developer. IDE autocomplete helps here..

Andreas Neumann November 11, 2014 at 7:05 AM

yes, that is better. I added (in CDAP) a Bytes.toString(ByteBuffer bb) method that does exactly that. Should it be a convenience method of StreamEvent? Perhaps... but is that necessary with the utility in Bytes?

Alex Baranau November 11, 2014 at 1:03 AM

should it be simply

String eventBody = Charsets.UTF_8.decode(event.getBody()).toString();

?

Also, I believe it should be a convenience method of StreamEvent: https://issues.cask.co/browse/CDAP-92

Fixed
Pinned fields
Click on the next to a field label to start pinning.

Details

Assignee

Reporter

Affects versions

Fix versions

Priority

Created November 6, 2014 at 1:52 AM
Updated March 27, 2015 at 7:31 PM
Resolved November 19, 2014 at 1:34 AM