8ebdcbe25207dd6e81dd634d5e35630e37bf7080
[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.IOException;
5 import java.io.OutputStream;
6 import java.io.RandomAccessFile;
7 import java.nio.ByteBuffer;
8 import java.nio.channels.FileChannel;
9 import java.nio.channels.FileLock;
10
11 import org.apache.commons.httpclient.methods.RequestEntity;
12
13 import eu.alefzero.webdav.OnDatatransferProgressListener;
14
15 import android.util.Log;
16
17
18 /**
19 * A RequestEntity that represents a File.
20 *
21 */
22 public class FileRequestEntity implements RequestEntity {
23
24 final File file;
25 final String contentType;
26 OnDatatransferProgressListener listener;
27
28 public FileRequestEntity(final File file, final String contentType) {
29 super();
30 if (file == null) {
31 throw new IllegalArgumentException("File may not be null");
32 }
33 this.file = file;
34 this.contentType = contentType;
35 }
36
37 public long getContentLength() {
38 return this.file.length();
39 }
40
41 public String getContentType() {
42 return this.contentType;
43 }
44
45 public boolean isRepeatable() {
46 return true;
47 }
48
49 public void setOnDatatransferProgressListener(OnDatatransferProgressListener listener) {
50 this.listener = listener;
51 }
52
53 public void writeRequest(final OutputStream out) throws IOException {
54 //byte[] tmp = new byte[4096];
55 ByteBuffer tmp = ByteBuffer.allocate(4096);
56 int i = 0;
57
58 FileChannel channel = new RandomAccessFile(this.file, "rw").getChannel();
59 FileLock lock = channel.tryLock();
60 //InputStream instream = new FileInputStream(this.file);
61
62 try {
63 //while ((i = instream.read(tmp)) >= 0) {
64 while ((i = channel.read(tmp)) >= 0) {
65 out.write(tmp.array(), 0, i);
66 tmp.clear();
67 if (listener != null)
68 listener.transferProgress(i);
69 }
70 } catch (IOException io) {
71 Log.e("FileRequestException", io.getMessage());
72 throw new RuntimeException("Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io);
73
74 } finally {
75 //instream.close();
76 lock.release();
77 channel.close();
78 }
79 }
80
81 }