Example usage for io.vertx.core.json JsonObject JsonObject

List of usage examples for io.vertx.core.json JsonObject JsonObject

Introduction

In this page you can find the example usage for io.vertx.core.json JsonObject JsonObject.

Prototype

public JsonObject() 

Source Link

Document

Create a new, empty instance

Usage

From source file:com.groupon.vertx.memcache.MemcacheClusterConfig.java

License:Apache License

public MemcacheClusterConfig(JsonObject jsonConfig) {
    if (jsonConfig == null) {
        log.error("initialize", "exception", "noConfigFound");
        throw new MemcacheException("No Memcache cluster config found");
    }//from  w  ww .j  a v  a2 s  . c  om

    this.eventBusAddressPrefix = jsonConfig.getString(EVENT_BUS_ADDRESS_PREFIX_KEY);
    this.retryInterval = jsonConfig.getLong(RETRY_INTERVAL, MemcacheConfig.DEFAULT_RETRY_INTERVAL);
    JsonObject clusters = jsonConfig.getJsonObject(CLUSTERS_KEY, new JsonObject());

    if (eventBusAddressPrefix != null && !eventBusAddressPrefix.isEmpty() && clusters.size() > 0) {
        for (String clusterKey : clusters.fieldNames()) {
            JsonObject clusterConfig = clusters.getJsonObject(clusterKey, new JsonObject()).copy();
            clusterConfig.put(EVENT_BUS_ADDRESS_KEY, eventBusAddressPrefix);
            clusterConfig.put(RETRY_INTERVAL, retryInterval);
            clusterMap.put(clusterKey, new MemcacheConfig(clusterConfig));
        }
    } else {
        log.error("initialize", "exception", "invalidConfigFound", new String[] { "config" },
                jsonConfig.encode());
        throw new MemcacheException("Invalid Memcache config defined");
    }

    log.info("initialize", "success", new String[] { "eventBusAddressPrefix", "clusters" },
            eventBusAddressPrefix, clusterMap.size());
}

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

License:Apache License

@Override
protected Future<JsonObject> sendCommand(RedisCommand command) {
    final Future<JsonObject> finalResult = Future.future();
    final DeliveryOptions deliveryOptions = new DeliveryOptions().setSendTimeout(replyTimeout);
    eventBus.send(eventBusAddress, new JsonObject().put("commands", new JsonArray().add(command.toJson())),
            deliveryOptions, new Handler<AsyncResult<Message<JsonObject>>>() {
                @Override//w  w w .j  a  v  a  2 s.c  o  m
                public void handle(AsyncResult<Message<JsonObject>> messageAsyncResult) {
                    if (messageAsyncResult.succeeded() && messageAsyncResult.result() != null) {
                        finalResult.complete(messageAsyncResult.result().body());
                    } else {
                        RedisCommandException exception;
                        if (messageAsyncResult.cause() != null) {
                            String errorMessage;
                            final Throwable cause = messageAsyncResult.cause();
                            if (cause instanceof ReplyException) {
                                errorMessage = createErrorJson(((ReplyException) cause).failureType().name());
                            } else {
                                errorMessage = createErrorJson(cause.getMessage());
                            }
                            exception = new RedisCommandException(errorMessage);
                            exception.addSuppressed(messageAsyncResult.cause());
                        } else {
                            exception = new RedisCommandException(
                                    createErrorJson(HttpResponseStatus.INTERNAL_SERVER_ERROR.reasonPhrase()));
                        }
                        finalResult.fail(exception);
                    }
                }
            });
    return finalResult;
}

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

License:Apache License

private String createErrorJson(String message) {
    return new JsonObject().put("status", "error").put("code", HttpResponseStatus.INTERNAL_SERVER_ERROR.code())
            .put("message", message).encode();
}

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

License:Apache License

/**
 * Renders the command into a JsonObject for transport across the event bus.
 *
 * @return - A JsonObject containing the command.
 *//*  w  ww  .j  ava  2  s. c  o  m*/
public JsonObject toJson() {
    JsonObject jsonObject = new JsonObject();
    jsonObject.put("command", type.getCommand());

    JsonArray arrayArgs = new JsonArray();
    for (String arg : arguments) {
        arrayArgs.add(arg);
    }
    jsonObject.put("arguments", arrayArgs);

    return jsonObject;
}

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

License:Apache License

private JsonObject buildReply(String status, JsonObject data, String message) {
    JsonObject reply = new JsonObject();

    reply.put("status", status);

    if ("success".equals(status) || data != null) {
        reply.putNull("data");
    } else {//from   w ww .  j a v  a2  s . c  o  m
        reply.put("message", message);
    }

    return reply;
}

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

License:Apache License

/**
 * This method is fired when enough data is in the Buffer to complete a command.  If the
 * command does not match the signature of the buffered data then an exception is thrown
 * and the socket should be closed as the command/response queues are no longer in sync.
 *
 * @param command - The command to process from the response buffer.
 *///from  w w  w .j  a v  a  2  s . c o  m
