forked from chanjarster/web-async-learn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AsyncWriteServlet.java
78 lines (62 loc) · 2.24 KB
/
AsyncWriteServlet.java
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
package me.chanjar.learning;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
@WebServlet(value = "/async-write", asyncSupported = true)
public class AsyncWriteServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Servlet thread: " + Thread.currentThread().getName());
AsyncContext asyncCtx = req.startAsync();
ServletOutputStream os = resp.getOutputStream();
InputStream bigfileInputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("bigfile");
os.setWriteListener(new WriteListener() {
@Override
public void onWritePossible() throws IOException {
int writeBytes = 0;
System.out.println("WriteListener thread: " + Thread.currentThread().getName());
while (os.isReady()) {
byte[] bytes = new byte[1024];
int readBytes = readContent(bytes);
if (readBytes > 0) {
os.write(bytes);
writeBytes += readBytes;
} else {
closeInputStream();
asyncCtx.complete();
break;
}
}
System.out.println("Write bytes: " + writeBytes);
}
@Override
public void onError(Throwable t) {
try {
os.print("Error happened");
os.print(ExceptionUtils.getStackTrace(t));
} catch (IOException e) {
e.printStackTrace();
} finally {
closeInputStream();
asyncCtx.complete();
}
}
private int readContent(byte[] buffer) throws IOException {
int readLength = IOUtils.read(bigfileInputStream, buffer);
return readLength;
}
private void closeInputStream() {
IOUtils.closeQuietly(bigfileInputStream);
}
});
}
}