Example usage for io.vertx.core.json JsonArray getJsonObject

List of usage examples for io.vertx.core.json JsonArray getJsonObject

Introduction

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

Prototype

public JsonObject getJsonObject(int pos) 

Source Link

Document

Get the JsonObject at position pos in the array.

Usage

From source file:com.cyngn.vertx.opentsdb.service.OpenTsDbService.java

License:Apache License

private void initializeWorkers(Future<Void> startedResult) {
    final AtomicInteger count = new AtomicInteger();
    processor = new MetricsProcessor(workers, options.getMaxBufferBytes(), vertx.eventBus());
    JsonArray hosts = options.getHosts();
    for (int i = 0; i < hosts.size(); i++) {
        JsonObject jsonHost = hosts.getJsonObject(i);

        // we setup one worker dedicated to each endpoint, the same worker always rights to the same outbound socket
        OpenTsDbClient worker = new OpenTsDbClient(jsonHost.getString("host"), jsonHost.getInteger("port"),
                vertx, success -> {//  ww  w  .  j  a va2  s .c om
                    if (!success) {
                        String error = String.format("Failed to connect to host: %s", jsonHost.encode());
                        logger.error(error);
                        vertx.close();
                        startedResult.fail(error);
                        return;
                    }

                    count.incrementAndGet();
                    if (count.get() == hosts.size()) {
                        flushTimerId = vertx.setPeriodic(options.getFlushInterval(),
                                timerId -> processor.processMetrics(metrics));
                        logger.info(options);
                        startReporter();
                        startedResult.complete();
                    }
                });
        workers.add(worker);
    }
}

From source file:com.cyngn.vertx.opentsdb.service.OpenTsDbService.java

License:Apache License

private void processMetricBatch(Message<JsonObject> message) {
    JsonArray metricsObjects = message.body().getJsonArray(MetricsParser.METRICS_FIELD);

    if (metricsObjects == null) {
        String errMsg = String.format("invalid batch message request no 'metrics' field supplied, msg: %s",
                message.body());//from w ww .java2s  . c  o m
        logger.warn(errMsg);
        sendError(message, errMsg);
    }

    // roll through and add all the metrics
    for (int i = 0; i < metricsObjects.size(); i++) {
        String metric = metricsParser.createMetricString(message, metricsObjects.getJsonObject(i));
        if (metric != null) {
            if (!addMetric(null, metric)) {
                reportFullBacklog(message);
                break;
            }
        } else {
            // something is bad in the batch, the parsers error handler will reply to the message as failed
            return;
        }
    }
    message.reply(OK_REPLY);
}

From source file:com.github.ithildir.airbot.service.impl.MapQuestGeoServiceImpl.java

License:Open Source License

private Location _getLocation(JsonObject jsonObject) {
    JsonArray resultsJsonArray = jsonObject.getJsonArray("results");

    JsonObject resultJsonObject = resultsJsonArray.getJsonObject(0);

    JsonArray locationsJsonArray = resultJsonObject.getJsonArray("locations");

    JsonObject locationJsonObject = locationsJsonArray.getJsonObject(0);

    JsonObject latLngJsonObject = locationJsonObject.getJsonObject("latLng");

    double latitude = latLngJsonObject.getDouble("lat");
    double longitude = latLngJsonObject.getDouble("lng");

    String country = locationJsonObject.getString("adminArea1");

    return new Location(latitude, longitude, country);
}

From source file:com.github.ithildir.numbers.game.NumbersGameVerticle.java

License:Open Source License

private void _handle(RoutingContext routingContext) {
    JsonObject requestJSON = routingContext.getBodyAsJson();

    JsonArray inputsJSON = requestJSON.getJsonArray("inputs");

    JsonObject inputJSON = inputsJSON.getJsonObject(0);

    String intent = inputJSON.getString("intent");

    if (intent.equals(ConversationUtil.INTENT_MAIN)) {
        _handleMain(routingContext.response());
    } else {/* w w w  .  j  av  a  2  s.c o  m*/
        _handleText(requestJSON, inputJSON, routingContext.response());
    }
}

From source file:com.github.ithildir.numbers.game.NumbersGameVerticle.java

License:Open Source License

