/** * Ensures that either the UTF-8 text has been set directly or by indirectly converting the Map contents to JSON. */ private void ensureTextSet() { if (_text.limit() == 0) { checkState(_map != null, "Neither JSON text nor map has been set"); _text.clear(); // First try reading the JSON directly into be buffer. try { JsonHelper.writeJson(new ByteBufferOutputStream(_text), _map); // Set the limit and move the position back to zero. _text.flip(); } catch (Exception e) { if (Iterables.tryFind(Throwables.getCausalChain(e), Predicates.instanceOf(BufferOverflowException.class)).isPresent()) { // Buffer was insufficient. Allocate a new array and read the bytes into it. byte[] utf8 = JsonHelper.asUtf8Bytes(_map); _text = ByteBuffer.wrap(utf8); } else { throw Throwables.propagate(e); } } } }