/** * Converts generic byte[] to text. * * @param source byte[] to convert. * @param destination MediaType of the desired text conversion. * @return byte[] content interpreted as text, in the encoding specified by the destination MediaType. */ public static byte[] convertOctetStreamToText(byte[] source, MediaType destination) { if (source == null) return null; return convertCharset(source, UTF_8, destination.getCharset()); }
/** * Converts a java object to a text/plain representation. * @param source Object to convert. * @param sourceMediaType The MediaType for the source object. * @param destinationMediaType The required text/plain specification. * @return byte[] with the text/plain representation of the object with the requested charset. */ public static byte[] convertJavaToText(Object source, MediaType sourceMediaType, MediaType destinationMediaType) { if (source == null) return null; if (sourceMediaType == null || destinationMediaType == null) { throw new NullPointerException("sourceMediaType and destinationMediaType cannot be null!"); } Object decoded = decodeObjectContent(source, sourceMediaType); if (decoded instanceof byte[]) { return convertCharset(source, StandardCharsets.UTF_8, destinationMediaType.getCharset()); } else { String asString = decoded.toString(); return asString.getBytes(destinationMediaType.getCharset()); } }
/** * Convert text content to a different encoding. * * @param source The source content. * @param sourceType MediaType for the source content. * @param destinationType the MediaType of the converted content. * @return content conforming to the destination MediaType. */ public static Object convertTextToText(Object source, MediaType sourceType, MediaType destinationType) { if (source == null) return null; if (sourceType == null) throw new NullPointerException("MediaType cannot be null!"); if (!sourceType.match(MediaType.TEXT_PLAIN)) throw log.invalidMediaType(TEXT_PLAIN_TYPE, sourceType.toString()); boolean asString = destinationType.hasStringType(); Charset sourceCharset = sourceType.getCharset(); Charset destinationCharset = destinationType.getCharset(); if (sourceCharset.equals(destinationCharset)) return convertTextClass(source, destinationType, asString); byte[] byteContent = source instanceof byte[] ? (byte[]) source : source.toString().getBytes(sourceCharset); return convertTextClass(convertCharset(byteContent, sourceCharset, destinationCharset), destinationType, asString); }
byte[] contentKorean = convertCharset(contentUTF, UTF_8, korean);