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

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

Introduction

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

Prototype

public int size() 

Source Link

Document

Get the number of values in this JSON array

Usage

From source file:examples.ConfigExamples.java

License:Apache License

public void propsWitHierarchicalStructure() {
    ConfigStoreOptions propertyWitHierarchical = new ConfigStoreOptions().setFormat("properties")
            .setType("file")
            .setConfig(new JsonObject().put("path", "hierarchical.properties").put("hierarchical", true));
    ConfigRetrieverOptions options = new ConfigRetrieverOptions().addStore(propertyWitHierarchical);

    ConfigRetriever configRetriever = ConfigRetriever.create(Vertx.vertx(), options);

    configRetriever.configStream().handler(config -> {
        String host = config.getJsonObject("server").getString("host");
        Integer port = config.getJsonObject("server").getInteger("port");
        JsonArray multiple = config.getJsonObject("multiple").getJsonArray("values");
        for (int i = 0; i < multiple.size(); i++) {
            Integer value = multiple.getInteger(i);
        }/*from   w w w.j  a v  a  2 s . co m*/
    });
}

From source file:fr.wseduc.rack.controllers.RackController.java

License:Open Source License

private void copyFiles(final HttpServerRequest request, final JsonArray idsArray, final String folder,
        final UserInfos user, final String destinationCollection) {

    String criteria = "{ \"_id\" : { \"$in\" : " + idsArray.encode() + "}";
    criteria += ", \"to\" : \"" + user.getUserId() + "\" }";

    mongo.find(collection, new JsonObject(criteria), new Handler<Message<JsonObject>>() {

        private void persist(final JsonArray insert, int remains) {
            if (remains == 0) {
                mongo.insert(destinationCollection, insert, new Handler<Message<JsonObject>>() {
                    @Override//from  w  ww . j  a v  a2 s  .  co m
                    public void handle(Message<JsonObject> inserted) {
                        if ("ok".equals(inserted.body().getString("status"))) {
                            /* Increment quota */
                            long totalSize = 0l;
                            for (Object insertion : insert) {
                                JsonObject added = (JsonObject) insertion;
                                totalSize += added.getJsonObject("metadata", new JsonObject()).getLong("size",
                                        0l);
                            }
                            updateUserQuota(user.getUserId(), totalSize);
                            renderJson(request, inserted.body());
                        } else {
                            renderError(request, inserted.body());
                        }
                    }
                });
            }
        }

        @Override
        public void handle(Message<JsonObject> r) {
            JsonObject src = r.body();
            if ("ok".equals(src.getString("status")) && src.getJsonArray("results") != null) {
                final JsonArray origs = src.getJsonArray("results");
                final JsonArray insert = new JsonArray();
                final AtomicInteger number = new AtomicInteger(origs.size());

                emptySize(user, new Handler<Long>() {

                    @Override
                    public void handle(Long emptySize) {
                        long size = 0;

                        /* Get total file size */
                        for (Object o : origs) {
                            if (!(o instanceof JsonObject))
                                continue;
                            JsonObject metadata = ((JsonObject) o).getJsonObject("metadata");
                            if (metadata != null) {
                                size += metadata.getLong("size", 0l);
                            }
                        }
                        /* If total file size is too big (> quota left) */
                        if (size > emptySize) {
                            badRequest(request, "files.too.large");
                            return;
                        }

                        /* Process */
                        for (Object o : origs) {
                            JsonObject orig = (JsonObject) o;
                            final JsonObject dest = orig.copy();
                            String now = MongoDb.formatDate(new Date());
                            dest.remove("_id");
                            dest.remove("protected");
                            dest.remove("comments");
                            dest.put("application", WORKSPACE_NAME);

                            dest.put("owner", user.getUserId());
                            dest.put("ownerName", dest.getString("toName"));
                            dest.remove("to");
                            dest.remove("from");
                            dest.remove("toName");
                            dest.remove("fromName");

                            dest.put("created", now);
                            dest.put("modified", now);
                            if (folder != null && !folder.trim().isEmpty()) {
                                dest.put("folder", folder);
                            } else {
                                dest.remove("folder");
                            }
                            insert.add(dest);
                            final String filePath = orig.getString("file");

                            if (folder != null && !folder.trim().isEmpty()) {

                                //If the document has a new parent folder, replicate sharing rights
                                String parentName, parentFolder;
                                if (folder.lastIndexOf('_') < 0) {
                                    parentName = folder;
                                    parentFolder = folder;
                                } else if (filePath != null) {
                                    String[] splittedPath = folder.split("_");
                                    parentName = splittedPath[splittedPath.length - 1];
                                    parentFolder = folder;
                                } else {
                                    String[] splittedPath = folder.split("_");
                                    parentName = splittedPath[splittedPath.length - 2];
                                    parentFolder = folder.substring(0, folder.lastIndexOf("_"));
                                }

                                QueryBuilder parentFolderQuery = QueryBuilder.start("owner")
                                        .is(user.getUserId()).and("folder").is(parentFolder).and("name")
                                        .is(parentName);

                                mongo.findOne(collection, MongoQueryBuilder.build(parentFolderQuery),
                                        new Handler<Message<JsonObject>>() {
                                            @Override
                                            public void handle(Message<JsonObject> event) {
                                                if ("ok".equals(event.body().getString("status"))) {
                                                    JsonObject parent = event.body().getJsonObject("result");
                                                    if (parent != null && parent.getJsonArray("shared") != null
                                                            && parent.getJsonArray("shared").size() > 0)
                                                        dest.put("shared", parent.getJsonArray("shared"));

                                                    if (filePath != null) {
                                                        storage.copyFile(filePath, new Handler<JsonObject>() {
                                                            @Override
                                                            public void handle(JsonObject event) {
                                                                if (event != null && "ok"
                                                                        .equals(event.getString("status"))) {
                                                                    dest.put("file", event.getString("_id"));
                                                                    persist(insert, number.decrementAndGet());
                                                                }
                                                            }
                                                        });
                                                    } else {
                                                        persist(insert, number.decrementAndGet());
                                                    }
                                                } else {
                                                    renderJson(request, event.body(), 404);
                                                }
                                            }
                                        });

                            } else if (filePath != null) {
                                storage.copyFile(filePath, new Handler<JsonObject>() {

                                    @Override
                                    public void handle(JsonObject event) {
                                        if (event != null && "ok".equals(event.getString("status"))) {
                                            dest.put("file", event.getString("_id"));
                                            persist(insert, number.decrementAndGet());
                                        }
                                    }
                                });
                            } else {
                                persist(insert, number.decrementAndGet());
                            }
                        }
                    }
                });
            } else {
                notFound(request, src.toString());
            }
        }
    });

}

