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

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

Introduction

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

Prototype

default void fail(int failureCode, String message) 

Source Link

Document

Signal to the sender that processing of this message failed.

Usage

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

License:Open Source License

/**
 * Get a key from the cache.//from  w w 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.//from  ww  w .  j  a  v  a 2s.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.//w w w  .ja v a2 s .  com
 * @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>).
 *///w  w  w.  j a  va 2  s. c om
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.test.db.DbServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {//from w w  w . j ava2  s.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 "storedProc": {
            service.storedProc((java.lang.String) json.getValue("procName"),
                    (io.vertx.core.json.JsonObject) json.getValue("databaseConfig"), createHandler(msg));
            break;
        }
        case "createStm": {
            service.createStm((java.lang.String) json.getValue("query"),
                    (io.vertx.core.json.JsonObject) json.getValue("databaseConfig"), createHandler(msg));
            break;
        }
        case "update": {
            service.update((java.lang.String) json.getValue("query"),
                    (io.vertx.core.json.JsonObject) json.getValue("databaseConfig"), createHandler(msg));
            break;
        }
        case "delete": {
            service.delete((java.lang.String) json.getValue("query"),
                    (io.vertx.core.json.JsonObject) json.getValue("databaseConfig"), createHandler(msg));
            break;
        }
        case "read": {
            service.read((java.lang.String) json.getValue("query"),
                    (io.vertx.core.json.JsonObject) json.getValue("databaseConfig"), createHandler(msg));
            break;
        }
        case "nonSharedRead": {
            service.nonSharedRead((java.lang.String) json.getValue("query"),
                    (io.vertx.core.json.JsonObject) json.getValue("databaseConfig"), createHandler(msg));
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.fail(-1, t.getMessage());
        throw t;
    }
}

From source file:de.neofonie.deployer.DeployerVerticle.java

License:Open Source License

/**
 * Iterate and deploy verticles//  w  w w. j a  v  a2  s  .  c  o  m
 */
private void deployVerticle(final Message<JsonObject> event) {

    // iterate over all candidates to be deployed
    Set<String> candidates = this.workingCopy.fieldNames();

    // detach from underlying json
    Map<String, JsonObject> initiants = new HashMap<>();
    candidates.forEach(id -> {
        JsonObject info = this.workingCopy.getJsonObject(id);
        JsonArray dependsOn = info.getJsonArray("dependsOn");
        if (dependsOn != null && deployed.getList().containsAll(dependsOn.getList()) || dependsOn == null
                || dependsOn.isEmpty()) {
            initiants.put(id, info);
        }
    });

    // remove the initiants
    initiants.keySet().forEach(id -> this.workingCopy.remove(id));

    // setup latch for the reply
    CountDownLatch latch = new CountDownLatch(initiants.size());
    if (initiants.isEmpty()) {
        event.reply(Boolean.TRUE);
        return;
    }

    // run over all dependencies
    initiants.forEach((id, info) -> {

        // get the name of the verticle
        String name = info.getString("name");
        final JsonObject localConfig = new JsonObject();
        localConfig.mergeIn(globalConfig);
        localConfig.mergeIn(info.getJsonObject("config", new JsonObject()));

        Handler<AsyncResult<String>> handler = innerEvent -> {
            if (innerEvent.succeeded()) {
                // add service to deployed-list
                deployed.add(id);

                // re-emit
                vertx.eventBus().send(LOOPBACK, workingCopy, (AsyncResult<Message<Boolean>> recursiveReply) -> {
                    // always decrease latch
                    latch.countDown();

                    if (recursiveReply.succeeded() && recursiveReply.result().body()) {
                        if (latch.getCount() == 0) {
                            event.reply(recursiveReply.result().body() & Boolean.TRUE);
                        }
                    } else {
                        event.fail(500, this.getFailure(id, recursiveReply));
                    }
                });

            } else {
                event.fail(500, id + " >> " + innerEvent.cause().getMessage());
            }
        };

        LOG.log(Level.INFO, "Deploying: ''{0}''", new Object[] { id });
        DeploymentOptions deploymentOptions = new DeploymentOptions(info);
        vertx.deployVerticle(name, deploymentOptions.setConfig(localConfig), handler);
    });
}

