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
|
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.http.server;
import com.yahoo.container.jdisc.HttpResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.BlockingQueue;
/**
* Reads feed responses from a queue and renders them continuously to the
* feeder.
*
* @author Steinar Knutsen
*/
public class FeedResponse extends HttpResponse {
BlockingQueue<OperationStatus> operations;
public FeedResponse(
int status,
BlockingQueue<OperationStatus> operations,
int protocolVersion,
String sessionId) {
super(status);
this.operations = operations;
headers().add(Headers.SESSION_ID, sessionId);
headers().add(Headers.VERSION, Integer.toString(protocolVersion));
}
// This is used by the V3 protocol.
public FeedResponse(
int status,
BlockingQueue<OperationStatus> operations,
int protocolVersion,
String sessionId,
int outstandingClientOperations,
String hostName) {
super(status);
this.operations = operations;
headers().add(Headers.SESSION_ID, sessionId);
headers().add(Headers.VERSION, Integer.toString(protocolVersion));
headers().add(Headers.OUTSTANDING_REQUESTS, Integer.toString(outstandingClientOperations));
headers().add(Headers.HOSTNAME, hostName);
}
@Override
public void render(OutputStream output) throws IOException {
int i = 0;
OperationStatus status;
try {
status = operations.take();
while (status.errorCode != ErrorCode.END_OF_FEED) {
output.write(toBytes(status.render()));
if (++i % 5 == 0) {
output.flush();
}
status = operations.take();
}
} catch (InterruptedException e) {
output.flush();
}
}
private byte[] toBytes(String s) {
byte[] b = new byte[s.length()];
for (int i = 0; i < b.length; ++i) {
b[i] = (byte) s.charAt(i); // renderSingleStatus ensures ASCII only
}
return b;
}
@Override
public String getContentType() {
return "text/plain";
}
@Override
public String getCharacterEncoding() {
return StandardCharsets.US_ASCII.name();
}
}
|