remove all warning from project
[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 mFile;
25 final String mContentType;
26 OnDatatransferProgressListener mListener;
27
28 public FileRequestEntity(final File file, final String contentType) {
29 super();
30 this.mFile = file;
31 this.mContentType = contentType;
32 if (file == null) {
33 throw new IllegalArgumentException("File may not be null");
34 }
35 }
36
37 @Override
38 public long getContentLength() {
39 return mFile.length();
40 }
41
42 @Override
43 public String getContentType() {
44 return mContentType;
45 }
46
47 @Override
48 public boolean isRepeatable() {
49 return true;
50 }
51
52 public void setOnDatatransferProgressListener(OnDatatransferProgressListener listener) {
53 mListener = listener;
54 }
55
56 @Override
57 public void writeRequest(final OutputStream out) throws IOException {
58 //byte[] tmp = new byte[4096];
59 ByteBuffer tmp = ByteBuffer.allocate(4096);
60 int i = 0;
61
62 // TODO(bprzybylski): each mem allocation can throw OutOfMemoryError we need to handle it
63 // globally in some fashionable manner
64 RandomAccessFile raf = new RandomAccessFile(mFile, "rw");
65 FileChannel channel = raf.getChannel();
66 FileLock lock = channel.tryLock();
67 //InputStream instream = new FileInputStream(this.file);
68
69 try {
70 //while ((i = instream.read(tmp)) >= 0) {
71 while ((i = channel.read(tmp)) >= 0) {
72 out.write(tmp.array(), 0, i);
73 tmp.clear();
74 if (mListener != null)
75 mListener.transferProgress(i);
76 }
77 } catch (IOException io) {
78 Log.e("FileRequestException", io.getMessage());
79 throw new RuntimeException("Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io);
80
81 } finally {
82 //instream.close();
83 lock.release();
84 channel.close();
85 raf.close();
86 }
87 }
88
89 }