Example usage for io.vertx.core.json JsonObject getString

List of usage examples for io.vertx.core.json JsonObject getString

Introduction

In this page you can find the example usage for io.vertx.core.json JsonObject getString.

Prototype

public String getString(String key) 

Source Link

Document

Get the string value with the specified key, special cases are addressed for extended JSON types Instant , byte[] and Enum which can be converted to String.

Usage

From source file:org.entcore.common.share.impl.MongoDbShareService.java

License:Open Source License

private void removeShare(String resourceId, final String shareId, List<String> removeActions, boolean isGroup,
        final Handler<Either<String, JsonObject>> handler) {
    final String shareIdAttr = isGroup ? "groupId" : "userId";
    final List<String> actions = findRemoveActions(removeActions);
    QueryBuilder query = QueryBuilder.start("_id").is(resourceId);
    JsonObject keys = new JsonObject().put("shared", 1);
    final JsonObject q = MongoQueryBuilder.build(query);
    mongo.findOne(collection, q, keys, new Handler<Message<JsonObject>>() {
        @Override//from  www  .  j  a  v a  2s  .  c  om
        public void handle(Message<JsonObject> event) {
            if ("ok".equals(event.body().getString("status")) && event.body().getJsonObject("result") != null) {
                JsonArray actual = event.body().getJsonObject("result").getJsonArray("shared",
                        new fr.wseduc.webutils.collections.JsonArray());
                JsonArray shared = new fr.wseduc.webutils.collections.JsonArray();
                for (int i = 0; i < actual.size(); i++) {
                    JsonObject s = actual.getJsonObject(i);
                    String id = s.getString(shareIdAttr);
                    if (shareId.equals(id)) {
                        if (actions != null) {
                            for (String action : actions) {
                                s.remove(action);
                            }
                            if (s.size() > 1) {
                                shared.add(s);
                            }
                        }
                    } else {
                        shared.add(s);
                    }
                }
                MongoUpdateBuilder updateQuery = new MongoUpdateBuilder().set("shared", shared);
                mongo.update(collection, q, updateQuery.build(), new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> res) {
                        handler.handle(Utils.validResult(res));
                    }
                });
            } else {
                handler.handle(new Either.Left<String, JsonObject>("Resource not found."));
            }
        }
    });
}

From source file:org.entcore.common.share.Shareable.java

License:Open Source License

default void notifyShare(final HttpServerRequest request, final EventBus eb, final String resource,
        final UserInfos user, JsonArray sharedArray, final String notificationName, final JsonObject params,
        final String resourceNameAttribute) {
    final List<String> recipients = new ArrayList<>();
    final AtomicInteger remaining = new AtomicInteger(sharedArray.size());
    for (Object j : sharedArray) {
        JsonObject json = (JsonObject) j;
        String userId = json.getString("userId");
        if (userId != null) {
            recipients.add(userId);/*from ww w  .  j a va  2s .c o m*/
            remaining.getAndDecrement();
        } else {
            String groupId = json.getString("groupId");
            if (groupId != null) {
                UserUtils.findUsersInProfilsGroups(groupId, eb, user.getUserId(), false,
                        new Handler<JsonArray>() {
                            @Override
                            public void handle(JsonArray event) {
                                if (event != null) {
                                    for (Object o : event) {
                                        if (!(o instanceof JsonObject))
                                            continue;
                                        JsonObject j = (JsonObject) o;
                                        String id = j.getString("id");
                                        recipients.add(id);
                                    }
                                }
                                if (remaining.decrementAndGet() < 1) {
                                    sendNotify(request, resource, user, recipients, notificationName, params,
                                            resourceNameAttribute);
                                }
                            }
                        });
            }
        }
    }
    if (remaining.get() < 1) {
        sendNotify(request, resource, user, recipients, notificationName, params, resourceNameAttribute);
    }
}

From source file:org.entcore.common.sql.SqlResult.java

License:Open Source License

private static Either<String, JsonArray> jsonToEither(JsonObject body) {
    if ("ok".equals(body.getString("status"))) {
        return new Either.Right<>(transform(body));
    } else {/*from w  w  w  .  jav  a2s.c om*/
        return new Either.Left<>(body.getString("message", ""));
    }
}

From source file:org.entcore.common.sql.SqlResult.java

License:Open Source License

private static Either<String, JsonObject> validRows(JsonObject body) {
    if ("ok".equals(body.getString("status"))) {
        long rows = body.getLong("rows", 0l);
        JsonObject result = new JsonObject();
        if (rows > 0) {
            result.put("rows", rows);
        }/*from ww w  .j a v  a  2s  .  c  om*/
        return new Either.Right<>(result);
    } else {
        return new Either.Left<>(body.getString("message", ""));
    }
}

From source file:org.entcore.common.sql.SqlResult.java

License:Open Source License

