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

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

Introduction

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

Prototype

public JsonArray add(Object value) 

Source Link

Document

Add an Object to the JSON array.

Usage

From source file:io.knotx.util.MultiMapConverter.java

License:Apache License

/**
 * Converts MultiMap to JsonObject<br> It expects the MultiMap key, contains List of String
 * objects, so the result of conversion will look like below
 * <br>/* w w w  .  ja  va 2 s  .com*/
 * <pre>
 *   {
 *      "mapKey1": ["val1", "val2"],
 *      "mapKey2": ["val1"]
 *   }
 * </pre>
 *
 * @param multiMap - {@link MultiMap} to convert
 * @return - {@link JsonObject} with {@link JsonArray} under each object key
 */
public static JsonObject toJsonObject(MultiMap multiMap) {
    JsonObject json = new JsonObject();

    ((io.vertx.core.MultiMap) multiMap.getDelegate()).forEach(entry -> {
        JsonArray values;
        if (json.containsKey(entry.getKey())) {
            values = json.getJsonArray(entry.getKey());
        } else {
            values = new JsonArray();
            json.put(entry.getKey(), values);
        }
        values.add(entry.getValue());
    });

    return json;
}

From source file:io.silverware.microservices.providers.cdi.internal.RestInterface.java

License:Apache License

@SuppressWarnings("checkstyle:JavadocMethod")
public void listMethods(final RoutingContext routingContext) {
    String microserviceName = routingContext.request().getParam("microservice");
    Bean bean = gatewayRegistry.get(microserviceName);

    if (bean == null) {
        routingContext.response().setStatusCode(503).end("Resource not available");
    } else {//from   ww w. j  a  v  a  2s  .co  m
        JsonArray methods = new JsonArray();

        for (final Method m : bean.getBeanClass().getDeclaredMethods()) {
            if (Modifier.isPublic(m.getModifiers())) {
                JsonObject method = new JsonObject();
                method.put("methodName", m.getName());
                JsonArray params = new JsonArray();
                for (Class c : m.getParameterTypes()) {
                    params.add(c.getName());
                }
                method.put("parameters", params);
                method.put("returns", m.getReturnType().getName());

                methods.add(method);
            }
        }

        routingContext.response().end(methods.encodePrettily());
    }
}

From source file:io.techcode.logbulk.pipeline.input.SyslogInput.java

License:Open Source License

/**
 * Default implementation returns a list of structured data elements with
 * no internal parsing./*from w  w w .j  a  v a  2s . c o  m*/
 *
 * @param reader the reader.
 * @return the structured data.
 */
private JsonArray parseStructuredDataElements(Reader reader) {
    JsonArray fragments = new JsonArray();
    while (reader.is('[')) {
        reader.mark();
        reader.skipTo(']');
        fragments.add(reader.getMarkedSegment());
    }
    return fragments;
}

From source file:net.kuujo.vertigo.context.impl.InputPortContextImpl.java

License:Apache License

@Override
public JsonObject toJson() {
    JsonArray connectionJson = new JsonArray();
    connections.forEach(connection -> connectionJson.add(connection.toJson()));

    JsonObject json = new JsonObject().put("name", name).put("connections", connectionJson);

    if (type != null && type != Object.class) {
        json.put("type", type.toString());
    }//  ww  w  . j  a va 2 s.c o  m

    if (codec != null) {
        json.put("codec", codec.toString());
    }

    //    if (persistent) {
    //      json.put("persistent", persistent);
    //    }

    return json;

}

From source file:net.kuujo.vertigo.impl.AbstractResolver.java

License:Apache License

/**
 * Converts a Typesafe configuration list to {@link JsonObject}
 *
 * @param configs The Typesafe configuration list to convert.
 * @return The converted configuration./*  ww  w . ja  v  a  2 s.  c om*/
 */
@SuppressWarnings("unchecked")
protected static JsonArray configListToJson(ConfigList configs) {
    JsonArray json = new JsonArray();
    for (ConfigValue value : configs) {
        if (value.valueType() == ConfigValueType.OBJECT) {
            json.add(configObjectToJson((Config) value));
        } else if (value.valueType() == ConfigValueType.LIST) {
            json.add(configListToJson((ConfigList) value));
        } else {
            json.add(value.unwrapped());
        }
    }
    return json;
}

From source file:net.kuujo.vertigo.network.impl.NetworkImpl.java

License:Apache License

@Override
public JsonObject toJson() {
    JsonObject json = new JsonObject();
    json.put(NETWORK_NAME, name);// w  w w  . j a  v  a 2  s. co  m
    JsonObject components = new JsonObject();
    for (ComponentConfig component : this.components) {
        components.put(component.getName(), component.toJson());
    }
    json.put(NETWORK_COMPONENTS, components);
    JsonArray connections = new JsonArray();
    for (ConnectionConfig connection : this.connections) {
        connections.add(connection.toJson());
    }
    json.put(NETWORK_CONNECTIONS, connections);
    return json;
}

From source file:org.azrul.langmera.DecisionService.java