private void _handleText(JsonObject requestJSON, JsonObject inputJSON, HttpServerResponse httpServerResponse) {

    JsonArray rawInputsJSON = inputJSON.getJsonArray("raw_inputs");

    JsonObject rawInputJSON = rawInputsJSON.getJsonObject(0);

    String query = rawInputJSON.getString("query");

    JsonObject conversationJSON = requestJSON.getJsonObject("conversation");

    int correctAnswer = Integer.parseInt(conversationJSON.getString("conversation_token"));

    int answer;/* ww  w .  ja  va 2s .c  om*/

    try {
        answer = Integer.parseInt(query);
    } catch (NumberFormatException nfe) {
        ConversationUtil.ask(httpServerResponse, String.valueOf(correctAnswer),
                "That's not a number, say it again!", _NO_INPUT_PROMPTS);

        return;
    }

    String textToSpeech = "You're right, it is " + correctAnswer + "!";

    if (answer != correctAnswer) {
        textToSpeech = "You're wrong, it was " + correctAnswer + "!";
    }

    ConversationUtil.tell(httpServerResponse, textToSpeech);
}

From source file:io.flowly.auth.manager.BaseManager.java

License:Open Source License

/**
 * Revoke and grant permissions based on the specification.
 * Sequence - remove specified permissions, update specified permissions and then add specified permissions.
 *
 * @param vertex the node that represents a user or group vertex.
 * @param jsonObject JSON object representing the user or group permissions.
 *//*from   ww w .j a v a 2s  .c o  m*/
protected void redoPermissions(Vertex vertex, JsonObject jsonObject) {
    // Remove permissions.
    JsonArray permissionsToRemove = jsonObject.getJsonArray(Permission.PERMISSIONS_TO_REMOVE);
    if (permissionsToRemove != null) {
        graph.traversal().V(vertex).outE(Schema.E_HAS_PERMISSION).as("e").inV()
                .has(T.id, P.within(permissionsToRemove.getList().toArray())).<Edge>select("e").drop().toList();
    }

    // Update permissions.
    JsonArray permissionsToUpdate = jsonObject.getJsonArray(Permission.PERMISSIONS_TO_UPDATE);
    if (permissionsToUpdate != null) {
        for (Object prm : permissionsToUpdate) {
            Permission permission = new Permission((JsonObject) prm);
            Long resourceVertexId = permission.getResourceVertexId();

            graph.traversal().V(vertex).outE(Schema.E_HAS_PERMISSION).as("e").inV().has(T.id, resourceVertexId)
                    .<Edge>select("e").property(Schema.E_P_RWX, permission.getRWX()).toList();
        }
    }

    // Add permissions.
    JsonArray permissionsToAdd = jsonObject.getJsonArray(Permission.PERMISSIONS_TO_ADD);
    if (permissionsToAdd != null) {
        Set<Long> existingIds = new HashSet<>();
        Long[] idsToAdd = new Long[permissionsToAdd.size()];

        for (int i = 0; i < permissionsToAdd.size(); i++) {
            idsToAdd[i] = permissionsToAdd.getJsonObject(i).getLong(Permission.RESOURCE_VERTEX_ID);
        }

        graph.traversal().V(vertex).outE(Schema.E_HAS_PERMISSION).inV().has(T.id, P.within(idsToAdd))
                .sideEffect(s -> {
                    existingIds.add((Long) s.get().id());
                }).toList();

        grantPermissions(vertex, permissionsToAdd, existingIds);
    }

}

From source file:io.nonobot.core.handlers.GiphyHandler.java

License:Apache License

public void handle(Message msg) {
    String query = msg.matchedGroup(1);
    HttpClientRequest req = client.get(80, "api.giphy.com",
            "/v1/gifs/search?q=" + query + "&api_key=" + "dc6zaTOxFJmzC", resp -> {
                if (resp.statusCode() == 200 && resp.getHeader("Content-Type").equals("application/json")) {
                    System.out.println(resp.statusCode());
                    System.out.println(resp.statusMessage());
                    System.out.println(resp.getHeader("Content-Type"));
                    resp.exceptionHandler(err -> {
                        msg.reply("Error: " + err.getMessage());
                    });/*from  ww  w  .  ja va 2  s.c o m*/
                    Buffer buf = Buffer.buffer();
                    resp.handler(buf::appendBuffer);
                    resp.endHandler(v -> {
                        JsonObject json = new JsonObject(buf.toString());
                        JsonArray images = json.getJsonArray("data");
                        if (images.size() > 0) {
                            JsonObject image = images.getJsonObject(0); // Should be random !!!
                            String url = image.getJsonObject("images").getJsonObject("original")
                                    .getString("url");
                            msg.reply(url);
                        }
                        msg.reply("got response " + json);
                    });
                } else {
                    msg.reply("Error");
                }
            });
    req.exceptionHandler(err -> {
        msg.reply("Error: " + err.getMessage());
    });
    req.end();
}

From source file:io.nonobot.core.handlers.GitHubVerticle.java

