List of usage examples for io.vertx.core.json JsonObject getLong
public Long getLong(String key)
From source file:org.entcore.archive.controllers.ArchiveController.java
License:Open Source License
@Override public void init(Vertx vertx, final JsonObject config, RouteMatcher rm, Map<String, fr.wseduc.webutils.security.SecuredAction> securedActions) { super.init(vertx, config, rm, securedActions); String exportPath = config.getString("export-path", System.getProperty("java.io.tmpdir")); Set<String> expectedExports = new HashSet<>(); final JsonArray e = config.getJsonArray("expected-exports"); for (Object o : e) { if (o instanceof String) { expectedExports.add((String) o); }//from w w w . jav a 2 s.com } LocalMap<Object, Object> server = vertx.sharedData().getLocalMap("server"); Boolean cluster = (Boolean) server.get("cluster"); final Map<String, Long> userExport = MapFactory.getSyncClusterMap(Archive.ARCHIVES, vertx); EmailFactory emailFactory = new EmailFactory(vertx, config); EmailSender notification = config.getBoolean("send.export.email", false) ? emailFactory.getSender() : null; storage = new StorageFactory(vertx, config).getStorage(); exportService = new FileSystemExportService(vertx.fileSystem(), eb, exportPath, expectedExports, notification, storage, userExport, new TimelineHelper(vertx, eb, config)); eventStore = EventStoreFactory.getFactory().getEventStore(Archive.class.getSimpleName()); Long periodicUserClear = config.getLong("periodicUserClear"); if (periodicUserClear != null) { vertx.setPeriodic(periodicUserClear, new Handler<Long>() { @Override public void handle(Long event) { final long limit = System.currentTimeMillis() - config.getLong("userClearDelay", 3600000l); Set<Map.Entry<String, Long>> entries = new HashSet<>(userExport.entrySet()); for (Map.Entry<String, Long> e : entries) { if (e.getValue() == null || e.getValue() < limit) { userExport.remove(e.getKey()); } } } }); } }
From source file:org.entcore.common.neo4j.Neo4jRest.java
License:Open Source License
@Override public void executeBatch(JsonArray queries, final Handler<JsonObject> handler) { JsonArray body = new fr.wseduc.webutils.collections.JsonArray(); int i = 0;//from w w w .j a va2s.c om for (Object q : queries) { JsonObject query = new JsonObject().put("method", "POST").put("to", "/cypher") .put("body", (JsonObject) q).put("id", i++); body.add(query); } logger.debug(body.encode()); try { sendRequest("/batch", body, new Handler<HttpClientResponse>() { @Override public void handle(final HttpClientResponse resp) { resp.bodyHandler(new Handler<Buffer>() { @Override public void handle(Buffer b) { logger.debug(b.toString()); if (resp.statusCode() != 404 && resp.statusCode() != 500) { JsonArray json = new fr.wseduc.webutils.collections.JsonArray(b.toString("UTF-8")); JsonArray out = new fr.wseduc.webutils.collections.JsonArray(); for (Object j : json) { JsonObject qr = (JsonObject) j; out.add(new JsonObject() .put("result", transformJson(qr.getJsonObject("body", new JsonObject()))) .put("idx", qr.getLong("id"))); } handler.handle(new JsonObject().put("results", out)); } else { handler.handle(new JsonObject().put("message", resp.statusMessage() + " : " + b.toString())); } } }); } }); } catch (Neo4jConnectionException e) { ExceptionUtils.exceptionToJson(e); } }
From source file:org.entcore.common.notification.TimelineHelper.java
License:Open Source License
public void notifyTimeline(final HttpServerRequest req, final String notificationName, UserInfos sender, final List<String> recipients, String resource, String subResource, final JsonObject params, final boolean disableAntiFlood) { notificationsLoader.getNotification(notificationName, notification -> { JsonArray r = new fr.wseduc.webutils.collections.JsonArray(); for (String userId : recipients) { r.add(new JsonObject().put("userId", userId).put("unread", 1)); }/* w w w .j a v a 2s .c o m*/ final JsonObject event = new JsonObject().put("action", "add") .put("type", notification.getString("type")) .put("event-type", notification.getString("event-type")).put("recipients", r) .put("recipientsIds", new fr.wseduc.webutils.collections.JsonArray(recipients)); if (resource != null) { event.put("resource", resource); } if (sender != null) { event.put("sender", sender.getUserId()); } if (subResource != null && !subResource.trim().isEmpty()) { event.put("sub-resource", subResource); } if (disableAntiFlood || params.getBoolean("disableAntiFlood", false)) { event.put("disableAntiFlood", true); } Long date = params.getLong("timeline-publish-date"); if (date != null) { event.put("date", new JsonObject().put("$date", date)); params.remove("timeline-publish-date"); } event.put("pushNotif", params.remove("pushNotif")); HttpServerRequest request; if (req == null) { request = new JsonHttpServerRequest(new JsonObject()); } else { request = req; } event.put("params", params).put("notificationName", notificationName).put("notification", notification) .put("request", new JsonObject().put("headers", new JsonObject().put("Host", Renders.getHost(request)) .put("X-Forwarded-Proto", Renders.getScheme(request)) .put("Accept-Language", request.headers().get("Accept-Language")))); eb.send(TIMELINE_ADDRESS, event, handlerToAsyncHandler(new Handler<Message<JsonObject>>() { public void handle(Message<JsonObject> event) { JsonObject result = event.body(); if ("error".equals(result.getString("status", "error"))) { log.error("Error in timeline notification : " + result.getString("message")); } } })); }); }
From source file:org.entcore.common.notification.TimelineHelper.java
License:Open Source License
/** * @deprecated//from w w w. j a va2s. co m * Notification system was refactored in version 1.16.1 */ @Deprecated public void notifyTimeline(HttpServerRequest request, UserInfos sender, String type, final String eventType, List<String> recipients, String resource, String subResource, String template, JsonObject params) { JsonArray r = new fr.wseduc.webutils.collections.JsonArray(); for (String userId : recipients) { r.add(new JsonObject().put("userId", userId).put("unread", 1)); } final JsonObject event = new JsonObject().put("action", "add").put("type", type) .put("event-type", eventType).put("recipients", r); if (resource != null) { event.put("resource", resource); } if (sender != null) { event.put("sender", sender.getUserId()); } if (subResource != null && !subResource.trim().isEmpty()) { event.put("sub-resource", subResource); } Long date = params.getLong("timeline-publish-date"); if (date != null) { event.put("date", new JsonObject().put("$date", date)); params.remove("timeline-publish-date"); } render.processTemplate(request, template, params, new Handler<String>() { @Override public void handle(String message) { if (message != null) { event.put("message", message); eb.send(TIMELINE_ADDRESS, event); } else { log.error("Unable to send timeline " + eventType + " notification."); } } }); }
From source file:org.entcore.common.storage.impl.FileStorage.java
License:Open Source License
@Override public void writeUploadFile(final HttpServerRequest request, final Long maxSize, final Handler<JsonObject> handler) { request.pause();/*from w w w. j av a2s .c om*/ final String id = UUID.randomUUID().toString(); final String path; final JsonObject res = new JsonObject(); try { path = getPath(id); } catch (FileNotFoundException e) { handler.handle(res.put("status", "error").put("message", "invalid.path")); log.warn(e.getMessage(), e); return; } request.setExpectMultipart(true); request.uploadHandler(new Handler<HttpServerFileUpload>() { @Override public void handle(final HttpServerFileUpload upload) { request.pause(); final JsonObject metadata = FileUtils.metadata(upload); if (validator != null) { validator.process(metadata, new JsonObject().put("maxSize", maxSize), new Handler<AsyncResult<Void>>() { @Override public void handle(AsyncResult<Void> event) { if (event.succeeded()) { doUpload(upload, metadata); } else { handler.handle(res.put("status", "error").put("message", event.cause().getMessage())); } } }); } else { doUpload(upload, metadata); } } private void doUpload(final HttpServerFileUpload upload, final JsonObject metadata) { upload.endHandler(new Handler<Void>() { @Override public void handle(Void event) { if (metadata.getLong("size") == 0l) { metadata.put("size", upload.size()); if (maxSize != null && maxSize < metadata.getLong("size", 0l)) { handler.handle(res.put("status", "error").put("message", "file.too.large")); try { fs.delete(getPath(id), new Handler<AsyncResult<Void>>() { @Override public void handle(AsyncResult<Void> event) { if (event.failed()) { log.error(event.cause().getMessage(), event.cause()); } } }); } catch (FileNotFoundException e) { log.error(e.getMessage(), e); } } } handler.handle(res.put("_id", id).put("status", "ok").put("metadata", metadata)); scanFile(path); } }); upload.exceptionHandler(new Handler<Throwable>() { @Override public void handle(Throwable event) { handler.handle(res.put("status", "error")); log.error(event.getMessage(), event); } }); upload.streamToFileSystem(path); } }); mkdirsIfNotExists(id, path, new Handler<AsyncResult<Void>>() { @Override public void handle(AsyncResult<Void> event) { if (event.succeeded()) { request.resume(); } else { handler.handle(res.put("status", "error")); log.error(event.cause().getMessage(), event.cause()); } } }); }
From source file:org.entcore.common.storage.impl.GridfsStorage.java
License:Open Source License
@Override public void stats(final Handler<AsyncResult<BucketStats>> handler) { mongoDb.command(new JsonObject().put("collStats", bucket + ".chunks").encode(), new Handler<Message<JsonObject>>() { @Override//ww w . j ava2 s . c o m public void handle(Message<JsonObject> event) { final JsonObject chunksStats = event.body().getJsonObject("result"); if ("ok".equals(event.body().getString("status")) && chunksStats != null) { final BucketStats bucketStats = new BucketStats(); bucketStats.setStorageSize(chunksStats.getLong("size")); mongoDb.command(new JsonObject().put("collStats", bucket + ".files").encode(), new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> event) { final JsonObject filesStats = event.body().getJsonObject("result"); if ("ok".equals(event.body().getString("status")) && filesStats != null) { bucketStats.setObjectNumber(filesStats.getLong("count")); handler.handle(new DefaultAsyncResult<>(bucketStats)); } else { handler.handle(new DefaultAsyncResult<BucketStats>( new StorageException(event.body().getString("message")))); } } }); } else { handler.handle(new DefaultAsyncResult<BucketStats>( new StorageException(event.body().getString("message")))); } } }); }
From source file:org.entcore.common.validation.QuotaFileSizeValidation.java
License:Open Source License
@Override protected void validate(JsonObject metadata, JsonObject context, Handler<AsyncResult<Void>> handler) { Long maxSize = context.getLong("maxSize"); if (maxSize != null && maxSize < metadata.getLong("size", 0l)) { handler.handle(new DefaultAsyncResult<Void>(new ValidationException("file.too.large"))); } else {/*from w ww .j a v a2 s . co m*/ handler.handle(new DefaultAsyncResult<Void>((Void) null)); } }
From source file:org.entcore.conversation.controllers.ConversationController.java
License:Open Source License
@Delete("message/:id/attachment/:attachmentId") @SecuredAction(value = "", type = ActionType.RESOURCE) @ResourceFilter(MessageUserFilter.class) public void deleteAttachment(final HttpServerRequest request) { final String messageId = request.params().get("id"); final String attachmentId = request.params().get("attachmentId"); Handler<UserInfos> userInfosHandler = new Handler<UserInfos>() { public void handle(final UserInfos user) { if (user == null) { unauthorized(request);/*from w w w.jav a 2 s . co m*/ return; } conversationService.removeAttachment(messageId, attachmentId, user, new Handler<Either<String, JsonObject>>() { @Override public void handle(Either<String, JsonObject> event) { if (event.isLeft()) { badRequest(request, event.left().getValue()); return; } if (event.isRight() && event.right().getValue() == null) { badRequest(request, event.right().getValue().toString()); return; } final JsonObject result = event.right().getValue(); boolean deletionCheck = result.getBoolean("deletionCheck", false); final String fileId = result.getString("fileId"); final long fileSize = result.getLong("fileSize"); updateUserQuota(user.getUserId(), -fileSize, new Handler<Void>() { public void handle(Void v) { renderJson(request, result); } }); if (deletionCheck) { storage.removeFile(fileId, new Handler<JsonObject>() { @Override public void handle(final JsonObject result) { if (!"ok".equals(result.getString("status"))) { log.error("[" + ConversationController.class.getSimpleName() + "] Error while tying to delete attachment file (_id: {" + fileId + "})"); } } }); } } }); } }; UserUtils.getUserInfos(eb, request, userInfosHandler); }
From source file:org.entcore.conversation.controllers.ConversationController.java
License:Open Source License
private void updateUserQuota(final String userId, long size, final Handler<Void> continuation) { 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, handlerToAsyncHandler(new Handler<Message<JsonObject>>() { public void handle(Message<JsonObject> reply) { JsonObject obj = reply.body(); UserUtils.addSessionAttribute(eb, userId, "storage", obj.getLong("storage"), null); if (obj.getBoolean("notify", false)) { notifyEmptySpaceIsSmall(userId); }/*w ww . j a v a 2s .co m*/ if (continuation != null) continuation.handle(null); } })); }
From source file:org.entcore.conversation.service.impl.SqlConversationService.java
License:Open Source License
@Override public void removeAttachment(String messageId, String attachmentId, UserInfos user, final Handler<Either<String, JsonObject>> result) { if (validationParamsError(user, result, messageId, attachmentId)) return;/*from w w w . j a va 2 s. c o m*/ SqlStatementsBuilder builder = new SqlStatementsBuilder(); JsonArray values = new fr.wseduc.webutils.collections.JsonArray().add(messageId).add(user.getUserId()) .add(attachmentId); String query1 = "SELECT att.* FROM " + attachmentTable + " att WHERE att.id = ?"; builder.prepared(query1, new fr.wseduc.webutils.collections.JsonArray().add(attachmentId)); String query2 = "SELECT (count(*) = 1) AS deletionCheck FROM " + attachmentTable + " att JOIN " + userMessageAttachmentTable + " uma ON uma.attachment_id = att.id " + "WHERE att.id = ? " + "GROUP BY att.id HAVING count(distinct uma.user_id) = 1 AND count(distinct uma.message_id) = 1"; builder.prepared(query2, new fr.wseduc.webutils.collections.JsonArray().add(attachmentId)); String query3 = "WITH attachment AS (" + query1 + ") " + "UPDATE " + userMessageTable + " AS um " + "SET total_quota = um.total_quota - (SELECT SUM(DISTINCT attachment.size) FROM attachment) " + "WHERE um.message_id = ? AND um.user_id = ?"; JsonArray values3 = new fr.wseduc.webutils.collections.JsonArray().add(attachmentId).add(messageId) .add(user.getUserId()); builder.prepared(query3, values3); String query4 = "DELETE FROM " + userMessageAttachmentTable + " WHERE " + "message_id = ? AND user_id = ? AND attachment_id = ?"; builder.prepared(query4, values); sql.transaction(builder.build(), SqlResult.validResultsHandler(new Handler<Either<String, JsonArray>>() { public void handle(Either<String, JsonArray> event) { if (event.isLeft()) { result.handle(new Either.Left<String, JsonObject>(event.left().getValue())); return; } else { JsonArray results = event.right().getValue(); JsonObject attachment = results.getJsonArray(0).getJsonObject(0); boolean deletionCheck = results.getJsonArray(1).size() > 0 ? results.getJsonArray(1).getJsonObject(0).getBoolean("deletioncheck", false) : false; JsonObject resultJson = new JsonObject().put("deletionCheck", deletionCheck) .put("fileId", attachment.getString("id")).put("fileSize", attachment.getLong("size")); result.handle(new Either.Right<String, JsonObject>(resultJson)); } } })); }