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:fr.wseduc.rack.controllers.RackController.java

License:Open Source License

private Handler<HttpServerFileUpload> getUploadHandler(final Buffer fileBuffer, final JsonObject metadata,
        final HttpServerRequest request) {
    return new Handler<HttpServerFileUpload>() {
        @Override/* w w w . j  a v  a 2 s  .  c o m*/
        public void handle(final HttpServerFileUpload upload) {
            upload.handler(new Handler<Buffer>() {
                @Override
                public void handle(Buffer data) {
                    fileBuffer.appendBuffer(data);
                }
            });
            upload.endHandler(new Handler<Void>() {
                @Override
                public void handle(Void v) {
                    metadata.put("name", upload.name());
                    metadata.put("filename", upload.filename());
                    metadata.put("content-type", upload.contentType());
                    metadata.put("content-transfer-encoding", upload.contentTransferEncoding());
                    metadata.put("charset", upload.charset());
                    metadata.put("size", upload.size());
                    if (metadata.getLong("size", 0l).equals(0l)) {
                        metadata.put("size", fileBuffer.length());
                    }

                    if (storage.getValidator() != null) {
                        request.pause();
                        storage.getValidator().process(metadata, new JsonObject(),
                                new Handler<AsyncResult<Void>>() {
                                    @Override
                                    public void handle(AsyncResult<Void> voidAsyncResult) {
                                        if (voidAsyncResult.succeeded()) {
                                            request.resume();
                                        } else {
                                            badRequest(request, voidAsyncResult.cause().getMessage());
                                            return;
                                        }
                                    }
                                });
                    }
                }
            });
        }
    };
}

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

License:Open Source License

/**
 * Returns a rack document./*from  w w  w. ja  v a2 s. c om*/
 * @param request Client request containing the id of the document.
 */
@Get("/get/:id")
@SecuredAction(value = owner, type = ActionType.RESOURCE)
public void getRack(final HttpServerRequest request) {
    final String thumbSize = request.params().get("thumbnail");
    final String id = request.params().get("id");
    rackService.getRack(id, new Handler<Either<String, JsonObject>>() {
        @Override
        public void handle(Either<String, JsonObject> event) {
            if (event.isRight()) {
                JsonObject result = event.right().getValue();
                String file;

                if (thumbSize != null && !thumbSize.trim().isEmpty()) {
                    file = result.getJsonObject("thumbnails", new JsonObject()).getString(thumbSize,
                            result.getString("file"));
                } else {
                    file = result.getString("file");
                }

                if (file != null && !file.trim().isEmpty()) {
                    boolean inline = inlineDocumentResponse(result, request.params().get("application"));
                    if (inline && ETag.check(request, file)) {
                        notModified(request, file);
                    } else {
                        storage.sendFile(file, result.getString("name"), request, inline,
                                result.getJsonObject("metadata"));
                    }
                } else {
                    notFound(request);
                    request.response().setStatusCode(404).end();
                }

            } else {
                JsonObject error = new JsonObject().put("error", event.left().getValue());
                Renders.renderJson(request, error, 400);
            }
        }
    });
}

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

License:Open Source License

private void getVisibleRackUsers(final HttpServerRequest request, final Handler<JsonObject> handler) {
    final String customReturn = "MATCH visibles-[:IN]->(:Group)-[:AUTHORIZED]->(:Role)-[:AUTHORIZE]->(a:Action) "
            + "WHERE has(a.name) AND a.name={action} AND NOT has(visibles.activationCode) "
            + "RETURN distinct visibles.id as id, visibles.displayName as username, visibles.lastName as name, HEAD(visibles.profiles) as profile "
            + "ORDER BY name ";
    final JsonObject params = new JsonObject().put("action",
            "fr.wseduc.rack.controllers.RackController|listRack");
    final String queryGroups = "RETURN distinct profileGroup.id as id, profileGroup.name as name, "
            + "profileGroup.groupDisplayName as groupDisplayName, profileGroup.structureName as structureName "
            + "ORDER BY name ";
    UserUtils.findVisibleProfilsGroups(eb, request, queryGroups, new JsonObject(), visibleGroups -> {
        for (Object u : visibleGroups) {
            if (!(u instanceof JsonObject))
                continue;
            JsonObject group = (JsonObject) u;
            UserUtils.groupDisplayName(group, I18n.acceptLanguage(request));
        }/*w  ww.  j  av  a  2 s  .c  om*/
        findVisibleUsers(eb, request, false, customReturn, params, visibleUsers -> {
            JsonObject visibles = new JsonObject().put("groups", visibleGroups).put("users", visibleUsers);
            handler.handle(visibles);
        });
    });
}

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

License:Open Source License

@Get("/users/group/:groupId")
@SecuredAction(value = "", type = ActionType.AUTHENTICATED)
public void listUsersInGroup(final HttpServerRequest request) {
    final String groupId = request.params().get("groupId");
    final String customReturn = "MATCH visibles-[:IN]->(:Group {id : {groupId}}) "
            + "RETURN distinct visibles.id as id, visibles.displayName as username, visibles.lastName as name, HEAD(visibles.profiles) as profile "
            + "ORDER BY name ";
    final JsonObject params = new JsonObject().put("groupId", groupId);

    UserUtils.findVisibleUsers(eb, request, false, false, null, customReturn, params, new Handler<JsonArray>() {
        @Override// w  w  w.  j  a v  a  2  s  .  com
        public void handle(JsonArray users) {
            renderJson(request, users);
        }
    });

}

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