private static void parseShared(JsonObject j) {
    Map<String, JsonObject> shared = new HashMap<>();
    JsonArray a = new fr.wseduc.webutils.collections.JsonArray();
    JsonArray s = new fr.wseduc.webutils.collections.JsonArray(j.getString("shared"));
    JsonArray m = new fr.wseduc.webutils.collections.JsonArray(j.getString("groups"));
    for (Object o : s) {
        if (o == null || !(o instanceof JsonObject))
            continue;
        JsonObject json = (JsonObject) o;
        String member = json.getString("member_id");
        String action = json.getString("action");
        if (member != null && action != null) {
            if (shared.containsKey(member)) {
                shared.get(member).put(action, true);
            } else {
                JsonObject sj = new JsonObject().put(action, true);
                if (m.contains(member)) {
                    sj.put("groupId", member);
                } else {
                    sj.put("userId", member);
                }//from   w  w  w. j a  v a  2  s .c  om
                shared.put(member, sj);
                a.add(sj);
            }
        }
    }
    j.remove("groups");
    j.put("shared", a);
}

From source file:org.entcore.common.storage.impl.FileStorage.java

License:Open Source License

@Override
public void sendFile(String id, String downloadName, HttpServerRequest request, boolean inline,
        JsonObject metadata, Handler<AsyncResult<Void>> resultHandler) {
    final HttpServerResponse resp = request.response();
    try {/* ww  w  .  j  a  v a  2s.  co  m*/
        final String path = getPath(id);
        if (!inline) {
            String name = FileUtils.getNameWithExtension(downloadName, metadata);
            resp.putHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
        }
        ETag.addHeader(resp, id);
        if (metadata != null && metadata.getString("content-type") != null) {
            resp.putHeader("Content-Type", metadata.getString("content-type"));
        }
        if (resultHandler != null) {
            resp.sendFile(path, resultHandler);
        } else {
            resp.sendFile(path, ar -> {
                if (ar.failed() && !request.response().ended()) {
                    Renders.notFound(request);
                }
            });
        }
    } catch (FileNotFoundException e) {
        resp.setStatusCode(404).setStatusMessage("Not Found").end();
        if (resultHandler != null) {
            resultHandler.handle(new DefaultAsyncResult<>((Void) null));
        }
        log.warn(e.getMessage(), e);
    }
}

From source file:org.entcore.common.storage.impl.GridfsStorage.java

License:Open Source License

@Override
public void writeFsFile(final String id, final String filePath, final Handler<JsonObject> handler) {
    if (id == null || id.trim().isEmpty() || filePath == null || filePath.trim().isEmpty()
            || filePath.endsWith(File.separator)) {
        handler.handle(new JsonObject().put("status", "error").put("message", "invalid.parameter"));
        return;//from   ww w.  j a  v a2  s. c  o m
    }
    final String filename = filePath.contains(File.separator)
            ? filePath.substring(filePath.lastIndexOf(File.separator) + 1)
            : filePath;
    final String contentType = getContentType(filePath);
    vertx.fileSystem().props(filePath, new Handler<AsyncResult<FileProps>>() {
        @Override
        public void handle(AsyncResult<FileProps> event) {
            if (event.succeeded()) {
                final long fileSize = event.result().size();
                vertx.fileSystem().open(filePath, new OpenOptions(), new Handler<AsyncResult<AsyncFile>>() {
                    @Override
                    public void handle(AsyncResult<AsyncFile> event) {
                        if (event.succeeded()) {
                            final AsyncFile asyncFile = event.result();
                            int nbChunks = (int) Math.ceil(fileSize / BUFFER_SIZE);
                            final Handler[] handlers = new Handler[nbChunks + 1];

                            handlers[handlers.length - 1] = new Handler<AsyncResult<Buffer>>() {
                                @Override
                                public void handle(AsyncResult<Buffer> asyncResult) {
                                    if (asyncResult.failed()) {
                                        handler.handle(new JsonObject().put("status", "error").put("message",
                                                asyncResult.cause().getMessage()));
                                        return;
                                    }
                                    Buffer buff = asyncResult.result();
                                    saveChunk(id, buff, handlers.length - 1, contentType, filename, fileSize,
                                            handler);
                                    asyncFile.close();
                                }
                            };

                            for (int i = nbChunks - 1; i >= 0; i--) {
                                final int j = i;
                                handlers[i] = new Handler<AsyncResult<Buffer>>() {
                                    @Override
                                    public void handle(AsyncResult<Buffer> asyncResult) {
                                        if (asyncResult.failed()) {
                                            handler.handle(new JsonObject().put("status", "error")
                                                    .put("message", asyncResult.cause().getMessage()));
                                            return;
                                        }
                                        Buffer buff = asyncResult.result();
                                        saveChunk(id, buff, j, contentType, filename, fileSize,
                                                new Handler<JsonObject>() {
                                                    @Override
                                                    public void handle(JsonObject message) {
                                                        if ("ok".equals(message.getString("status"))) {
                                                            asyncFile.read(Buffer.buffer((int) BUFFER_SIZE), 0,
                                                                    (j + 1) * BUFFER_SIZE, (int) BUFFER_SIZE,
                                                                    handlers[j + 1]);
                                                        } else {
                                                            handler.handle(message);
                                                        }
                                                    }
                                                });
                                    }
                                };
                            }

                            asyncFile.read(Buffer.buffer((int) BUFFER_SIZE), 0, 0, (int) BUFFER_SIZE,
                                    handlers[0]);

                        } else {
                            handler.handle(new JsonObject().put("status", "error").put("message",
                                    event.cause().getMessage()));
                        }
                    }
                });
            } else {
                handler.handle(
                        new JsonObject().put("status", "error").put("message", event.cause().getMessage()));
            }
        }
    });
}

