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:org.etourdot.vertx.marklogic.model.options.DatabasesOptions.java

License:Open Source License

/**
 * Range attribute indexes/* ww w .jav  a2s. c o m*/
 */
public DatabasesOptions addRangeAttributeIndex(RangeAttributeIndex index) {
    if (operation == null) {
        operation = new JsonObject();
    }
    JsonArray indexes = operation.getJsonArray("range-element-attribute-indexes");
    if (indexes == null) {
        indexes = new JsonArray();
    }
    indexes.add(index.toJson());
    return this;
}

From source file:org.folio.auth.permissions_module.impl.MongoPermissionsStore.java

@Override
public Future<JsonArray> getExpandedPermissions(String permission, String tenant) {
    //System.out.println("Permissions> Expanding permission '"+ permission + "' on tenant '"+
    //        tenant + "'");
    JsonObject query = new JsonObject().put("permission_name", permission).put("tenant", tenant);
    JsonArray permList = new JsonArray();
    Future<JsonArray> future = Future.future();
    mongoClient.find("permissions", query, res -> {
        if (res.succeeded() && res.result().size() > 0) {
            //System.out.println("Permissions> Successfully queried mongo for '"+ permission + "' on tenant '"+
            //    tenant + "'");
            /*//from w  w w  . jav a  2  s .com
            If there are no subpermissions, go ahead and complete the future with the
            given value of the JsonArray
                    
            If there are subpermissions, create a list of new futures, by calling
            walkPerms for each sub permission, then create a composite future from
            these new futures, with a handler that completes the original
            future when they return
            */
            JsonObject permObj = res.result().get(0);
            permList.add(permission);
            JsonArray subPerms = permObj.getJsonArray("sub_permissions");
            LinkedList<Future> futureList = new LinkedList<>();
            if (subPerms != null && !subPerms.isEmpty()) {
                logger.debug("Permissions> " + subPerms.size() + " subs to process for '" + permission + "'");
                for (Object o : subPerms) {
                    String sub = (String) o;
                    Future<JsonArray> newFuture = getExpandedPermissions(sub, tenant);
                    futureList.add(newFuture);
                }
                logger.debug("Permissions> Creating CompositeFuture to expand " + permission + " into "
                        + futureList.size() + " subs: " + subPerms.encode());
                CompositeFuture compositeFuture = CompositeFuture.all(futureList);
                compositeFuture.setHandler(res2 -> {
                    if (res2.succeeded()) {
                        //Get output of contained futures and complete the future here
                        for (Future f : futureList) {
                            JsonArray arr = (JsonArray) f.result();
                            for (Object o : arr) {
                                permList.add(o);
                            }
                        }
                        future.complete(permList);
                    } else {
                        future.fail("Unable to populate permissions: " + res2.cause().getMessage());
                    }
                });
            } else {
                //System.out.println("Permissions> No sub-permissions found for '" + permission + "'");
                future.complete(permList);
            }
        } else {
            future.fail("No permission '" + permission + "' found for tenant '" + tenant + "'");
        }
    });
    return future;
}

From source file:org.folio.auth.permissions_module.impl.MongoPermissionsStore.java

public Future<JsonArray> getPermissionsForUser(String user, String tenant, Boolean expand) {
    JsonObject query = new JsonObject().put("username", user).put("tenant", tenant);
    Future<JsonArray> future = Future.future();
    mongoClient.find("users", query, (AsyncResult<List<JsonObject>> res) -> {
        if (res.result().size() < 1) {
            future.fail("No such user");
        } else {// w w w.ja  va  2 s  .  c  om
            JsonObject userObject = res.result().get(0);
            logger.debug("Permissions> Permissions for user " + user + ": " + userObject.encode());
            JsonArray permissions = userObject.getJsonArray("permissions");
            if (expand) {
                ArrayList<Future> futureList = new ArrayList<>();
                for (Object o : permissions) {
                    String permissionName = (String) o;
                    Future<JsonArray> expandPermissionFuture = this.getExpandedPermissions(permissionName,
                            tenant);
                    futureList.add(expandPermissionFuture);
                }
                logger.debug("Permissions> Assembling CompositeFuture of " + futureList.size()
                        + " permissions to expand");
                CompositeFuture compositeFuture = CompositeFuture.all(futureList);
                compositeFuture.setHandler(res2 -> {
                    if (res2.failed()) {
                        future.fail(res2.cause());
                    } else {
                        JsonArray allPermissions = new JsonArray();
                        for (Future f : futureList) {
                            JsonArray arr = (JsonArray) f.result();
                            for (Object o : arr) {
                                String perm = (String) o;
                                if (!allPermissions.contains(perm)) {
                                    allPermissions.add(perm);
                                }
                            }
                        }
                        logger.debug(
                                "Permissions> Returning list of " + allPermissions.size() + " permissions");
                        future.complete(allPermissions);
                    }
                });
            } else {
                future.complete(permissions);
            }
        }
    });
    return future;
}

