@Provider @Produces(SerializableProvider.MIMETYPE) @Consumes(SerializableProvider.MIMETYPE) public class SerializableProvider implements MessageBodyReader, MessageBodyWriter { /** Marshaller for Java serialized objects */ public final static String MIMETYPE = "application/x-java-serialized-object"; /** Corresponding MediaType */ public final static MediaType MEDIATYPE = new MediaType("application", "x-java-serialized-object"); @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return Serializable.class.isAssignableFrom(type) && MEDIATYPE.isCompatible(mediaType); } @Override public long getSize(Serializable t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public void writeTo(Serializable t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { BufferedOutputStream bos = new BufferedOutputStream(entityStream); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(t); oos.close(); } @Override public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return Serializable.class.isAssignableFrom(type) && MEDIATYPE.isCompatible(mediaType); } @Override public Serializable readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { BufferedInputStream bis = new BufferedInputStream(entityStream); ObjectInputStream ois = new ObjectInputStream(bis); try { return Serializable.class.cast(ois.readObject()); } catch (ClassNotFoundException e) { throw new WebApplicationException(e); } } }