code: public static byte[] asByteArray(ByteBuffer buf) {
          byte[] result;
          if (buf.hasArray() && buf.arrayOffset() == 0 && buf.capacity() == buf.remaining()) {
              result = buf.array();
          }
          else {
              result = new byte[buf.remaining()];
              if (buf.hasArray()) {
                  System.arraycopy(buf.array(), buf.arrayOffset() + buf.position(), result, 0, result.length);
              }
              else {
                  // Direct buffer
                  ByteBuffer duplicate = buf.duplicate();
                  duplicate.mark();
                  duplicate.get(result);
                  duplicate.reset();
              }
          }
          return result;
      }
docs: Gets the content of the ByteBuffer as a byte[] without mutating the buffer
  (so thread safe) and minimizing GC (i.e. object creation)