should be enough to provide you with your own MessageBodyWriter for java.io.File that fires some events or notifies some listeners about the progress of the changes
@Provider() @Produces(MediaType.APPLICATION_OCTET_STREAM) public class MyFileProvider implements MessageBodyWriter<File> { public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return File.class.isAssignableFrom(type); } public void writeTo(File t, Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { InputStream in = new FileInputStream(t); try { int read; final byte[] data = new byte[ReaderWriter.BUFFER_SIZE]; while ((read = in.read(data)) != -1) { entityStream.write(data, 0, read);
and make your client application just use this new provider:
ClientConfig config = new DefaultClientConfig(); config.getClasses().add(MyFileProvider.class);
or
ClientConfig config = new DefaultClientConfig(); MyFileProvider myProvider = new MyFileProvider (); cc.getSingletons().add(myProvider);
You will also need to enable some algorithm to recognize which file is being transmitted when receiving progress events.
Edited by:
I just discovered that by default, HTTPUrlConnection uses buffering. And to disable buffering, you can do several things:
- httpUrlConnection.setChunkedStreamingMode (chunklength) - disables buffering and uses encoded transmission encoding to send a request
- httpUrlConnection.setFixedLengthStreamingMode (contentLength) - disables buffering, but has some restrictions for streaming: the exact number of bytes must be sent
So, I suggest that the final solution to your problem use the first option and look like this:
ClientConfig config = new DefaultClientConfig(); config.getClasses().add(MyFileProvider.class); URLConnectionClientHandler clientHandler = new URLConnectionClientHandler(new HttpURLConnectionFactory() { @Override public HttpURLConnection getHttpURLConnection(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setChunkedStreamingMode(1024); return connection; } }); Client client = new Client(clientHandler, config);
Tomasz Krzyżak
source share