License:Open Source License

private void getUserQuota(String userId, final Handler<JsonObject> handler) {
    JsonObject message = new JsonObject();
    message.put("action", "getUserQuota");
    message.put("userId", userId);

    eb.send(QUOTA_BUS_ADDRESS, message, new Handler<AsyncResult<Message<JsonObject>>>() {
        @Override/*from  www  . ja  v  a  2 s.  co  m*/
        public void handle(AsyncResult<Message<JsonObject>> reply) {
            handler.handle(reply.result().body());
        }
    });
}

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

License:Open Source License

private void updateUserQuota(final String userId, long size) {
    JsonObject message = new JsonObject();
    message.put("action", "updateUserQuota");
    message.put("userId", userId);
    message.put("size", size);
    message.put("threshold", threshold);

    eb.send(QUOTA_BUS_ADDRESS, message, new Handler<AsyncResult<Message<JsonObject>>>() {
        @Override//from   w  ww  .j  a  va2  s . co m
        public void handle(AsyncResult<Message<JsonObject>> reply) {
            JsonObject obj = reply.result().body();
            UserUtils.addSessionAttribute(eb, userId, "storage", obj.getLong("storage"), null);
            if (obj.getBoolean("notify", false)) {
                notifyEmptySpaceIsSmall(userId);
            }
        }
    });

}

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

License:Open Source License

private void notifyEmptySpaceIsSmall(String userId) {
    List<String> recipients = new ArrayList<>();
    recipients.add(userId);/*from  www  . j av a2 s. c om*/
    notification.notifyTimeline(new JsonHttpServerRequest(new JsonObject()), "rack.storage", null, recipients,
            new JsonObject());
}

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

License:Open Source License

private void deleteFile(final HttpServerRequest request, final String owner) {
    final String id = request.params().get("id");
    rackService.getRack(id, new Handler<Either<String, JsonObject>>() {
        @Override/*w  ww.ja  va2 s .  com*/
        public void handle(Either<String, JsonObject> event) {
            if (event.isRight()) {
                final JsonObject result = event.right().getValue();

                String file = result.getString("file");
                Set<Entry<String, Object>> thumbnails = new HashSet<Entry<String, Object>>();
                if (result.containsKey("thumbnails")) {
                    thumbnails = result.getJsonObject("thumbnails").getMap().entrySet();
                }

                storage.removeFile(file, new Handler<JsonObject>() {
                    @Override
                    public void handle(JsonObject event) {
                        if (event != null && "ok".equals(event.getString("status"))) {
                            rackService.deleteRack(id, new Handler<Either<String, JsonObject>>() {
                                @Override
                                public void handle(Either<String, JsonObject> deletionEvent) {
                                    if (deletionEvent.isRight()) {
                                        JsonObject deletionResult = deletionEvent.right().getValue();
                                        long size = -1l * result.getJsonObject("metadata", new JsonObject())
                                                .getLong("size", 0l);
                                        updateUserQuota(owner, size);
                                        renderJson(request, deletionResult, 204);
                                    } else {
                                        badRequest(request, deletionEvent.left().getValue());
                                    }
                                }
                            });
                        } else {
                            renderError(request, event);
                        }
                    }
                });

                //Delete thumbnails
                for (final Entry<String, Object> thumbnail : thumbnails) {
                    storage.removeFile(thumbnail.getValue().toString(), new Handler<JsonObject>() {
                        @Override
                        public void handle(JsonObject event) {
                            if (event == null || !"ok".equals(event.getString("status"))) {
                                logger.error("[gridfsRemoveFile] Error while deleting thumbnail " + thumbnail);
                            }
                        }
                    });
                }

            } else {
                JsonObject error = new JsonObject().put("error", event.left().getValue());
                Renders.renderJson(request, error, 400);
            }
        }
    });
}

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

License:Open Source License

private void addAfterUpload(final JsonObject uploaded, final JsonObject doc, String name, String application,
        final List<String> thumbs, final Handler<Message<JsonObject>> handler) {
    //Write additional fields in the document
    doc.put("name", getOrElse(name, uploaded.getJsonObject("metadata").getString("filename"), false));
    doc.put("metadata", uploaded.getJsonObject("metadata"));
    doc.put("file", uploaded.getString("_id"));
    doc.put("application", getOrElse(application, WORKSPACE_NAME));
    //Save document to mongo
    mongo.save(collection, doc, new Handler<Message<JsonObject>>() {
        @Override/* w  ww .j  a v a 2s  .  c o  m*/
        public void handle(Message<JsonObject> res) {
            if ("ok".equals(res.body().getString("status"))) {
                Long size = doc.getJsonObject("metadata", new JsonObject()).getLong("size", 0l);
                updateUserQuota(doc.getString("to"), size);
                createThumbnailIfNeeded(collection, uploaded, res.body().getString("_id"), null, thumbs);
            }
            if (handler != null) {
                handler.handle(res);
            }
        }
    });
}

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  www  . j  ava 2s .co  m*/
                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());
                }
            }
        });
    }
}