/** * 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()); } }
/** * Converts a java object to a sequence of bytes applying standard java serialization. * * @param source source the java object to convert. * @param sourceMediaType the MediaType matching application/x-application-object describing the source. * @return byte[] representation of the java object. * @throws EncodingException if the sourceMediaType is not a application/x-java-object or if the conversion is * not supported. */ public static byte[] convertJavaToOctetStream(Object source, MediaType sourceMediaType, Marshaller marshaller) throws IOException, InterruptedException { if (source == null) return null; if (!sourceMediaType.match(MediaType.APPLICATION_OBJECT)) { throw new EncodingException("destination MediaType not conforming to application/x-java-object!"); } Object decoded = decodeObjectContent(source, sourceMediaType); if (decoded instanceof byte[]) return (byte[]) decoded; if (decoded instanceof String && isJavaString(sourceMediaType)) return ((String) decoded).getBytes(StandardCharsets.UTF_8); return marshaller.objectToByteBuffer(source); }
private Object convertToObject(Object content, MediaType contentType, MediaType destinationType) { if (contentType.match(APPLICATION_OCTET_STREAM)) { byte[] decoded = StandardConversions.decodeOctetStream(content, destinationType); return StandardConversions.convertOctetStreamToJava(decoded, destinationType, javaMarshaller); } if (contentType.match(APPLICATION_OBJECT)) { return StandardConversions.decodeObjectContent(content, contentType); } if (contentType.match(TEXT_PLAIN)) { return StandardConversions.convertTextToObject(content, contentType); } if (contentType.match(APPLICATION_WWW_FORM_URLENCODED)) { return StandardConversions.convertUrlEncodedToObject(content); } if (contentType.equals(MediaType.APPLICATION_UNKNOWN)) { if (content instanceof byte[]) { return tryDeserialize((byte[]) content); } if (content instanceof WrappedByteArray) { return tryDeserialize(((WrappedByteArray) content).getBytes()); } return content; } throw log.unsupportedContent(content); }