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, String def) 

Source Link

Document

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

Usage

From source file:org.apache.servicecomb.config.client.MemberDiscovery.java

License:Apache License

public void refreshMembers(JsonObject members) {
    List<String> newServerAddresses = new ArrayList<>();
    members.getJsonArray("instances").forEach(m -> {
        JsonObject instance = (JsonObject) m;
        if ("UP".equals(instance.getString("status", "UP"))) {
            String endpoint = instance.getJsonArray("endpoints").getString(0);
            String scheme = instance.getBoolean("isHttps", false) ? "https" : "http";
            newServerAddresses.add(scheme + SCHEMA_SEPRATOR
                    + endpoint.substring(endpoint.indexOf(SCHEMA_SEPRATOR) + SCHEMA_SEPRATOR.length()));
        }// w  ww.  ja  va  2 s . c  om
    });

    synchronized (lock) {
        this.configServerAddresses.clear();
        this.configServerAddresses.addAll(newServerAddresses);
        Collections.shuffle(this.configServerAddresses);
    }
    LOGGER.info("New config center members: {}", this.configServerAddresses);
}

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);
        }/*  w  ww .  j a  v  a  2  s  . c  o  m*/
    }
    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.auth.adapter.UserInfoAdapterV1_0Json.java

License:Open Source License

protected JsonObject getCommonFilteredInfos(JsonObject info, String clientId) {
    JsonObject filteredInfos = info.copy();
    String type = Utils.getOrElse(types.get(info.getString("type", "")), "");
    filteredInfos.put("type", type);
    filteredInfos.remove("cache");
    if (filteredInfos.getString("level") == null) {
        filteredInfos.put("level", "");
    } else if (filteredInfos.getString("level").contains("$")) {
        String[] level = filteredInfos.getString("level").split("\\$");
        filteredInfos.put("level", level[level.length - 1]);
    }//from w ww.j  a v  a 2  s .  co m
    if (clientId != null && !clientId.trim().isEmpty()) {
        JsonArray classNames = filteredInfos.getJsonArray("classNames");
        filteredInfos.remove("classNames");
        JsonArray structureNames = filteredInfos.getJsonArray("structureNames");
        filteredInfos.remove("structureNames");
        filteredInfos.remove("federated");
        if (classNames != null && classNames.size() > 0) {
            filteredInfos.put("classId", classNames.getString(0));
        }
        if (structureNames != null && structureNames.size() > 0) {
            filteredInfos.put("schoolName", structureNames.getString(0));
        }
        filteredInfos.remove("functions");
        filteredInfos.remove("groupsIds");
        filteredInfos.remove("structures");
        filteredInfos.remove("classes");
        filteredInfos.remove("apps");
        filteredInfos.remove("authorizedActions");
        filteredInfos.remove("children");
        JsonArray authorizedActions = new fr.wseduc.webutils.collections.JsonArray();
        for (Object o : info.getJsonArray("authorizedActions")) {
            JsonObject j = (JsonObject) o;
            String name = j.getString("name");
            if (name != null && name.startsWith(clientId + "|")) {
                authorizedActions.add(j);
            }
        }
        if (authorizedActions.size() > 0) {
            filteredInfos.put("authorizedActions", authorizedActions);
        }
    }
    return filteredInfos;
}

From source file:org.entcore.auth.controllers.SamlController.java

License:Open Source License

@Post("/saml/selectUser")
public void selectUser(final HttpServerRequest request) {
    request.setExpectMultipart(true);/*from  www  .  j  av a 2s.c  om*/
    request.endHandler(new Handler<Void>() {
        @Override
        public void handle(Void v) {
            final JsonObject j = new JsonObject();
            for (String attr : request.formAttributes().names()) {
                if (isNotEmpty(request.formAttributes().get(attr))) {
                    j.put(attr, request.formAttributes().get(attr));
                }
            }
            final String nameId = j.getString("nameId", "").replaceAll("\\r", "");
            final String sessionIndex = j.getString("sessionIndex");
            try {
                if (j.getString("key", "").equals(HmacSha1
                        .sign(sessionIndex + nameId + j.getString("login") + j.getString("id"), signKey))) {
                    authenticate(j, sessionIndex, nameId, request);
                } else {
                    log.error("Invalid signature for federated user.");
                    redirect(request, LOGIN_PAGE);
                }
            } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
                log.error("Error validating signature of federated user.", e);
                redirect(request, LOGIN_PAGE);
            }
        }
    });
}

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

License:Open Source License

@Override
public void create(JsonObject blog, UserInfos author, final Handler<Either<String, JsonObject>> result) {
    CommentType commentType = Utils.stringToEnum(blog.getString("comment-type", "").toUpperCase(),
            CommentType.NONE, CommentType.class);
    PublishType publishType = Utils.stringToEnum(blog.getString("publish-type", "").toUpperCase(),
            PublishType.RESTRAINT, PublishType.class);
    JsonObject now = MongoDb.now();//from   ww w .  jav  a  2s .  c  o  m
    JsonObject owner = new JsonObject().put("userId", author.getUserId()).put("username", author.getUsername())
            .put("login", author.getLogin());
    blog.put("created", now).put("modified", now).put("author", owner).put("comment-type", commentType.name())
            .put("publish-type", publishType.name()).put("shared", new JsonArray());
    JsonObject b = Utils.validAndGet(blog, FIELDS, FIELDS);
    if (validationError(result, b))
        return;
    mongo.save(BLOG_COLLECTION, b, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> res) {
            result.handle(Utils.validResult(res));
        }
    });
}

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

