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:pt.davidafsilva.slacker.server.EventServerVerticle.java

License:Open Source License

/**
 * Handles a executor register request message event by trying to register the executor with the
 * received information.//from  w  ww  .  jav a2s .  c  om
 * The registry might fail due to incompatible versions
 *
 * @param message the request message event
 */
private void handlerRegisterEvent(final Message<Object> message) {
    LOGGER.debug("received register event message: {0}", message.body());

    // validate the received event
    if (message.body() == null || !JsonObject.class.isInstance(message.body())) {
        message.fail(1, "invalid register event received");
        return;
    }

    // try to register the executor
    final JsonObject executorRequest = (JsonObject) message.body();
    executorRegistry.register(executorRequest, address -> message.reply(new JsonObject().put("a", address)),
            reason -> message.fail(1, String.format("unable to register executor: %s", reason)));
}

From source file:pt.davidafsilva.slacker.server.EventServerVerticle.java

License:Open Source License

/**
 * Handles a request message event by delivering the request to the appropriate executor, if
 * any is registered to handle that particular type of request.
 *
 * @param message the request message event
 *//*from   www .ja v a  2  s  .c  o  m*/
private void handlerRequestEvent(final Message<Object> message) {
    LOGGER.debug("received request event message: {0}", message.body());

    // validate the received event
    if (message.body() == null || !SlackerRequest.class.isInstance(message.body())) {
        LOGGER.error("invalid event body");
        message.fail(1, "invalid request event received");
        return;
    }

    // handle the request
    final SlackerRequest request = (SlackerRequest) message.body();
    executorRegistry.lookup(request.getCommand(), address -> sendRequestToExecutor(address, request, message),
            v -> message.fail(1,
                    String.format("no executor available for the command: %s", request.getCommand())));
}

From source file:pt.davidafsilva.slacker.server.EventServerVerticle.java

License:Open Source License

/**
 * Sends the requests to the executor and handles the reply
 *
 * @param address        the address of the executor
 * @param request        the request to be sent
 * @param requestMessage the original request message with the reply address
 *///from  w  w  w .  j  av  a  2  s  .com
private void sendRequestToExecutor(final String address, final SlackerRequest request,
        final Message<Object> requestMessage) {
    LOGGER.debug("forwarding request message to {0}..", address);
    vertx.eventBus().send(address, request, new DeliveryOptions().setCodecName(SlackerRequestMessageCodec.NAME),
            reply -> {
                if (reply.succeeded() && SlackerResponse.class.isInstance(reply.result().body())) {
                    requestMessage.reply(reply.result().body(),
                            new DeliveryOptions().setCodecName(SlackerResponseMessageCodec.NAME));
                } else {
                    LOGGER.error("failed to process request", reply.cause());
                    requestMessage.fail(2,
                            String.format("failed %s processing: %s", request.getCommand(),
                                    Optional.ofNullable(reply.cause()).map(Throwable::getMessage)
                                            .orElse("invalid response")));
                }
            });
}

From source file:pt.davidafsilva.ushortx.persistence.DatabaseVerticle.java

License:Open Source License

/**
 * Queries the database for an url entry with the identifier specified in the message
 *
 * @param message the message from where to extract the identifier and to reply from
 *///www .  j  av a 2s. c  om
private void findById(final Message<JsonObject> message) {
    LOGGER.info("incoming find request: " + message.body());
    connect(connection -> {
        // validate the identifier
        final Optional<Long> id = Optional.ofNullable(message.body().getLong("id"));
        if (!id.isPresent()) {
            connection.close();
            message.fail(2, "invalid identifier");
            return;
        }

        // create the query parameters
        final JsonArray queryParams = new JsonArray().add(id.get());

        // execute the query
        connection.queryWithParams(FIND_BY_ID_QUERY, queryParams,
                FIND_QUERY_RESULT_HANDLER.apply(message, connection));
    }, Optional.of(cause -> message.fail(1, "unavailable resources")));
}

From source file:pt.davidafsilva.ushortx.persistence.DatabaseVerticle.java

License:Open Source License

/**
 * Saves at the database the url specified in the message, if non-existent. Otherwise the same
 * entry is used.//from www.ja va  2 s . co  m
 *
 * @param message the message from where to extract the url data and to reply from
 */