From source file:org.entcore.common.storage.impl.GridfsStorage.java

License:Open Source License

private static void gridfsSendChunkFile(final String id, final String downloadName, final EventBus eb,
        final String gridfsAddress, final HttpServerResponse response, final boolean inline,
        final JsonObject metadata, final Handler<AsyncResult<Void>> resultHandler) {
    response.setChunked(true);//w  w  w  . j a va2  s .c om
    gridfsReadChunkFile(id, eb, gridfsAddress, response, new Handler<Chunk>() {
        @Override
        public void handle(Chunk chunk) {
            if (chunk == null) {
                response.setStatusCode(404).setStatusMessage("Not Found").end();
                if (resultHandler != null) {
                    resultHandler.handle(new DefaultAsyncResult<>((Void) null));
                }
                return;
            }
            if (chunk.eof()) {
                response.end();
                if (resultHandler != null) {
                    resultHandler.handle(new DefaultAsyncResult<>((Void) null));
                }
                return;
            }
            if (chunk.n == 0) {
                if (!inline) {
                    String name = fr.wseduc.swift.utils.FileUtils.getNameWithExtension(downloadName, metadata);
                    response.putHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
                } else {
                    ETag.addHeader(response, id);
                }
                if (metadata != null && metadata.getString("content-type") != null) {
                    response.putHeader("Content-Type", metadata.getString("content-type"));
                }
            }

            response.write(chunk.data);
        }
    });
}

From source file:org.entcore.common.storage.impl.MongoDBApplicationStorage.java

License:Open Source License

@Override
public void getInfo(final String fileId, final Handler<AsyncResult<FileInfos>> handler) {
    final JsonObject query = new JsonObject().put(mapping.getString("file", "file"), fileId);
    mongo.findOne(collection, query, keys, new Handler<Message<JsonObject>>() {
        @Override//from   w ww.  j  ava 2 s. c  o m
        public void handle(Message<JsonObject> event) {
            if ("ok".equals(event.body().getString("status"))) {
                JsonObject res = event.body().getJsonObject("result");
                if (res != null) {
                    final FileInfos fi = new FileInfos();
                    fi.setApplication(application);
                    fi.setId(fileId);
                    fi.setName(res.getString(mapping.getString("title", "title")));
                    fi.setOwner(res.getString(mapping.getString("owner", "owner")));
                    handler.handle(new DefaultAsyncResult<>(fi));
                } else {
                    handler.handle(new DefaultAsyncResult<>((FileInfos) null));
                }
            } else {
                handler.handle(new DefaultAsyncResult<FileInfos>(
                        new StorageException(event.body().getString("message"))));
            }
        }
    });
}

From source file:org.entcore.common.storage.impl.PostgresqlApplicationStorage.java

License:Open Source License

protected void getInfoProcess(final String fileId, final Handler<AsyncResult<FileInfos>> handler) {
    sql.prepared(getInfoQuery(), new fr.wseduc.webutils.collections.JsonArray().add(fileId),
            new Handler<Message<JsonObject>>() {
                @Override//from w w  w.  j a  va  2s. com
                public void handle(Message<JsonObject> event) {
                    Either<String, JsonArray> r = validResult(event);
                    if (r.isRight()) {
                        final JsonArray result = r.right().getValue();
                        if (result.size() == 1) {
                            final JsonObject res = result.getJsonObject(0);
                            final FileInfos fi = new FileInfos();
                            fi.setApplication(application);
                            fi.setId(fileId);
                            fi.setName(res.getString(mapping.getString("name", "name")));
                            fi.setOwner(res.getString(mapping.getString("owner", "owner")));
                            fi.setSize(res.getInteger(mapping.getString("size", "size")));
                            handler.handle(new DefaultAsyncResult<>(fi));
                        } else {
                            handler.handle(new DefaultAsyncResult<>((FileInfos) null));
                        }
                    } else {
                        handler.handle(
                                new DefaultAsyncResult<FileInfos>(new StorageException(r.left().getValue())));
                    }
                }
            });
}