From source file:org.gooru.nucleus.handlers.resources.processors.repositories.activejdbc.dbhandlers.DBHelper.java

static JsonObject getDuplicateResourcesByURL(String inputURL) {
    JsonObject returnValue = null;//from  w w w .j  a  v  a  2 s  .  c  o  m

    try {
        PGobject contentFormat = new PGobject();
        contentFormat.setType(AJEntityResource.CONTENT_FORMAT_TYPE);
        contentFormat.setValue(AJEntityResource.VALID_CONTENT_FORMAT_FOR_RESOURCE);

        LazyList<AJEntityResource> result = AJEntityResource
                .findBySQL(AJEntityResource.SQL_GETDUPLICATERESOURCESBYURL, inputURL, contentFormat);
        LOGGER.debug("getDuplicateResourcesByURL ! : {} ", result.toString());

        if (result.size() > 0) {
            JsonArray retArray = new JsonArray();
            for (AJEntityResource model : result) {
                retArray.add(model.get(AJEntityResource.RESOURCE_ID).toString());
            }
            returnValue = new JsonObject().put("duplicate_ids", retArray);
        }
    } catch (SQLException se) {
        LOGGER.error("getDuplicateResourcesByURL ! : {} ", se);
    }
    return returnValue;
}

From source file:org.gooru.nucleus.handlers.resources.processors.repositories.activejdbc.dbhandlers.DBHelper.java

static JsonObject getCopiesOfAResource(AJEntityResource resource, String originalResourceId) {
    JsonObject returnValue = null;//w  ww  .  j  a v a2  s  .  com

    setPGObject(resource, AJEntityResource.CONTENT_FORMAT, AJEntityResource.CONTENT_FORMAT_TYPE,
            AJEntityResource.VALID_CONTENT_FORMAT_FOR_RESOURCE);

    LazyList<AJEntityResource> result = AJEntityResource.findBySQL(AJEntityResource.SQL_GETCOPIESOFARESOURCE,
            AJEntityResource.VALID_CONTENT_FORMAT_FOR_RESOURCE, originalResourceId);
    if (result.size() > 0) {
        JsonArray idArray = new JsonArray();
        JsonArray collectionIdArray = new JsonArray();
        String collectionId;
        for (AJEntityResource model : result) {
            idArray.add(model.get(AJEntityResource.RESOURCE_ID).toString());
            collectionId = model.getString(AJEntityResource.COLLECTION_ID);
            if (collectionId != null && !collectionId.isEmpty()) {
                collectionIdArray.add(collectionId);
            }
        }
        returnValue = new JsonObject().put("resource_copy_ids", idArray)
                .put(AJEntityResource.COLLECTION_ID, collectionIdArray).put("id", originalResourceId);
        LOGGER.debug("getCopiesOfAResource ! : {} ", returnValue.toString());
    }
    return returnValue;
}

From source file:org.hawkular.apm.examples.vertx.opentracing.orderlog.OrderLogVerticle.java

License:Apache License

private void setupConsumers() {
    logger.info("Setting up consumers");
    getVertx().eventBus().consumer("joined").handler(
            message -> logger.info(String.format("Acknowledging that %s just joined", message.body())));

    MessageConsumer<JsonObject> ordersConfirmedConsumer = getVertx().eventBus().consumer("Orders.confirmed");
    MessageConsumer<JsonObject> getOrdersConsumer = getVertx().eventBus().consumer("OrderLog.getOrders");

    getOrdersConsumer.handler(message -> {
        JsonObject order = message.body();

        SpanContext spanCtx = tracer.extract(Format.Builtin.TEXT_MAP, new VertxMessageExtractAdapter(order));

        try (Span getOrdersSpan = tracer.buildSpan("GetOrders").asChildOf(spanCtx).start()) {

            try (Span ignored = tracer.buildSpan("RetrieveOrders").asChildOf(getOrdersSpan)
                    .withTag("database.url", "OrdersDB")
                    .withTag("database.statement", "SELECT order FROM Orders WHERE accountId = ?").start()) {
                String acctId = order.getString("accountId");
                JsonArray myOrders = orders.get(acctId);
                if (myOrders == null) {
                    sendError(1, "Account not found", message, getOrdersSpan);
                } else {
                    message.reply(myOrders);
                }//from  w  w  w .  j a va  2s. co  m
            }
        }
    }).completionHandler(result -> {
        if (result.succeeded()) {
            getVertx().eventBus().send("joined", "OrderLog.getOrders");
            logger.info("Registration has completed.");
        } else {
            logger.warning("Could not register: " + result.cause().getMessage());
        }
    });

    ordersConfirmedConsumer.handler(message -> {
        JsonObject order = message.body();

        SpanContext spanCtx = tracer.extract(Format.Builtin.TEXT_MAP, new VertxMessageExtractAdapter(order));

        try (Span orderConfirmedSpan = tracer.buildSpan("StoreOrder").asChildOf(spanCtx).start()) {

            try (Span ignored = tracer.buildSpan("WriteOrder").asChildOf(orderConfirmedSpan)
                    .withTag("database.url", "OrdersDB")
                    .withTag("database.statement", "UPDATE Orders SET order=?").start()) {

                String acctId = order.getString("accountId");
                JsonArray myOrders = orders.get(acctId);
                if (myOrders == null) {
                    myOrders = new JsonArray();
                    orders.put(acctId, myOrders);
                }
                myOrders.add(order);
            }
        }
    }).completionHandler(result -> {
        if (result.succeeded()) {
            getVertx().eventBus().send("joined", "Orders.confirmed");
            logger.info("Registration has completed.");
        } else {
            logger.warning("Could not register: " + result.cause().getMessage());
        }
    });
}