License:Apache License

@Override
public void start() throws Exception {
    super.start();
    Router router = Router.router(vertx);
    bot.webRouter().mountSubRouter("/github", router);
    router.post().handler(ctx -> {/*from ww  w.  j  a v  a2  s. c om*/
        HttpServerRequest req = ctx.request();
        String event = req.getHeader("X-Github-Event");
        if (!"push".equals(event)) {
            req.response().setStatusCode(400).end("X-Github-Event " + event + " not handled");
            return;
        }
        String contentType = req.getHeader("Content-Type");
        if (!"application/json".equals(contentType)) {
            req.response().setStatusCode(400).end("Content-Type " + contentType + " not handled");
            return;
        }
        req.bodyHandler(body -> {
            JsonObject json = body.toJsonObject();
            req.response().end();
            String chatId = req.getParam("chat");
            JsonArray commits = json.getJsonArray("commits");
            if (chatId != null && commits != null && commits.size() > 0) {
                String commitWord = commits.size() > 1 ? "commits" : "commit";
                bot.chatRouter().sendMessage(new SendOptions().setChatId(chatId),
                        "Got " + commits.size() + " new " + commitWord + " from "
                                + json.getJsonObject("pusher").getString("name") + " on "
                                + json.getJsonObject("repository").getString("full_name"));
                for (int index = 0; index < commits.size(); index++) {
                    JsonObject commit = commits.getJsonObject(index);
                    bot.chatRouter().sendMessage(new SendOptions().setChatId(chatId),
                            "  * " + commit.getString("message") + " " + commit.getString("url"));
                }
            }
        });
    });
}

From source file:io.sqp.proxy.vertx.VertxBackendConnectionPool.java

License:Open Source License

private void loadConfigurations(JsonArray backendConfs) throws ConfigurationException {
    // first validate the configuration object
    if (backendConfs == null || backendConfs.isEmpty()) {
        throw new ConfigurationException("No backend was configured.");
    }/*w w w  .java 2s  .com*/
    if (backendConfs.size() > 1) {
        logger.log(Level.WARNING,
                "Only one backend configuration is supported at the moment. The rest is ignored.");
    }
    JsonObject firstConf = backendConfs.getJsonObject(0);
    if (firstConf == null) {
        throwInvalidConfiguration("It's not a valid JSON object.");
    }

    // Every backend needs a specific 'config' configuration map
    JsonObject backendSpecificConf = firstConf.getJsonObject("config");
    if (backendSpecificConf == null) {
        throwInvalidConfiguration("Backend specific configuration is missing.");
    }
    _backendSpecificConfiguration = backendSpecificConf.getMap();

    // The 'type' defines the subclass of BackendConnection that is the heart of the backend
    String backendType = firstConf.getString("type");
    if (backendType == null) {
        throwInvalidConfiguration("No type specified.");
    }
    // Get the class from the class loader and verify it's a subclass of BackendConnection
    Class<?> uncastedBackendClass = null;
    try {
        uncastedBackendClass = Class.forName(backendType);
    } catch (ClassNotFoundException e) {
        throwInvalidConfiguration("Class '" + backendType + "' specified as 'type' was not found.");
    }
    try {
        _backendClass = uncastedBackendClass.asSubclass(Backend.class);
    } catch (ClassCastException e) {
        throwInvalidConfiguration("Class '" + backendType + "' is not a valid Backend implementation.");
    }
}

From source file:org.eclipse.hono.service.credentials.BaseCredentialsService.java

License:Open Source License

private boolean containsValidSecretValue(final JsonObject credentials) {

    final Object obj = credentials.getValue(FIELD_SECRETS);

    if (JsonArray.class.isInstance(obj)) {

        JsonArray secrets = (JsonArray) obj;
        if (secrets.isEmpty()) {

            log.debug("credentials request contains empty {} object in payload - not supported", FIELD_SECRETS);
            return false;

        } else {/*from w  w  w.j av  a2  s  . co  m*/

            for (int i = 0; i < secrets.size(); i++) {
                JsonObject currentSecret = secrets.getJsonObject(i);
                if (!containsValidTimestampIfPresentForField(currentSecret, FIELD_SECRETS_NOT_BEFORE)
                        || !containsValidTimestampIfPresentForField(currentSecret, FIELD_SECRETS_NOT_AFTER)) {
                    log.debug("credentials request did contain invalid timestamp values in payload");
                    return false;
                }
            }

            return true;
        }

    } else {

        log.debug("credentials request does not contain a {} array in payload - not supported", FIELD_SECRETS);
        return false;

    }
}