blob: 15cc4f49611ff9d0c895a3b7c5a8018c011ed97b (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
|
package com.koushikdutta.async;
import com.koushikdutta.async.callback.CompletedCallback;
import com.koushikdutta.async.callback.DataCallback;
import com.koushikdutta.async.util.StreamUtility;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* Created by koush on 5/22/13.
*/
public class FileDataEmitter extends DataEmitterBase {
AsyncServer server;
File file;
public FileDataEmitter(AsyncServer server, File file) {
this.server = server;
this.file = file;
paused = !server.isAffinityThread();
if (!paused)
doResume();
}
DataCallback callback;
@Override
public void setDataCallback(DataCallback callback) {
this.callback = callback;
}
@Override
public DataCallback getDataCallback() {
return callback;
}
@Override
public boolean isChunked() {
return false;
}
boolean paused;
@Override
public void pause() {
paused = true;
}
@Override
public void resume() {
paused = false;
doResume();
}
@Override
protected void report(Exception e) {
StreamUtility.closeQuietly(channel);
super.report(e);
}
ByteBufferList pending = new ByteBufferList();
FileChannel channel;
Runnable pumper = new Runnable() {
@Override
public void run() {
try {
if (channel == null)
channel = new FileInputStream(file).getChannel();
if (!pending.isEmpty()) {
Util.emitAllData(FileDataEmitter.this, pending);
if (!pending.isEmpty())
return;
}
ByteBuffer b;
do {
b = ByteBufferList.obtain(8192);
if (-1 == channel.read(b)) {
report(null);
return;
}
b.flip();
pending.add(b);
Util.emitAllData(FileDataEmitter.this, pending);
}
while (pending.remaining() == 0 && !isPaused());
}
catch (Exception e) {
report(e);
}
}
};
private void doResume() {
server.post(pumper);
}
@Override
public boolean isPaused() {
return paused;
}
@Override
public AsyncServer getServer() {
return server;
}
@Override
public void close() {
try {
channel.close();
}
catch (Exception e) {
}
}
}
|