From source file:org.hawkular.apm.examples.vertx.opentracing.OrderLog.java

License:Apache License

protected void initOrdersConfirmedConsumer(EventBus eb, Tracer tracer) {
    ordersConfirmedConsumer = eb.consumer("Orders.confirmed");
    ordersConfirmedConsumer.handler(message -> {
        JsonObject order = message.body();

        SpanContext spanCtx = tracer.extract(Format.Builtin.TEXT_MAP, new VertxMessageExtractAdapter(order));

        try (Span orderConfirmedSpan = tracer.buildSpan("StoreOrder").asChildOf(spanCtx)
                .withTag("service", "OrderLog").start()) {

            try (Span storeOrderSpan = tracer.buildSpan("WriteOrder").asChildOf(orderConfirmedSpan)
                    .withTag("database.url", "OrdersDB")
                    .withTag("database.statement", "UPDATE Orders SET order=?").start()) {

                String acctId = order.getString("accountId");
                JsonArray myOrders = orders.get(acctId);
                if (myOrders == null) {
                    myOrders = new JsonArray();
                    orders.put(acctId, myOrders);
                }/*www  .j  a v a 2s  .co m*/
                myOrders.add(order);
            }
        }
    });
}

From source file:org.hawkular.metrics.clients.ptrans.Configuration.java

License:Apache License

private static JsonObject getHttpHeaders(Properties properties) {
    JsonObject jsonObject = new JsonObject();
    Set<Object> keys = properties.keySet();
    String namePrefix = "metrics.http.header.";
    String nameSuffix = ".name";
    Set<String> headerIds = keys.stream().filter(k -> k instanceof String).map(String.class::cast)
            .filter(name -> name.startsWith(namePrefix) && name.endsWith(nameSuffix))
            .map(name -> name.substring(namePrefix.length(), name.length() - nameSuffix.length()))
            .collect(Collectors.toSet());
    headerIds.forEach(headerId -> {/* w  w  w  .  ja v  a  2s . c  o m*/
        String headerName = properties.getProperty(namePrefix + headerId + nameSuffix);
        String valuePrefix = namePrefix + headerId + ".value.";
        List<Integer> headerPriorities = keys.stream().filter(k -> k instanceof String).map(String.class::cast)
                .filter(name -> name.startsWith(valuePrefix)).map(name -> name.substring(valuePrefix.length()))
                .filter(orderStr -> orderStr.matches("\\d{1,2}")).map(Integer::valueOf).sorted()
                .collect(toList());
        if (!headerPriorities.isEmpty()) {
            if (headerPriorities.size() == 1) {
                String headerValue = properties.getProperty(valuePrefix + headerPriorities.iterator().next());
                jsonObject.put(headerName, headerValue);
            } else {
                JsonArray headerValues = new JsonArray();
                headerPriorities.forEach(headerPriority -> {
                    String headerValue = properties.getProperty(valuePrefix + headerPriority);
                    headerValues.add(headerValue);
                });
                jsonObject.put(headerName, headerValues);
            }
        }
    });
    return jsonObject;
}

From source file:org.jberet.vertx.rest.JBeretRouterConfig.java

License:Open Source License

private static void getJobs(final RoutingContext routingContext) {
    final JobEntity[] jobEntities = JobService.getInstance().getJobs();
    final JsonArray jsonArray = new JsonArray();
    for (JobEntity jobEntity : jobEntities) {
        jsonArray.add(JsonObject.mapFrom(jobEntity));
    }/*w ww.j a  v a  2s  .  c  o m*/
    sendJsonResponse(routingContext, jsonArray.encodePrettily());
}

From source file:org.jberet.vertx.rest.JBeretRouterConfig.java

License:Open Source License

private static void getStepExecutions(final RoutingContext routingContext) {
    final long jobExecutionId = getIdAsLong(routingContext, "jobExecutionId");
    final StepExecutionEntity[] stepExecutions = JobService.getInstance().getStepExecutions(jobExecutionId);

    final JsonArray jsonArray = new JsonArray();
    for (StepExecutionEntity e : stepExecutions) {
        jsonArray.add(JsonObject.mapFrom(e));
    }//from  www.j  a va2s .co  m
    sendJsonResponse(routingContext, jsonArray.encodePrettily());
}