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