code: public static String toUtf8StringOrHex(ByteArrayOutputStream byteStream, int maxLen) {
          if (maxLen == -1) {
              maxLen = Integer.MAX_VALUE;
          }
  
          String result;
          try {
              result = byteStream.toString("UTF-8");
          } catch (Exception notUtf8) {
              result = Hex.encodeHexString(byteStream.toByteArray());
          }
  
          final int resultLen = result != null ? result.length() : 0;
          final String suffix = resultLen > maxLen ? "..." : "";
          return resultLen == 0 ? "" : result.substring(0, Math.min(resultLen, maxLen)) + suffix;
      }
docs: generate a String of UTF-8 characters (or hex-digits if byteStream isn't UTF-8 chars) from byteStream,
  truncating to maxLen (with "..." added if the result is truncated)
  @param byteStream the source of bytes to be converted to a UTF-8 String
  @param maxLen     the point at which to truncate the string (-1 means don't truncate) in which case "..." is appended
  @return the String read from the stream