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

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

Introduction

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

Prototype

public Boolean getBoolean(String key, Boolean def) 

Source Link

Document

Like #getBoolean(String) but specifying a default value to return if there is no entry.

Usage

From source file:org.entcore.blog.services.impl.DefaultPostService.java

License:Open Source License

private boolean userIsManager(UserInfos user, JsonObject res) {
    if (res != null && res.getJsonArray("shared") != null) {
        for (Object o : res.getJsonArray("shared")) {
            if (!(o instanceof JsonObject))
                continue;
            JsonObject json = (JsonObject) o;
            return json != null && json.getBoolean("manager", false)
                    && (user.getUserId().equals(json.getString("userId"))
                            || user.getGroupsIds().contains(json.getString("groupId")));
        }//from  w  ww  .j av  a  2  s.  c  o m
    }
    return false;
}

From source file:org.entcore.common.elasticsearch.ElasticSearch.java

License:Open Source License

public void init(Vertx vertx, JsonObject config) {
    this.vertx = vertx;
    JsonArray serverUris = config.getJsonArray("server-uris");
    String serverUri = config.getString("server-uri");
    if (serverUris == null && serverUri != null) {
        serverUris = new fr.wseduc.webutils.collections.JsonArray().add(serverUri);
    }/*from   w  w w .ja  v  a2s . co  m*/

    if (serverUris != null) {
        try {
            URI[] uris = new URI[serverUris.size()];
            for (int i = 0; i < serverUris.size(); i++) {
                uris[i] = new URI(serverUris.getString(i));
            }
            init(uris, vertx, config.getInteger("poolSize", 16), config.getBoolean("keepAlive", true), config);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    } else {
        log.error("Invalid ElasticSearch URI");
    }
}

From source file:org.entcore.common.http.filter.CsrfFilter.java

License:Open Source License

private void loadIgnoredMethods() {
    ignoreBinding = new HashSet<>();
    InputStream is = CsrfFilter.class.getClassLoader()
            .getResourceAsStream(IgnoreCsrf.class.getSimpleName() + ".json");
    if (is != null) {
        BufferedReader r = null;/*from  ww w .j a va2s  .  co m*/
        try {
            r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line;
            while ((line = r.readLine()) != null) {
                final JsonObject ignore = new JsonObject(line);
                if (ignore.getBoolean("ignore", false)) {
                    for (Binding binding : bindings) {
                        if (binding != null
                                && ignore.getString("method", "").equals(binding.getServiceMethod())) {
                            ignoreBinding.add(binding);
                            break;
                        }
                    }
                }
            }
        } catch (IOException | DecodeException e) {
            log.error("Unable to load ignoreCsrf", e);
        } finally {
            if (r != null) {
                try {
                    r.close();
                } catch (IOException e) {
                    log.error("Close inputstream error", e);
                }
            }
        }
    }
}

From source file:org.entcore.common.neo4j.Neo4j.java

License:Open Source License

public void init(Vertx vertx, JsonObject config) {
    this.eb = Server.getEventBus(vertx);
    JsonArray serverUris = config.getJsonArray("server-uris");
    String serverUri = config.getString("server-uri");
    if (serverUris == null && serverUri != null) {
        serverUris = new fr.wseduc.webutils.collections.JsonArray().add(serverUri);
    }// w w  w .  j  a  v a2s .  co  m

    if (serverUris != null) {
        try {
            URI[] uris = new URI[serverUris.size()];
            for (int i = 0; i < serverUris.size(); i++) {
                uris[i] = new URI(serverUris.getString(i));
            }
            database = new Neo4jRest(uris, config.getBoolean("slave-readonly", false), vertx,
                    config.getLong("checkDelay", 3000l), config.getInteger("poolSize", 16),
                    config.getBoolean("keepAlive", true), config);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    } else {
        log.error("Invalid Neo4j URI");
    }
}

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));
        }/*from ww  w  .  jav a 2s.co  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.TimelineNotificationsLoader.java

License:Open Source License

private void processNotification(final String path, final String type) {
    final File pathFile = new File(path);
    final String notificationName = pathFile.getName().substring(0, pathFile.getName().lastIndexOf('.'));
    final String propsFilePath = path.substring(0, path.lastIndexOf(".")) + ".json";
    //final String templatePath = pathFile.getAbsolutePath().substring(pathFile.getAbsolutePath().indexOf("notify/"));

    vertx.fileSystem().readFile(path, new Handler<AsyncResult<Buffer>>() {
        public void handle(AsyncResult<Buffer> templateAsync) {
            if (templateAsync.failed()) {
                log.error("Cannot read template at path : " + path);
                return;
            }//from w ww . jav a  2  s.  com

            final String fullName = (type + "." + notificationName).toLowerCase();

            //Default values
            final JsonObject notificationJson = new JsonObject().put("type", type.toUpperCase())
                    .put("event-type", notificationName.toUpperCase())
                    .put("app-name", Config.getConf().getString("app-name"))
                    .put("app-address", Config.getConf().getString("app-address", "/"))
                    .put("template", templateAsync.result().toString())
                    .put("defaultFrequency", Frequencies.defaultFrequency())
                    .put("restriction", Restrictions.defaultRestriction()).put("push-notif", false);

            vertx.fileSystem().exists(propsFilePath, new Handler<AsyncResult<Boolean>>() {
                public void handle(AsyncResult<Boolean> ar) {
                    if (ar.succeeded()) {
                        if (ar.result()) {
                            vertx.fileSystem().readFile(propsFilePath, new Handler<AsyncResult<Buffer>>() {
                                public void handle(AsyncResult<Buffer> ar) {
                                    if (ar.succeeded()) {
                                        JsonObject props = new JsonObject(ar.result().toString("UTF-8"));

                                        // Overrides
                                        registerNotification(fullName,
                                                notificationJson
                                                        .put("defaultFrequency",
                                                                props.getString("default-frequency",
                                                                        notificationJson
                                                                                .getString("defaultFrequency")))
                                                        .put("restriction",
                                                                props.getString("restrict",
                                                                        notificationJson
                                                                                .getString("restriction")))
                                                        .put("push-notif",
                                                                props.getBoolean("push-notif", false)));
                                    } else {
                                        registerNotification(fullName, notificationJson);
                                    }
                                }
                            });
                        } else {
                            registerNotification(fullName, notificationJson);
                        }
                    }
                }
            });
        }
    });

}

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. j a v a2  s.c o 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 w w.  j a  v a  2 s .  c  om

            if (continuation != null)
                continuation.handle(null);
        }
    }));
}

From source file:org.entcore.directory.controllers.StructureController.java

License:Open Source License

@Put("structure/:id/profile/block")
@SecuredAction(value = "", type = ActionType.RESOURCE)
@ResourceFilter(AdminStructureFilter.class)
public void blockUsers(final HttpServerRequest request) {
    RequestUtils.bodyToJson(request, new Handler<JsonObject>() {
        @Override/*from ww  w.j  ava  2 s  .c  o  m*/
        public void handle(JsonObject json) {
            final String structureId = request.params().get("id");
            final String profile = json.getString("profile");
            final boolean block = json.getBoolean("block", true);
            structureService.blockUsers(structureId, profile, block, new Handler<JsonObject>() {
                @Override
                public void handle(JsonObject r) {
                    if ("ok".equals(r.getString("status"))) {
                        request.response().end();
                        JsonArray usersId = r.getJsonArray("result").getJsonObject(0).getJsonArray("usersId");
                        for (Object userId : usersId) {
                            UserUtils.deletePermanentSession(eb, (String) userId, null, new Handler<Boolean>() {
                                @Override
                                public void handle(Boolean event) {
                                    if (!event) {
                                        log.error("Error delete permanent session with userId : " + userId);
                                    }
                                }
                            });
                            UserUtils.deleteCacheSession(eb, (String) userId, new Handler<Boolean>() {
                                @Override
                                public void handle(Boolean event) {
                                    if (!event) {
                                        log.error("Error delete cache session with userId : " + userId);
                                    }
                                }
                            });
                        }
                    } else {
                        badRequest(request);
                    }
                }
            });
        }
    });
}