private void processCommand(RedisCommand command) {
    if (command == null) {
        // No command to process so return.  Should add log message here.
        log.warn("processCommand", "noCommandFound");
        return;
    }

    JsonObject response = new JsonObject();

    byte[] line = completedLines.poll();

    if (line == null) {
        log.warn("processCommand", "noCompletedLinesFound", new String[] { "command" }, command.getCommand());
        response.put("status", "error");
        response.put("message", "Unable to find completed line for command: " + command.getCommand());
    } else if (line[0] == RedisResponseType.ERROR.marker) {
        log.warn("processCommand", "redisReturnedError", new String[] { "command" }, command.getCommand());
        response.put("status", "fail");
        response.put("data", processLine(line));
    } else if (line[0] == RedisResponseType.BULK_REPLY.marker && line[1] == '-') {
        log.debug("processCommand", "redisReturnedNil", new String[] { "command" }, command.getCommand());
        response.put("status", "success");
        response.put("data", processBulkLine(line));
    } else if (line[0] != command.getResponseType().marker) {
        log.warn("processCommand", "mismatchedResponse",
                new String[] { "command", "expectedDelim", "foundDelim" }, command.getCommand(),
                (char) command.getResponseType().marker, (char) line[0]);
        throw new RedisCommandException("Invalid response found");
    } else {
        response.put("status", "success");

        if (command.getResponseType() == RedisResponseType.MULTI_BULK_REPLY) {
            response.put("data", processMultiLine(line));
        } else if (command.getResponseType() == RedisResponseType.BULK_REPLY) {
            response.put("data", processBulkLine(line));
        } else if (command.getResponseType() == RedisResponseType.INTEGER_REPLY) {
            response.put("data", processIntegerLine(line));
        } else {
            response.put("data", processLine(line));
        }

        log.trace("processCommand", "redisCommandSuccess", new String[] { "command", "data" },
                command.getCommand(), response.getValue("data"));
    }

    command.setResponse(response);
}

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

License:Apache License

public Future<JsonObject> exec() {
    final Future<JsonObject> finalResult = Future.future();
    if (!pendingCommands.isEmpty()) {
        JsonArray commands = new JsonArray();
        final List<Future<JsonObject>> clientCommandResponses = new ArrayList<>();
        clientCommandResponses.add(finalResult);

        RedisCommand command = pendingCommands.poll();
        while (command != null) {
            clientCommandResponses.add(command.getClientCommandResponse());
            commands.add(command.toJson());
            command = pendingCommands.poll();
        }/*  w  w w.  j  av  a 2s. c o m*/

        JsonObject transactionCommands = new JsonObject();
        transactionCommands.put("isTransaction", true);
        transactionCommands.put("commands", commands);
        final DeliveryOptions deliveryOptions = new DeliveryOptions().setSendTimeout(replyTimeout);
        eventBus.send(eventBusAddress, transactionCommands, deliveryOptions,
                new Handler<AsyncResult<Message<JsonObject>>>() {
                    @Override
                    public void handle(AsyncResult<Message<JsonObject>> messageAsyncResult) {
                        JsonObject response;
                        if (messageAsyncResult.failed()) {
                            response = new JsonObject().put("status", "error").put("code",
                                    HttpURLConnection.HTTP_GATEWAY_TIMEOUT);
                        } else {
                            response = messageAsyncResult.result().body();
                        }

                        int index = 0;
                        executeResponse(clientCommandResponses.remove(0), response); // EXEC response
                        for (Future<JsonObject> clientCommandResponse : clientCommandResponses) {
                            if (clientCommandResponse != null) {
                                JsonObject result = constructTransactionCommandResult(response, index);
                                executeResponse(clientCommandResponse, result);
                            }
                            index++;
                        }
                    }
                });
    } else {
        // Nothing to execute.
        finalResult.complete(null);
    }
    return finalResult;
}

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

License:Apache License

private JsonObject constructTransactionCommandResult(JsonObject response, int index) {
    JsonArray responses = response.getJsonArray("data");
    if (responses != null && responses.size() > index) {
        Object commandResult = responses.getValue(index);
        JsonObject result = new JsonObject();
        result.put("status", response.getString("status"));
        if (commandResult instanceof JsonArray) {
            result.put("data", (JsonArray) commandResult);
        } else if (commandResult instanceof String) {
            result.put("data", (String) commandResult);
        } else if (commandResult instanceof Number) {
            result.put("data", (Number) commandResult);
        }// w w  w. ja v a 2 s.  com
        return result;
    }
    return response;
}

From source file:com.groupon.vertx.utils.config.ConfigLoader.java

License:Apache License

public Future<JsonObject> load(Object field) {
    Future<JsonObject> configFuture;

    if (field != null) {
        if (field instanceof String) {
            configFuture = getOrLoadConfig((String) field);
        } else if (field instanceof JsonObject) {
            configFuture = Future.future();
            configFuture.complete((JsonObject) field);
        } else {/*from   www  .ja v  a  2 s .co  m*/
            configFuture = Future.future();
            configFuture.fail(new IllegalStateException(
                    "Field `config` must contain an object or a string (path to the JSON config file)"));
        }
    } else {
        configFuture = Future.future();
        configFuture.complete(new JsonObject());
    }

    return configFuture;
}

From source file:com.hpe.sw.cms.store.Image.java

License:Apache License

public static JsonObject cloneImage(JsonObject sourceImage) {
    JsonObject targetImage = new JsonObject();
    targetImage.put("host", (sourceImage).getString("host"));
    targetImage.put("name", (sourceImage).getString("name"));
    targetImage.put("tag", (sourceImage).getString("tag"));
    targetImage.put("imageid", (sourceImage).getString("imageid"));
    targetImage.put("timestamp", (sourceImage).getLong("timestamp"));
    targetImage.put("isEnriched", (sourceImage).getBoolean("isEnriched"));
    targetImage.put("isScanned", (sourceImage).getBoolean("isScanned"));
    targetImage.put(Image.IS_SCANNED_FAILED, (sourceImage).getBoolean(Image.IS_SCANNED_FAILED));
    return targetImage;
}