code: public static byte[] bufferToArray(ByteBuffer buffer) {
      if (buffer.hasArray() && buffer.arrayOffset() == 0 &&
          buffer.array().length == buffer.remaining()) {
        return buffer.array();
      } else {
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        return bytes;
      }
    }
docs: Returns a byte array with the buffer's contents, trying to avoid copying the data if
  possible.