private void saveUrl(final Message<JsonObject> message) {
    LOGGER.info("incoming save request: " + message.body());
    connect(connection -> {
        // validate the url
        final Optional<String> url = Optional.ofNullable(message.body().getString("url"));
        if (!url.isPresent()) {
            connection.close();
            message.fail(2, "invalid url");
            return;
        }

        // create the update parameters
        final JsonArray updateParams = new JsonArray().add(url.get());

        // execute the update
        connection.updateWithParams(INSERT_URL_STATEMENT, updateParams,
                INSERT_URL_RESULT_HANDLER.apply(message, connection));
    }, Optional.of(cause -> message.fail(1, "unavailable resources")));
}

From source file:se.liquidbytes.jel.database.DatabaseServiceVertxProxyHandler.java

License:Apache License

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

    case "getConnection": {
        service.getConnection(res -> {
            if (res.failed()) {
                msg.fail(-1, res.cause().getMessage());
            } else {
                String proxyAddress = UUID.randomUUID().toString();
                ProxyHelper.registerService(DatabaseConnection.class, vertx, res.result(), proxyAddress);
                msg.reply(null, new DeliveryOptions().addHeader("proxyaddr", proxyAddress));
            }
        });
        break;
    }
    case "start": {
        service.start();
        break;
    }
    case "stop": {
        service.stop();
        break;
    }
    default: {
        throw new IllegalStateException("Invalid action: " + action);
    }
    }
}

From source file:se.liquidbytes.jel.owfs.OwfsAdapter.java

License:Apache License

/**
 * Main method for parsing the different requests that are sent to this adapter.
 *
 * @param message//from   w  w  w.  ja v  a2s . co m
 */
private void handleRequest(Message message) {
    String action = message.headers().get("action");
    logger.debug("Executing action \"{}\" on Owserver with adapter id \"{}\" running at {}:{}.", action,
            this.getId(), this.host, this.port);

    try {
        switch (action) {
        case "listSupportedDevices":
            this.getSupportedDevices(message);
            break;
        case "listDevices":
            this.getAvailableDevices(message);
            break;
        case "retrieveDeviceValue":
            this.getDeviceValue(message);
            break;
        case "updateDeviceValue":
            this.setDeviceValue(message);
            break;
        default:
            logger.info("Received a request for a non-implemented action '{}'. Ignoring action.", action);
        }

        logger.debug("Done executing action \"{}\" on Owserver with adapter id \"{}\" running at {}:{}.",
                action, this.getId(), this.host, this.port);
    } catch (DeviceMissingException ex) {
        logger.info(
                "Trying to perform an action on a non existing device ({}) on Owserver with adapter id \"{}\" running at {}:{}.",
                ex.getHardwareId(), this.getId(), this.host, this.port);
        message.fail(404, ex.getMessage());
    } catch (OwServerConnectionException ex) {
        logger.error("Failed to execute action \"{}\" on Owserver with adapter id \"{}\" running at {}:{}.",
                action, this.getId(), this.host, this.port, ex);
        message.fail(500, ex.getMessage());
    }
}

From source file:se.liquidbytes.jel.owfs.OwfsAdapter.java

License:Apache License

/**
 * Read value from device with specified hwId.
 *
 * @param message eventbus message.//w w w .ja v  a  2 s.c  om
 * @throws DeviceMissingException throws exception if specified device does not exist.
 */
private void getDeviceValue(Message message) throws DeviceMissingException {
    // Validate and extract action-specific parameters.
    if (message.body() == null) {
        message.fail(400, "Missing parameters.");
        return;
    }

    JsonObject params = (JsonObject) message.body();
    String hwId = params.getString("hwId");

    if (hwId == null || hwId.isEmpty()) {
        message.fail(400, "Missing parameter 'hwId'.");
        return;
    }

    message.reply(this.constructReply(this.getDeviceValue(hwId)));
}

From source file:se.liquidbytes.jel.owfs.OwfsAdapter.java

License:Apache License

/**
 * Set value on device with specified hwId.
 *
 * @param message eventbus message.//from  w  ww  .ja  v a 2s.  c om
 * @throws DeviceMissingException throws exception if specified device does not exist.
 * @throws OwServerConnectionException throws exception if command fails for any reason.
 */
private void setDeviceValue(Message message) throws DeviceMissingException, OwServerConnectionException {
    // Validate and extract action-specific parameters.
    if (message.body() == null) {
        message.fail(400, "Missing parameters.");
        return;
    }

    JsonObject params = (JsonObject) message.body();
    String hwId = params.getString("hwId");
    String value = params.getString("value");

    if (hwId == null || hwId.isEmpty()) {
        message.fail(400, "Missing parameter 'hwId'.");
        return;
    }
    if (value == null || value.isEmpty()) {
        message.fail(400, "Missing parameter 'value'.");
        return;
    }

    this.setDeviceValue(hwId, value);
}