private void getHistory(RoutingContext routingContext) {
    final HistoryRequest req = Json.decodeValue(routingContext.getBodyAsString(), HistoryRequest.class);
    List<HistoryResponseElement> histResponses = new ArrayList<>();
    String driver = config.getProperty("jdbc.driver", String.class);
    String url = config.getProperty("jdbc.url", String.class);
    String username = config.getProperty("jdbc.username", String.class);
    String password = config.getProperty("jdbc.password", String.class);

    JDBCClient client = JDBCClient.createShared(vertx, new JsonObject().put("url", url)
            .put("driver_class", driver).put("user", username).put("password", password));
    JsonArray param = new JsonArray();
    param.add(req.getContext()).add(req.getFrom()).add(req.getTo());
    //        for (int i = 0; i < InMemoryDB.store.get(0).size(); i++) {
    //            HistoryResponseElement resp = new HistoryResponseElement();
    //            String context = (String) InMemoryDB.store.get(0).get(i);
    //            if (context.equals(req.getContext())) {
    //                Date time = (Date) InMemoryDB.store.get(3).get(i);
    //                if (time.after(req.getFrom()) && time.before(req.getTo())) {
    //                    resp.setContext(context);
    //                    resp.setDecision((String) InMemoryDB.store.get(1).get(i));
    //                    resp.setInterest((Double) InMemoryDB.store.get(2).get(i));
    //                    resp.setTime(time);
    //                    histResponses.add(resp);
    //                }
    //            }
    //        }//from www. j a v  a  2 s .c o  m

    client.getConnection(ar -> {
        SQLConnection connection = ar.result();
        connection.queryWithParams(
                "SELECT * FROM Trace ORDER BY decisiontime desc where context=? and decisiontime between ? and ?",
                param, r -> {
                    if (r.succeeded()) {
                        for (JsonArray row : r.result().getResults()) {
                            HistoryResponseElement respElement = new HistoryResponseElement();
                            respElement.setContext(row.getString(1));
                            respElement.setDecision(row.getString(6));
                            respElement.setInterest(row.getDouble(8));
                            respElement.setTime(new Date(row.getLong(5)));
                            histResponses.add(respElement);
                        }
                        HistoryResponse resp = new HistoryResponse();
                        resp.setElements(histResponses);

                        routingContext.response().setStatusCode(201)
                                .putHeader("content-type", "application/json; charset=utf-8")
                                .exceptionHandler(ex -> {
                                    logger.log(Level.SEVERE, "Problem encountered when making decision", ex);
                                }).end(Json.encodePrettily(resp));
                    }

                    connection.close();
                });

    });

}

From source file:org.eclipse.hono.client.impl.HonoClientImpl.java

License:Open Source License

@Override
public JsonArray getSenderStatus() {

    JsonArray result = new JsonArray();
    for (Entry<String, MessageSender> senderEntry : activeSenders.entrySet()) {
        final MessageSender sender = senderEntry.getValue();
        JsonObject senderStatus = new JsonObject().put("address", senderEntry.getKey())
                .put("open", sender.isOpen()).put("credit", sender.getCredit());
        result.add(senderStatus);
    }//w  w  w .j  ava  2s.c o  m
    return result;
}

From source file:org.eclipse.hono.deviceregistry.FileBasedCredentialsService.java

License:Open Source License

private void parseCredentials(final JsonArray credentialsObject) {
    final AtomicInteger credentialsCount = new AtomicInteger();

    log.debug("trying to load credentials for {} tenants", credentialsObject.size());
    for (Object obj : credentialsObject) {
        JsonObject tenant = (JsonObject) obj;
        String tenantId = tenant.getString(FIELD_TENANT);
        Map<String, JsonArray> credentialsMap = new HashMap<>();
        for (Object credentialsObj : tenant.getJsonArray(ARRAY_CREDENTIALS)) {
            JsonObject credentials = (JsonObject) credentialsObj;
            JsonArray authIdCredentials;
            if (credentialsMap.containsKey(credentials.getString(FIELD_AUTH_ID))) {
                authIdCredentials = credentialsMap.get(credentials.getString(FIELD_AUTH_ID));
            } else {
                authIdCredentials = new JsonArray();
            }/*ww w .  jav a 2 s. co m*/
            authIdCredentials.add(credentials);
            credentialsMap.put(credentials.getString(FIELD_AUTH_ID), authIdCredentials);
            credentialsCount.incrementAndGet();
        }
        credentials.put(tenantId, credentialsMap);
    }
    log.info("successfully loaded {} credentials from file [{}]", credentialsCount.get(),
            getConfig().getCredentialsFilename());
}

From source file:org.eclipse.hono.deviceregistry.FileBasedCredentialsService.java

License:Open Source License

private void saveToFile(final Future<Void> writeResult) {

    if (!dirty) {
        log.trace("credentials registry does not need to be persisted");
        return;/*  w w  w . j  a  v  a  2s.c  o  m*/
    }

    final FileSystem fs = vertx.fileSystem();
    String filename = getConfig().getCredentialsFilename();

    if (!fs.existsBlocking(filename)) {
        fs.createFileBlocking(filename);
    }
    final AtomicInteger idCount = new AtomicInteger();
    JsonArray tenants = new JsonArray();
    for (Entry<String, Map<String, JsonArray>> entry : credentials.entrySet()) {
        JsonArray credentialsArray = new JsonArray();
        for (Entry<String, JsonArray> credentialEntry : entry.getValue().entrySet()) { // authId -> full json attributes object
            JsonArray singleAuthIdCredentials = credentialEntry.getValue(); // from one authId
            credentialsArray.addAll(singleAuthIdCredentials);
            idCount.incrementAndGet();
        }
        tenants.add(
                new JsonObject().put(FIELD_TENANT, entry.getKey()).put(ARRAY_CREDENTIALS, credentialsArray));
    }
    fs.writeFile(getConfig().getCredentialsFilename(), Buffer.factory.buffer(tenants.encodePrettily()),
            writeAttempt -> {
                if (writeAttempt.succeeded()) {
                    dirty = false;
                    log.trace("successfully wrote {} credentials to file {}", idCount.get(), filename);
                    writeResult.complete();
                } else {
                    log.warn("could not write credentials to file {}", filename, writeAttempt.cause());
                    writeResult.fail(writeAttempt.cause());
                }
            });
}