From source file:fr.wseduc.rack.controllers.RackController.java

License:Open Source License

private void createThumbnails(List<String> thumbs, JsonObject srcFile, final String collection,
        final String documentId) {
    Pattern size = Pattern.compile("([0-9]+)x([0-9]+)");
    JsonArray outputs = new JsonArray();
    for (String thumb : thumbs) {
        Matcher m = size.matcher(thumb);
        if (m.matches()) {
            try {
                int width = Integer.parseInt(m.group(1));
                int height = Integer.parseInt(m.group(2));
                if (width == 0 && height == 0)
                    continue;
                JsonObject j = new JsonObject().put("dest",
                        storage.getProtocol() + "://" + storage.getBucket());
                if (width != 0) {
                    j.put("width", width);
                }//from   w  ww  .  j  av a  2  s  .  c  om
                if (height != 0) {
                    j.put("height", height);
                }
                outputs.add(j);
            } catch (NumberFormatException e) {
                log.error("Invalid thumbnail size.", e);
            }
        }
    }
    if (outputs.size() > 0) {
        JsonObject json = new JsonObject().put("action", "resizeMultiple")
                .put("src",
                        storage.getProtocol() + "://" + storage.getBucket() + ":" + srcFile.getString("_id"))
                .put("destinations", outputs);
        eb.send(imageResizerAddress, json, new Handler<AsyncResult<Message<JsonObject>>>() {
            @Override
            public void handle(AsyncResult<Message<JsonObject>> event) {
                if (event.succeeded()) {
                    JsonObject thumbnails = event.result().body().getJsonObject("outputs");
                    if ("ok".equals(event.result().body().getString("status")) && thumbnails != null) {
                        mongo.update(collection, new JsonObject().put("_id", documentId),
                                new JsonObject().put("$set", new JsonObject().put("thumbnails", thumbnails)));
                    }
                } else {
                    log.error("Error when resize image.", event.cause());
                }
            }
        });
    }
}

From source file:fr.wseduc.smsproxy.providers.ovh.OVHSmsProvider.java

License:Apache License

