code: public static byte[] toByteArray(ByteBuffer buffer) {
          if (buffer.hasArray() && buffer.arrayOffset() == 0
                  && buffer.position() == 0 && buffer.limit() == buffer.capacity()
                  && buffer.array().length == buffer.capacity()) {
              final byte[] array = buffer.array();
              return array;
          }
  
          final int p = buffer.position();
          final byte[] array = new byte[buffer.remaining()];
          buffer.get(array);
          buffer.position(p);
          return array;
      }
docs: Returns an array containing a {@link ByteBuffer}'s {@link ByteBuffer#remaining() remaining} contents. <br> Upon returning
  from this method, the buffer's {@link ByteBuffer#position() position} will remain unchanged.
  
  @param buffer The buffer to write into the array.
  @return A newly allocated array of size {@link ByteBuffer#remaining() buffer.remaining()} containing the buffer's contents.