Refactoring of WebdavClient creation and setup
[pub/Android/ownCloud.git] / src / eu / alefzero / webdav / FileRequestEntity.java
1 package eu.alefzero.webdav;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8
9 import org.apache.commons.httpclient.methods.RequestEntity;
10
11 import eu.alefzero.webdav.OnDatatransferProgressListener;
12
13 import android.util.Log;
14
15
16 /**
17 * A RequestEntity that represents a File.
18 *
19 */
20 public class FileRequestEntity implements RequestEntity {
21
22 final File file;
23 final String contentType;
24 OnDatatransferProgressListener listener;
25
26 public FileRequestEntity(final File file, final String contentType) {
27 super();
28 if (file == null) {
29 throw new IllegalArgumentException("File may not be null");
30 }
31 this.file = file;
32 this.contentType = contentType;
33 }
34
35 public long getContentLength() {
36 return this.file.length();
37 }
38
39 public String getContentType() {
40 return this.contentType;
41 }
42
43 public boolean isRepeatable() {
44 return true;
45 }
46
47 public void setOnDatatransferProgressListener(OnDatatransferProgressListener listener) {
48 this.listener = listener;
49 }
50
51 public void writeRequest(final OutputStream out) throws IOException {
52 byte[] tmp = new byte[4096];
53 int i = 0;
54 InputStream instream = new FileInputStream(this.file);
55 try {
56 while ((i = instream.read(tmp)) >= 0) {
57 out.write(tmp, 0, i);
58 if (listener != null)
59 listener.transferProgress(i);
60 }
61 } catch (IOException io) {
62 Log.e("FileRequestException", io.getMessage());
63 throw new RuntimeException("Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io);
64
65 } finally {
66 instream.close();
67 }
68 }
69
70 }