Example usage for io.vertx.core.eventbus Message reply

List of usage examples for io.vertx.core.eventbus Message reply

Introduction

In this page you can find the example usage for io.vertx.core.eventbus Message reply.

Prototype

default void reply(@Nullable Object message) 

Source Link

Document

Reply to this message.

Usage

From source file:com.github.ithildir.airbot.service.UserServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {/* w w w.j  a va  2s.co m*/
        JsonObject json = msg.body();
        String action = msg.headers().get("action");
        if (action == null) {
            throw new IllegalStateException("action not specified");
        }
        accessed();
        switch (action) {

        case "getUserLocation": {
            service.getUserLocation((java.lang.String) json.getValue("userId"), res -> {
                if (res.failed()) {
                    if (res.cause() instanceof ServiceException) {
                        msg.reply(res.cause());
                    } else {
                        msg.reply(new ServiceException(-1, res.cause().getMessage()));
                    }
                } else {
                    msg.reply(res.result() == null ? null : res.result().toJson());
                }
            });
            break;
        }
        case "updateUserLocation": {
            service.updateUserLocation((java.lang.String) json.getValue("userId"),
                    json.getValue("latitude") == null ? null : (json.getDouble("latitude").doubleValue()),
                    json.getValue("longitude") == null ? null : (json.getDouble("longitude").doubleValue()),
                    (java.lang.String) json.getValue("country"), createHandler(msg));
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.reply(new ServiceException(500, t.getMessage()));
        throw t;
    }
}

From source file:com.github.jackygurui.vertxredissonrepository.handler.Impl.CallInMessageHandlerImpl.java

License:Apache License

@Override
public void handle(Message<JsonObject> m) {
    JsonObject jBody = m.body();/*from w  w w. j a va 2  s. c o  m*/
    String from = jBody.getString("from");
    String to = jBody.getString("to");
    Long requestTime = jBody.getLong("requestTime");
    String userData = jBody.getString("userData");
    AtomicReference<String> cId = new AtomicReference();
    AtomicReference<Customer.PersonalDetails> p = new AtomicReference();
    Async.waterfall().<String>task(t -> {
        personalDetailsRepo.searchUniqueIndex("phoneNumber", from, t);
    }).<Customer.PersonalDetails>task((id, t) -> {
        cId.set(id);
        personalDetailsRepo.get(id, t);
    }).<Customer.AddressDetails>task((c, t) -> {
        p.set(c);
        addressDetailsRepo.get(cId.get(), t);
    }).run(r -> {
        CallIn ci;
        if (r.failed()) {
            ci = CallIn.builder().callTime(requestTime).callType(numberTypeMap.get(to)).comments(userData)
                    .fullName("??").phoneNumber(from).build();
        } else {
            Customer.PersonalDetails cpd = p.get();
            Customer.AddressDetails cad = r.result();
            ci = CallIn.builder().address(cad.getFullAddress()).area(cpd.getArea()).birthDay(cpd.getBirthDay())
                    .callTime(requestTime).callType(numberTypeMap.get(to)).city(cpd.getCity())
                    .comments(userData).customerId(cId.get()).fullName(cpd.getFullName())
                    .gender(cpd.getGender()).phoneNumber(from).province(cpd.getProvince()).type(cpd.getType())
                    .build();
        }
        callInRepo.create(Json.encode(ci), c -> {
            m.reply(c.result());
            ci.setId(c.result());
            vertx.eventBus().publish("client.notification.inComingCall", Json.encode(ci));
        });
    });
}

From source file:com.github.vertx.node.example.HelloWorldServiceInterfaceVertxProxyHandler.java

License:Apache License

private <T> Handler<AsyncResult<T>> createHandler(Message msg) {
    return res -> {
        if (res.failed()) {
            msg.fail(-1, res.cause().getMessage());
        } else {/*w  ww.  ja  v  a2  s  .  c o  m*/
            if (res.result() != null && res.result().getClass().isEnum()) {
                msg.reply(((Enum) res.result()).name());
            } else {
                msg.reply(res.result());
            }
        }
    };
}

From source file:com.glencoesoftware.omero.ms.core.RedisCacheVerticle.java

License:Open Source License

/**
 * Get a key from the cache./* ww w .j  a v a2  s.c  o m*/
 */
private void get(Message<String> message) {
    if (connection == null) {
        log.debug("Cache not enabled");
        message.reply(null);
        return;
    }

    String key = message.body();
    if (key == null) {
        message.reply(null);
        return;
    }
    log.debug("Getting cache key: {}", key);

    RedisAsyncCommands<byte[], byte[]> commands = connection.async();
    final StopWatch t0 = new Slf4JStopWatch("get");
    // Binary retrieval, get(String) includes a UTF-8 step
    RedisFuture<byte[]> future = commands.get(key.getBytes());
    future.whenComplete((v, t) -> {
        try {
            if (t != null) {
                log.error("Exception while getting cache value", t);
                message.fail(500, t.getMessage());
                return;
            }
            message.reply(v);
        } finally {
            t0.stop();
        }
    });
}

From source file:com.glencoesoftware.omero.ms.core.RedisCacheVerticle.java

License:Open Source License

/**
 * Set a key in the cache./*w w  w. jav  a  2  s .com*/
 */
private void set(Message<JsonObject> message) {
    if (connection == null) {
        log.debug("Cache not enabled");
        message.reply(null);
        return;
    }

    JsonObject data = message.body();
    String key = data.getString("key");
    byte[] value = data.getBinary("value");
    if (key == null) {
        message.reply(null);
        return;
    }
    log.debug("Setting cache key: {}", key);

    RedisAsyncCommands<byte[], byte[]> commands = connection.async();
    final StopWatch t0 = new Slf4JStopWatch("set");
    // Binary retrieval, get(String) includes a UTF-8 step
    RedisFuture<String> future = commands.set(key.getBytes(), value);
    future.whenComplete((v, t) -> {
        try {
            if (t != null) {
                log.error("Exception while setting cache value", t);
                message.fail(500, t.getMessage());
                return;
            }
            if (!"OK".equals(v)) {
                message.fail(500, "Non OK reply: " + v);
                return;
            }
            message.reply(null);
        } finally {
            t0.stop();
        }
    });
}

From source file:com.glencoesoftware.omero.ms.thumbnail.ThumbnailVerticle.java

License:Open Source License

/**
 * Render thumbnail event handler. Responds with a <code>image/jpeg</code>
 * body on success or a failure.//from w w w  .j a  v  a2s  . co m
 * @param message JSON encoded event data. Required keys are
 * <code>omeroSessionKey</code> (String), <code>longestSide</code>
 * (Integer), and <code>imageId</code> (Long).
 */
private void renderThumbnail(Message<String> message) {
    JsonObject data = new JsonObject(message.body());
    String omeroSessionKey = data.getString("omeroSessionKey");
    int longestSide = data.getInteger("longestSide");
    long imageId = data.getLong("imageId");
    Optional<Long> renderingDefId = Optional.ofNullable(data.getLong("renderingDefId"));
    log.debug("Render thumbnail request Image:{} longest side {} RenderingDef:{}", imageId, longestSide,
            renderingDefId.orElse(null));

    try (OmeroRequest request = new OmeroRequest(host, port, omeroSessionKey)) {
        byte[] thumbnail = request
                .execute(new ThumbnailRequestHandler(longestSide, imageId, renderingDefId)::renderThumbnail);
        if (thumbnail == null) {
            message.fail(404, "Cannot find Image:" + imageId);
        } else {
            message.reply(thumbnail);
        }
    } catch (PermissionDeniedException | CannotCreateSessionException e) {
        String v = "Permission denied";
        log.debug(v);
        message.fail(403, v);
    } catch (Exception e) {
        String v = "Exception while retrieving thumbnail";
        log.error(v, e);
        message.fail(500, v);
    }
}

From source file:com.glencoesoftware.omero.ms.thumbnail.ThumbnailVerticle.java

License:Open Source License

/**
 * Get thumbnails event handler. Responds with a JSON dictionary of Base64
 * encoded <code>image/jpeg</code> thumbnails keyed by {@link Image}
 * identifier. Each dictionary value is prefixed with
 * <code>data:image/jpeg;base64,</code> so that it can be used with
 * <a href="http://caniuse.com/#feat=datauri">data URIs</a>.
 * @param message JSON encoded event data. Required keys are
 * <code>omeroSessionKey</code> (String), <code>longestSide</code>
 * (Integer), and <code>imageIds</code> (List<Long>).
 *//*from   w w  w  .j ava  2  s.  com*/
private void getThumbnails(Message<String> message) {
    JsonObject data = new JsonObject(message.body());
    String omeroSessionKey = data.getString("omeroSessionKey");
    int longestSide = data.getInteger("longestSide");
    JsonArray imageIdsJson = data.getJsonArray("imageIds");
    List<Long> imageIds = new ArrayList<Long>();
    for (int i = 0; i < imageIdsJson.size(); i++) {
        imageIds.add(imageIdsJson.getLong(i));
    }
    log.debug("Render thumbnail request ImageIds:{} longest side {}", imageIds, longestSide);

    try (OmeroRequest request = new OmeroRequest(host, port, omeroSessionKey)) {
        Map<Long, byte[]> thumbnails = request
                .execute(new ThumbnailsRequestHandler(longestSide, imageIds)::renderThumbnails);

        if (thumbnails == null) {
            message.fail(404, "Cannot find one or more Images");
        } else {
            Map<Long, String> thumbnailsJson = new HashMap<Long, String>();
            for (Entry<Long, byte[]> v : thumbnails.entrySet()) {
                thumbnailsJson.put(v.getKey(), "data:image/jpeg;base64," + Base64.encode(v.getValue()));
            }
            message.reply(Json.encode(thumbnailsJson));
        }
    } catch (PermissionDeniedException | CannotCreateSessionException e) {
        String v = "Permission denied";
        log.debug(v);
        message.fail(403, v);
    } catch (Exception e) {
        String v = "Exception while retrieving thumbnail";
        log.error(v, e);
        message.fail(500, v);
    }
}

From source file:com.groupon.vertx.memcache.command.MemcacheCommandHandler.java

License:Apache License

/**
 * This handles the incoming Memcache command JSON.
 *
 * @param command - The JsonObject containing the command and arguments to send to Memcache.
 *///from   w ww . jav  a2  s  .  c om
public void handle(final Message<MemcacheCommand> command) {
    MemcacheCommand memcacheCommand = command.body();
    if (memcacheCommand == null) {
        log.warn("handleCommand", "failure", new String[] { "reason" }, "Missing message body");
        command.reply(buildErrorReply("Invalid message with null or empty."));
        return;
    }

    memcacheCommand.commandResponseHandler(commandResponse -> {
        log.trace("handleCommand", "reply", new String[] { "response" }, commandResponse);
        command.reply(commandResponse);
    });

    socket.sendCommand(memcacheCommand);
}

From source file:com.groupon.vertx.redis.RedisCommandHandler.java

License:Apache License

/**
 * This handles the incoming Redis command JSON.
 *
 * @param command - The JsonObject containing the commands to send to Redis.
 *//*from  w  w  w .  j  av a  2s  .c  om*/
public void handle(final Message<JsonObject> command) {
    if (command.body() == null || command.body().size() == 0) {
        log.warn("handleCommand", "failure", new String[] { "reason" }, "Missing message body");
        command.reply(buildReply("error", null, "Invalid message with null or empty."));
        return;
    }

    JsonObject inputJson = command.body();
    boolean isMulti = inputJson.getBoolean("isTransaction", false);
    JsonArray commands = inputJson.getJsonArray("commands", new JsonArray());
    if (commands.size() > 0) {
        LinkedList<RedisCommand> transactionRedisCommands = new LinkedList<>();
        for (Object jsonCommand : commands) {
            RedisCommand redisCommand = getRedisCommand((JsonObject) jsonCommand, command, isMulti);
            if (redisCommand == null) {
                log.warn("handleCommand", "failure", new String[] { "reason" }, "Invalid redis command");
                command.reply(buildReply("error", null, "Invalid redis command"));
                return;
            }
            transactionRedisCommands.add(redisCommand);
        }
        if (isMulti) { //Wrap it with a  MULTI and EXEC block
            transactionRedisCommands.addFirst(new RedisCommand(RedisCommandType.MULTI, null));
            transactionRedisCommands.addLast(new RedisCommand(RedisCommandType.EXEC, null));
            setCommandResponseHandler(Collections.singletonList(transactionRedisCommands.getLast()), command,
                    isMulti);
        } else {
            setCommandResponseHandler(transactionRedisCommands, command, isMulti);
        }
        socket.sendCommand(transactionRedisCommands);
    } else {
        log.warn("handleCommand", "failure", new String[] { "reason" }, "Missing commands");
        command.reply(buildReply("error", null, "Invalid message with no commands"));
    }
}

From source file:com.groupon.vertx.redis.RedisCommandHandler.java

License:Apache License

private RedisCommand getRedisCommand(JsonObject jsonCommand, final Message<JsonObject> command,
        final boolean isMulti) {
    RedisCommand redisCommand = null;// w  w w. j  a  v a 2 s. c  o  m
    try {
        redisCommand = new RedisCommand(jsonCommand);
        log.trace("handleCommand", "createCommand", new String[] { "command", "isMulti" }, jsonCommand.encode(),
                isMulti);
    } catch (Exception ex) {
        log.error("handleCommand", "exception", "unknown", ex);
        command.reply(buildReply("error", null, ex.getMessage()));
    }
    return redisCommand;
}