From source file:org.entcore.directory.controllers.UserBookController.java

License:Open Source License

@Override
public void init(final Vertx vertx, JsonObject config, RouteMatcher rm,
        Map<String, fr.wseduc.webutils.security.SecuredAction> securedActions) {
    pathPrefix = "/userbook";
    super.init(vertx, config, rm, securedActions);
    this.neo = new Neo(vertx, Server.getEventBus(vertx), log);
    this.config = config;
    userBookData = config.getJsonObject("user-book-data");
    final HttpClientOptions options = new HttpClientOptions().setDefaultHost(config.getString("workspace-url"))
            .setDefaultPort(config.getInteger("workspace-port")).setMaxPoolSize(16).setKeepAlive(false);
    client = vertx.createHttpClient(options);
    getWithRegEx(".*", "proxyDocument");
    eventStore = EventStoreFactory.getFactory().getEventStore(ANNUAIRE_MODULE);
    if (config.getBoolean("activation-welcome-message", false)) {
        activationWelcomeMessage = new HashMap<>();
        String assetsPath = (String) vertx.sharedData().getLocalMap("server").get("assetPath");
        Map<String, String> skins = vertx.sharedData().getLocalMap("skins");
        if (skins != null) {
            activationWelcomeMessage = new HashMap<>();
            for (final Map.Entry<String, String> e : skins.entrySet()) {
                String path = assetsPath + "/assets/themes/" + e.getValue() + "/template/directory/welcome/";
                vertx.fileSystem().readDir(path, new Handler<AsyncResult<List<String>>>() {
                    @Override/*from  w ww  .j ava 2s  . co  m*/
                    public void handle(AsyncResult<List<String>> event) {
                        if (event.succeeded()) {
                            final Map<String, String> messages = new HashMap<>();
                            activationWelcomeMessage.put(e.getKey(), messages);
                            for (final String file : event.result()) {
                                vertx.fileSystem().readFile(file, new Handler<AsyncResult<Buffer>>() {
                                    @Override
                                    public void handle(AsyncResult<Buffer> event) {
                                        if (event.succeeded()) {
                                            String filename = file.substring(
                                                    file.lastIndexOf(File.separator) + 1,
                                                    file.lastIndexOf("."));
                                            messages.put(filename, event.result().toString());
                                            if (log.isDebugEnabled()) {
                                                log.debug("Load welcome message " + file + " as " + filename);
                                            }
                                        }
                                    }
                                });
                            }
                        }
                    }
                });
            }
        }
    }
}