final Handler<Message<JsonObject>> dbh = new Handler<Message<JsonObject>>() {
// how many messages have this handler received
int received = 0;
// keeps the received messages
JsonArray result = new JsonArray();
@Override
public void handle(Message<JsonObject> message) {
// increase the counter
received++;
// get the body
final JsonObject body = message.body();
if ("ok".equals(body.getString("status"))) {
// json -> string serialization
result.add(body.getObject("result"));
}
// end condition
if (received == count) {
request.response().end(result);
}
}
};
for (int i = 0; i < count; i++) {
eb.send(address, buildQuery("findone", "world", random.nextInt(10000) + 1), dbh);
}
}
})
// Test 4: fortune
.use("/fortunes", new Middleware() {
@Override
public void handle(final YokeRequest request, final Handler<Object> next) {
final List<JsonObject> results = new ArrayList<>();
eb.send(address, buildQuery("find", "fortune"), new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> reply) {
String status = reply.body().getString("status");
if (status != null) {
if ("ok".equalsIgnoreCase(status)) {
JsonArray itResult = reply.body().getArray("results");
for (Object o : itResult) {
results.add((JsonObject) o);
}
// end condition
results.add(new JsonObject().putNumber("id", 0).putString("message", "Additional fortune added at request time."));
// sort ASC
Collections.sort(results, new Comparator<JsonObject>() {
@Override
public int compare(JsonObject o1, JsonObject o2) {
return o1.getNumber("id").intValue() - o2.getNumber("id").intValue();
}
});
// render
request.put("fortunes", results);
request.response().render("fortunes.mvel", next);
return;
}
if ("more-exist".equalsIgnoreCase(status)) {
JsonArray itResult = reply.body().getArray("results");
for (Object o : itResult) {
results.add((JsonObject) o);
}
// reply asking for more
reply.reply(this);
return;
}
}
next.handle("error");
}
});
}
})
// Test 5: updates
.use("/updates", new Middleware() {
@Override
public void handle(final YokeRequest request, final Handler<Object> next) {
final Random random = ThreadLocalRandom.current();
// Get the count of queries to run.
final int count = parseRequestParam(request, "queries");
final Handler<Message<JsonObject>> dbh = new Handler<Message<JsonObject>>() {
// how many messages have this handler received
int received = 0;
// keeps the received messages
JsonArray worlds = new JsonArray();
@Override
public void handle(Message<JsonObject> message) {
// get the body
final JsonObject body = message.body();
JsonObject world;
if ("ok".equals(body.getString("status"))) {
world = new JsonObject()
.putNumber("id", received)
.putNumber("randomNumber", body.getObject("result").getNumber("randomNumber"));
worlds.add(world);
world.putNumber("randomNumber", random.nextInt(10000) + 1);
eb.send(address, buildUpdate("world", world.getInteger("id"), world.getInteger("randomNumber")));
}