@Override
public void sendSms(final Message<JsonObject> message) {
    final JsonObject parameters = message.body().getJsonObject("parameters");
    logger.debug("[OVH][sendSms] Called with parameters : " + parameters);

    final Handler<HttpClientResponse> resultHandler = new Handler<HttpClientResponse>() {
        public void handle(HttpClientResponse response) {
            if (response == null) {
                sendError(message, "ovh.apicall.error", null);
            } else {
                response.bodyHandler(new Handler<Buffer>() {
                    public void handle(Buffer body) {
                        final JsonObject response = new JsonObject(body.toString());
                        final JsonArray invalidReceivers = response.getJsonArray("invalidReceivers",
                                new JsonArray());
                        final JsonArray validReceivers = response.getJsonArray("validReceivers",
                                new JsonArray());

                        if (validReceivers.size() == 0) {
                            sendError(message, "invalid.receivers.all", null, new JsonObject(body.toString()));
                        } else if (invalidReceivers.size() > 0) {
                            sendError(message, "invalid.receivers.partial", null,
                                    new JsonObject(body.toString()));
                        } else {
                            message.reply(response);
                        }/*from w  w w. j  a  v a2s. c  om*/
                    }
                });
            }
        }
    };

    Handler<String> serviceCallback = new Handler<String>() {
        public void handle(String service) {
            if (service == null) {
                sendError(message, "ovh.apicall.error", null);
            } else {
                ovhRestClient.post("/sms/" + service + "/jobs/", parameters, resultHandler);
            }
        }
    };

    retrieveSmsService(message, serviceCallback);
}

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.
 *///  w  w w  . ja  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.flowly.auth.manager.GroupManager.java

License:Open Source License

/**
 * Create a group node in the auth graph.
 *
 * @param group JSON object representing a group's attributes, permissions, users and memberships.
 *              Ex: {/*from   w w w . ja  v  a  2 s  .  c  om*/
 *                  "groupId": "Group 1",
 *                  "usersToAdd": [
 *                      13,
 *                      14
 *                  ],
 *                  "groupsToAdd": [
 *                      12343,
 *                      34567
 *                  ],
 *                  "permissionsToAdd": [
 *                      {
 *                          "resourceVertexId": 555611
 *                          "rwx": 7
 *                      }
 *                  ]
 *              }
 * @return an empty list or a list of validation errors based on whether the group was created or not.
 */
@Override
public JsonArray create(JsonObject group) {
    Group newGroup = new Group(group);
    JsonArray errors = newGroup.validate();

    if (errors.size() == 0) {
        try {
            Vertex groupVertex = graph.addVertex(T.label, Schema.V_GROUP, Schema.V_P_GROUP_ID,
                    newGroup.getGroupId());
            setPropertyValue(groupVertex, Schema.V_P_DESCRIPTION, newGroup.getDescription());

            grantMemberships(groupVertex, true, group.getJsonArray(Group.USERS_TO_ADD), null);
            grantMemberships(groupVertex, false, group.getJsonArray(User.GROUPS_TO_ADD), null);
            grantPermissions(groupVertex, group.getJsonArray(Permission.PERMISSIONS_TO_ADD), null);

            commit();
        } catch (Exception ex) {
            rollback();
            String error = "Unable to create group: " + newGroup.getGroupId();
            logger.error(error, ex);
            errors.add(error);
        }
    }

    return errors;
}

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

License:Open Source License

/**
 * Update a group node in the auth graph.
 *
 * @param group JSON object representing a group's attributes, permissions, users and memberships.
 *              Ex: {//from  w w  w. j  a v  a  2  s  .  co  m
 *                  "id": 12345,
 *                  "description": "Represents flowly users.",
 *                  "usersToRemove": [
 *                      14
 *                  ],
 *                  "groupsToAdd": [
 *                      34567
 *                  ],
 *                  "groupsToRemove": [
 *                      12343
 *                  ],
 *                  "permissionsToRemove": [
 *                      555611
 *                  ]
 *              }
 * @return an empty list or a list of validation errors based on whether the group was updated or not.
 */