License:Open Source License

private List<String> getSharedIds(JsonArray shared, String filterRights) {
    List<String> shareIds = new ArrayList<>();
    for (Object o : shared) {
        if (!(o instanceof JsonObject))
            continue;
        JsonObject userShared = (JsonObject) o;

        if (filterRights != null && !userShared.getBoolean(filterRights, false))
            continue;

        String userOrGroupId = userShared.getString("groupId", userShared.getString("userId"));
        if (userOrGroupId != null && !userOrGroupId.trim().isEmpty()) {
            shareIds.add(userOrGroupId);
        }//from   ww  w.  j a  v  a 2  s.  c  om
    }
    return shareIds;
}

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

License:Open Source License

@Override
public void create(String blogId, JsonObject post, UserInfos author,
        final Handler<Either<String, JsonObject>> result) {
    JsonObject now = MongoDb.now();/*from w ww  .ja v  a  2s.  c  om*/
    JsonObject blogRef = new JsonObject().put("$ref", "blogs").put("$id", blogId);
    JsonObject owner = new JsonObject().put("userId", author.getUserId()).put("username", author.getUsername())
            .put("login", author.getLogin());
    post.put("created", now).put("modified", now).put("author", owner).put("state", StateType.DRAFT.name())
            .put("comments", new JsonArray()).put("views", 0).put("blog", blogRef);
    JsonObject b = Utils.validAndGet(post, FIELDS, FIELDS);
    if (validationError(result, b))
        return;
    b.put("sorted", now);
    if (b.containsKey("content")) {
        b.put("contentPlain", StringUtils.stripHtmlTag(b.getString("content", "")));
    }
    mongo.save(POST_COLLECTION, b,
            MongoDbResult.validActionResultHandler(new Handler<Either<String, JsonObject>>() {
                public void handle(Either<String, JsonObject> event) {
                    if (event.isLeft()) {
                        result.handle(event);
                        return;
                    }
                    mongo.findOne(POST_COLLECTION,
                            new JsonObject().put("_id", event.right().getValue().getString("_id")),
                            MongoDbResult.validResultHandler(result));
                }
            }));
}

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

License:Open Source License

@Override
public void update(String postId, final JsonObject post, final UserInfos user,
        final Handler<Either<String, JsonObject>> result) {

    final JsonObject jQuery = MongoQueryBuilder.build(QueryBuilder.start("_id").is(postId));
    mongo.findOne(POST_COLLECTION, jQuery,
            MongoDbResult.validActionResultHandler(new Handler<Either<String, JsonObject>>() {
                public void handle(Either<String, JsonObject> event) {
                    if (event.isLeft()) {
                        result.handle(event);
                        return;
                    } else {
                        final JsonObject postFromDb = event.right().getValue().getJsonObject("result",
                                new JsonObject());
                        final JsonObject now = MongoDb.now();
                        post.put("modified", now);
                        final JsonObject b = Utils.validAndGet(post, UPDATABLE_FIELDS,
                                Collections.<String>emptyList());

                        if (validationError(result, b))
                            return;
                        if (b.containsKey("content")) {
                            b.put("contentPlain", StringUtils.stripHtmlTag(b.getString("content", "")));
                        }//w w w  . j av  a 2s  .c o  m

                        if (postFromDb.getJsonObject("firstPublishDate") != null) {
                            b.put("sorted", postFromDb.getJsonObject("firstPublishDate"));
                        } else {
                            b.put("sorted", now);
                        }

                        //if user is author, draft state
                        if (user.getUserId().equals(
                                postFromDb.getJsonObject("author", new JsonObject()).getString("userId"))) {
                            b.put("state", StateType.DRAFT.name());
                        }

                        MongoUpdateBuilder modifier = new MongoUpdateBuilder();
                        for (String attr : b.fieldNames()) {
                            modifier.set(attr, b.getValue(attr));
                        }
                        mongo.update(POST_COLLECTION, jQuery, modifier.build(),
                                new Handler<Message<JsonObject>>() {
                                    @Override
                                    public void handle(Message<JsonObject> event) {
                                        if ("ok".equals(event.body().getString("status"))) {
                                            final JsonObject r = new JsonObject().put("state",
                                                    b.getString("state", postFromDb.getString("state")));
                                            result.handle(new Either.Right<String, JsonObject>(r));
                                        } else {
                                            result.handle(new Either.Left<String, JsonObject>(
                                                    event.body().getString("message", "")));
                                        }
                                    }
                                });
                    }
                }
            }));

}

From source file:org.entcore.cas.services.BRNERegisteredService.java

License:Open Source License

@Override
protected void prepareUser(User user, String userId, String service, JsonObject data) {
    //return the first uai as principalAttributeName
    for (Object s : data.getJsonArray("structureNodes", new fr.wseduc.webutils.collections.JsonArray())) {
        if (s == null || !(s instanceof JsonObject))
            continue;
        JsonObject structure = (JsonObject) s;
        String uai = structure.getString("UAI", "");
        if (!uai.isEmpty()) {
            user.setUser(uai);// w  w w.j ava 2s.c om
            break;
        }
    }

    user.setAttributes(new HashMap<String, String>());

    // Profile
    JsonArray profiles = data.getJsonArray("type", new fr.wseduc.webutils.collections.JsonArray());
    if (profiles.contains("Teacher")) {
        user.getAttributes().put(PROFIL, "National_3");
    } else if (profiles.contains("Student")) {
        user.getAttributes().put(PROFIL, "National_1");
    }
}

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   w w w. ja va2s  . c o 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);
                }
            }
        }
    }
}