From source file:fr.pjthin.vertx.client.UserDaoVertxProxyHandler.java

License:Apache License

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

        case "save": {
            service.save(
                    json.getJsonObject("newUser") == null ? null
                            : new fr.pjthin.vertx.client.data.User(json.getJsonObject("newUser")),
                    createHandler(msg));
            break;
        }
        case "findAll": {
            service.findAll(res -> {
                if (res.failed()) {
                    msg.fail(-1, res.cause().getMessage());
                } else {
                    msg.reply(new JsonArray(
                            res.result().stream().map(User::toJson).collect(Collectors.toList())));
                }
            });
            break;
        }
        case "findUserByLogin": {
            service.findUserByLogin((java.lang.String) json.getValue("login"), res -> {
                if (res.failed()) {
                    msg.fail(-1, res.cause().getMessage());
                } else {
                    msg.reply(res.result() == null ? null : res.result().toJson());
                }
            });
            break;
        }
        case "deleteByLogin": {
            service.deleteByLogin((java.lang.String) json.getValue("login"), createHandler(msg));
            break;
        }
        case "close": {
            service.close();
            close();
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.fail(-1, t.getMessage());
        throw t;
    }
}

From source file:io.apiman.gateway.platforms.vertx3.services.InitializeIngestorServiceVertxProxyHandler.java

License:Apache License

@Override
public void handle(Message<JsonObject> msg) {
    JsonObject json = msg.body();/*  ww  w . j a  v  a2s.c  o  m*/
    String action = msg.headers().get("action");
    if (action == null) {
        throw new IllegalStateException("action not specified");
    }
    accessed();
    switch (action) {
    case "createIngestor": {
        service.createIngestor((java.lang.String) json.getValue("uuid"), res -> {
            if (res.failed()) {
                msg.fail(-1, res.cause().getMessage());
            } else {
                String proxyAddress = UUID.randomUUID().toString();
                ProxyHelper.registerService(IngestorToPolicyService.class, vertx, res.result(), proxyAddress,
                        false, timeoutSeconds);
                msg.reply(null, new DeliveryOptions().addHeader("proxyaddr", proxyAddress));
            }
        });
        break;
    }

    default: {
        throw new IllegalStateException("Invalid action: " + action);
    }
    }
}