@Override
public JsonArray update(JsonObject group) {
    Group updatedGroup = new Group(group);
    JsonArray errors = updatedGroup.validate(true);

    if (errors.size() == 0) {
        try {
            Vertex groupVertex = getVertex(updatedGroup.getId());
            setGroupId(groupVertex, updatedGroup, true);
            setPropertyValue(groupVertex, Schema.V_P_DESCRIPTION, updatedGroup.getDescription());

            // Update group memberships.
            redoMemberships(groupVertex, false, updatedGroup.getJsonArray(User.GROUPS_TO_ADD),
                    updatedGroup.getJsonArray(User.GROUPS_TO_REMOVE));

            // Update group users.
            redoMemberships(groupVertex, true, updatedGroup.getJsonArray(Group.USERS_TO_ADD),
                    updatedGroup.getJsonArray(Group.USERS_TO_REMOVE));

            // Update permissions.
            redoPermissions(groupVertex, group);

            commit();
        } catch (IllegalArgumentException ex) {
            rollback();
            errors.add(ex.getMessage());
            logger.error(ex);
        } catch (Exception ex) {
            rollback();
            String error = "Unable to update group: " + updatedGroup.getGroupId();
            logger.error(error, ex);
            errors.add(error);
        }
    }

    return errors;
}

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

License:Open Source License

/**
 * Create a resource node in the auth graph.
 *
 * @param resource JSON object representing the resource attributes.
 *                 Ex: {// ww  w. ja v  a2  s  . c o  m
 *                     "resourceId": "Studio",
 *                     "description": "Allows users to design and develop flowly apps."
 *                 }
 * @return an empty list or a list of validation errors based on whether the resource was created or not.
 */
@Override
public JsonArray create(JsonObject resource) {
    Resource newResource = new Resource(resource);
    JsonArray errors = newResource.validate();

    if (errors.size() == 0) {
        try {
            Vertex resourceVertex = graph.addVertex(T.label, Schema.V_RESOURCE, Schema.V_P_RESOURCE_ID,
                    newResource.getResourceId());
            setPropertyValue(resourceVertex, Schema.V_P_DESCRIPTION, newResource.getDescription());

            commit();
        } catch (Exception ex) {
            rollback();
            String error = "Unable to create resource: " + newResource.getResourceId();
            logger.error(error, ex);
            errors.add(error);
        }
    }

    return errors;
}

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

License:Open Source License

/**
 * Update the attributes of a resource in the auth graph.
 *
 * @param resource JSON object representing the resource attributes.
 *                 Ex: {/*www  .  jav  a  2 s.c o  m*/
 *                     "id": 12345,
 *                     "resourceId": "Studio",
 *                     "description": "Allows users to design and develop flowly apps."
 *                 }
 *
 * @return an empty list or a list of validation errors based on whether the resource was updated or not.
 */
@Override
public JsonArray update(JsonObject resource) {
    Resource newResource = new Resource(resource);
    JsonArray errors = newResource.validate(true);

    if (errors.size() == 0) {
        try {
            Vertex resourceVertex = getVertex(newResource.getId());
            setPropertyValue(resourceVertex, Schema.V_P_RESOURCE_ID, newResource.getResourceId());
            setPropertyValue(resourceVertex, Schema.V_P_DESCRIPTION, newResource.getDescription());

            commit();
        } catch (Exception ex) {
            rollback();
            String error = "Unable to update resource: " + newResource.getResourceId();
            logger.error(error, ex);
            errors.add(error);
        }
    }

    return errors;
}

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

License:Open Source License

/**
 * Create a user node in the auth graph.
 * If this is an internally managed user, the provided password will be hashed before storing in the graph.
 * If group memberships are specified, add user to the groups.
 * If specified, grant permissions on resources (direct edge between user and resource).
 *
 * @param user JSON object representing the user attributes, memberships and permissions.
 *             Ex: {//from w w  w  .j av  a  2  s .c  om
 *                 "userId": "aragorn",
 *                 "firstName": "First",
 *                 "lastName": "Last",
 *                 "isInternal": false,
 *                 "groupsToAdd": [
 *                     12343,
 *                     34567,
 *                     99901
 *                 ],
 *                 "permissionsToAdd": [
 *                     {
 *                         "resourceVertexId": 555611
 *                         "rwx": 7
 *                     }
 *                 ]
 *             }
 * @return an empty list or a list of validation errors based on whether the user was created or not.
 */
@Override
public JsonArray create(JsonObject user) {
    User newUser = new User(user);
    JsonArray errors = newUser.validate();

    if (errors.size() == 0) {
        try {
            Vertex userVertex = graph.addVertex(Schema.V_USER);
            setUserAttributes(userVertex, newUser, false);
            grantMemberships(userVertex, false, newUser.getGroupsToAdd(), null);
            grantPermissions(userVertex, newUser.getPermissionsToAdd(), null);

            commit();
        } catch (Exception ex) {
            rollback();
            String error = "Unable to create user: " + newUser.getUserId();
            logger.error(error, ex);
            errors.add(error);
        }
    }

    return errors;
}