@Override
public void onResponse(IndexResponse response) {
try {
XContentBuilder builder = restContentBuilder(request);
builder.startObject().field("ok", true).field("id", response.getId()).endObject();
channel.sendResponse(new XContentRestResponse(request, OK, builder));
} catch (Exception e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
logger.error("Error processing publish request", e);
channel.sendResponse(new XContentThrowableRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
// push phase - scroll over subscribers for this topic currently connected
QueryBuilder queryBuilder = termQuery("topic", topic);
SearchResponse searchResponse = client.prepareSearch()
.setIndices(pubSubIndexName)
.setTypes("subscribe")
.setSearchType(SearchType.SCAN)
.setScroll(new TimeValue(60000))
.setQuery(queryBuilder)
.addField("subscriber.channel")
.setSize(100)
.execute().actionGet();
messageBuilder.close();
service.checkpoint(topic);
// push phase - write the message to the subscribers. We have 60 seconds per 100 subscribers.
while (true) {
searchResponse = client.prepareSearchScroll(searchResponse.getScrollId())
.setScroll(new TimeValue(60000))
.execute().actionGet();
for (SearchHit hit : searchResponse.getHits()) {
service.checkpoint(hit.getId());
SearchHitField channelField = hit.field("subscriber.channel");
Map<String, Object> channelfieldMap = channelField.getValue();
Integer id = (Integer) channelfieldMap.get("id");
Channel ch = transport.channel(id);
if (ch != null) {
ch.write(new NettyInteractiveResponse("message", messageBuilder).response());
}
}
if (searchResponse.getHits().hits().length == 0) {
break;
}
}
service.flushCheckpoint();
} catch (Exception e) {
try {
XContentBuilder builder = restContentBuilder(request);
channel.sendResponse(new XContentRestResponse(request, BAD_REQUEST, builder.startObject().field("error", e.getMessage()).endObject()));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
}