From source file:io.rebind.vertx.orientdb.OrientDBServiceVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {/* w w w.ja  va 2  s.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 "addVertex": {
            service.addVertex((java.lang.String) json.getValue("iClassName"),
                    (java.lang.String) json.getValue("iClusterName"),
                    (io.vertx.core.json.JsonObject) json.getValue("properties"), res -> {
                        if (res.failed()) {
                            msg.fail(-1, res.cause().getMessage());
                        } else {
                            msg.reply(res.result() == null ? null : res.result().toJson());
                        }
                    });
            break;
        }
        case "updateVertex": {
            service.updateVertex((java.lang.String) json.getValue("id"),
                    (io.vertx.core.json.JsonObject) json.getValue("properties"), res -> {
                        if (res.failed()) {
                            msg.fail(-1, res.cause().getMessage());
                        } else {
                            msg.reply(res.result() == null ? null : res.result().toJson());
                        }
                    });
            break;
        }
        case "removeVertex": {
            service.removeVertex((java.lang.String) json.getValue("id"), res -> {
                if (res.failed()) {
                    msg.fail(-1, res.cause().getMessage());
                } else {
                    msg.reply(res.result() == null ? null : res.result().toJson());
                }
            });
            break;
        }
        case "getVertex": {
            service.getVertex((java.lang.String) json.getValue("id"), res -> {
                if (res.failed()) {
                    msg.fail(-1, res.cause().getMessage());
                } else {
                    msg.reply(res.result() == null ? null : res.result().toJson());
                }
            });
            break;
        }
        case "getVerticesOfClass": {
            service.getVerticesOfClass((java.lang.String) json.getValue("iClassName"), res -> {
                if (res.failed()) {
                    msg.fail(-1, res.cause().getMessage());
                } else {
                    msg.reply(new JsonArray(
                            res.result().stream().map(Record::toJson).collect(Collectors.toList())));
                }
            });
            break;
        }
        case "getVertices": {
            service.getVertices((java.lang.String) json.getValue("iClassName"),
                    (io.vertx.core.json.JsonObject) json.getValue("vertexQuery"), res -> {
                        if (res.failed()) {
                            msg.fail(-1, res.cause().getMessage());
                        } else {
                            msg.reply(new JsonArray(
                                    res.result().stream().map(Record::toJson).collect(Collectors.toList())));
                        }
                    });
            break;
        }
        case "getRelatedVertices": {
            service.getRelatedVertices((java.lang.String) json.getValue("sourceId"),
                    (java.lang.String) json.getValue("label"), res -> {
                        if (res.failed()) {
                            msg.fail(-1, res.cause().getMessage());
                        } else {
                            msg.reply(new JsonArray(
                                    res.result().stream().map(Record::toJson).collect(Collectors.toList())));
                        }
                    });
            break;
        }
        case "addEdge": {
            service.addEdge((java.lang.String) json.getValue("sourceId"),
                    (java.lang.String) json.getValue("destinationId"),
                    (java.lang.String) json.getValue("label"),
                    (io.vertx.core.json.JsonObject) json.getValue("properties"), res -> {
                        if (res.failed()) {
                            msg.fail(-1, res.cause().getMessage());
                        } else {
                            msg.reply(res.result() == null ? null : res.result().toJson());
                        }
                    });
            break;
        }
        case "removeEdge": {
            service.removeEdge((java.lang.String) json.getValue("id"), res -> {
                if (res.failed()) {
                    msg.fail(-1, res.cause().getMessage());
                } else {
                    msg.reply(res.result() == null ? null : res.result().toJson());
                }
            });
            break;
        }
        case "removeEdges": {
            service.removeEdges((java.lang.String) json.getValue("sourceId"),
                    (java.lang.String) json.getValue("destinationId"),
                    (java.lang.String) json.getValue("label"), res -> {
                        if (res.failed()) {
                            msg.fail(-1, res.cause().getMessage());
                        } else {
                            msg.reply(new JsonArray(
                                    res.result().stream().map(Record::toJson).collect(Collectors.toList())));
                        }
                    });
            break;
        }
        case "getEdges": {
            service.getEdges((java.lang.String) json.getValue("sourceId"),
                    (java.lang.String) json.getValue("destinationId"),
                    (java.lang.String) json.getValue("label"), res -> {
                        if (res.failed()) {
                            msg.fail(-1, res.cause().getMessage());
                        } else {
                            msg.reply(new JsonArray(
                                    res.result().stream().map(Record::toJson).collect(Collectors.toList())));
                        }
                    });
            break;
        }
        case "getEdge": {
            service.getEdge((io.vertx.core.json.JsonObject) json.getValue("edgeQuery"), res -> {
                if (res.failed()) {
                    msg.fail(-1, res.cause().getMessage());
                } else {
                    msg.reply(new JsonArray(
                            res.result().stream().map(Record::toJson).collect(Collectors.toList())));
                }
            });
            break;
        }
        case "close": {
            service.close();
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.fail(-1, t.getMessage());
        throw t;
    }
}

From source file:net.kuujo.copycat.vertx.VertxEventBusProtocolServer.java

License:Apache License

@Override
public void handle(Message<byte[]> message) {
    if (handler != null) {
        handler.apply(ByteBuffer.wrap(message.body())).whenComplete((reply, error) -> {
            context.runOnContext(v -> {
                if (error != null) {
                    message.fail(0, error.getMessage());
                } else {
                    byte[] bytes = new byte[reply.remaining()];
                    reply.get(bytes);/*  ww w. j  a v a 2 s .c  om*/
                    message.reply(bytes);
                }
            });
        });
    } else {
        message.fail(ReplyFailure.NO_HANDLERS.toInt(), "No message handler registered");
    }
}