Example usage for io.vertx.core.json JsonArray JsonArray

List of usage examples for io.vertx.core.json JsonArray JsonArray

Introduction

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

Prototype

public JsonArray() 

Source Link

Document

Create an empty instance

Usage

From source file:org.eclipse.hono.service.auth.impl.FileBasedAuthenticationService.java

License:Open Source License

private Authorities toAuthorities(final JsonArray authorities) {

    AuthoritiesImpl result = new AuthoritiesImpl();
    Objects.requireNonNull(authorities).stream().filter(obj -> obj instanceof JsonObject).forEach(obj -> {
        final JsonObject authSpec = (JsonObject) obj;
        final JsonArray activities = authSpec.getJsonArray(FIELD_ACTIVITIES, new JsonArray());
        final String resource = authSpec.getString(FIELD_RESOURCE);
        final String operation = authSpec.getString(FIELD_OPERATION);
        if (resource != null) {
            List<Activity> activityList = new ArrayList<>();
            activities.forEach(s -> {
                Activity act = Activity.valueOf((String) s);
                if (act != null) {
                    activityList.add(act);
                }/* w ww.ja  v a  2 s.  c  o m*/
            });
            result.addResource(resource, activityList.toArray(new Activity[activityList.size()]));
        } else if (operation != null) {
            String[] parts = operation.split(":", 2);
            if (parts.length == 2) {
                result.addOperation(parts[0], parts[1]);
            } else {
                log.debug("ignoring malformed operation spec [{}], operation name missing", operation);
            }
        } else {
            throw new IllegalArgumentException("malformed authorities");
        }
    });
    return result;
}

From source file:org.eclipse.hono.service.auth.impl.FileBasedAuthenticationService.java

License:Open Source License

private boolean hasAuthority(final JsonObject user, final String role) {
    return user.getJsonArray(FIELD_AUTHORITIES, new JsonArray()).contains(role);
}

From source file:org.eclipse.hono.service.credentials.impl.FileBasedCredentialsService.java

License:Open Source License

protected void saveToFile(final Future<Void> writeResult) {

    if (!dirty) {
        log.trace("credentials registry does not need to be persisted");
        return;/*from   w w w.  j a  v a2s  .c  om*/
    }

    final FileSystem fs = vertx.fileSystem();
    if (!fs.existsBlocking(filename)) {
        fs.createFileBlocking(filename);
    }
    final AtomicInteger idCount = new AtomicInteger();
    JsonArray tenants = new JsonArray();
    for (Entry<String, Map<String, JsonArray>> entry : credentials.entrySet()) {
        JsonArray credentialsArray = new JsonArray();
        for (Entry<String, JsonArray> credentialEntry : entry.getValue().entrySet()) { // authId -> full json attributes object
            JsonArray singleAuthIdCredentials = credentialEntry.getValue(); // from one authId

            credentialsArray.add(singleAuthIdCredentials);
            idCount.incrementAndGet();
        }
        tenants.add(
                new JsonObject().put(FIELD_TENANT, entry.getKey()).put(ARRAY_CREDENTIALS, credentialsArray));
    }
    fs.writeFile(filename, Buffer.factory.buffer(tenants.encodePrettily()), writeAttempt -> {
        if (writeAttempt.succeeded()) {
            dirty = false;
            log.trace("successfully wrote {} credentials to file {}", idCount.get(), filename);
            writeResult.complete();
        } else {
            log.warn("could not write credentials to file {}", filename, writeAttempt.cause());
            writeResult.fail(writeAttempt.cause());
        }
    });
}

From source file:org.eclipse.hono.service.registration.impl.FileBasedRegistrationService.java

License:Open Source License

private void saveToFile(final Future<Void> writeResult) {

    if (!dirty) {
        log.trace("registry does not need to be persisted");
        return;/*ww w  . j a v a 2 s  .com*/
    }

    final FileSystem fs = vertx.fileSystem();
    if (!fs.existsBlocking(filename)) {
        fs.createFileBlocking(filename);
    }
    final AtomicInteger idCount = new AtomicInteger();
    JsonArray tenants = new JsonArray();
    for (Entry<String, Map<String, JsonObject>> entry : identities.entrySet()) {
        JsonArray devices = new JsonArray();
        for (Entry<String, JsonObject> deviceEntry : entry.getValue().entrySet()) {
            devices.add(new JsonObject().put(FIELD_HONO_ID, deviceEntry.getKey()).put(FIELD_DATA,
                    deviceEntry.getValue()));
            idCount.incrementAndGet();
        }
        tenants.add(new JsonObject().put(FIELD_TENANT, entry.getKey()).put(ARRAY_DEVICES, devices));
    }
    fs.writeFile(filename, Buffer.factory.buffer(tenants.encodePrettily()), writeAttempt -> {
        if (writeAttempt.succeeded()) {
            dirty = false;
            log.trace("successfully wrote {} device identities to file {}", idCount.get(), filename);
            writeResult.complete();
        } else {
            log.warn("could not write device identities to file {}", filename, writeAttempt.cause());
            writeResult.fail(writeAttempt.cause());
        }
    });
}

From source file:org.eclipse.hono.util.TenantObject.java

License:Open Source License

/**
 * Gets the configuration information for this tenant's
 * configured adapters.// ww  w . jav a  2s .  com
 * 
 * @return The configuration properties for this tenant's
 *         configured adapters or {@code null} if no specific
 *         configuration has been set for any protocol adapter.
 */
@JsonIgnore
public JsonArray getAdapterConfigurations() {
    if (adapterConfigurations == null) {
        return null;
    } else {
        final JsonArray result = new JsonArray();
        adapterConfigurations.values().forEach(config -> result.add((JsonObject) config));
        return result;
    }
}

From source file:org.entcore.auth.users.DefaultUserAuthAccount.java

License:Open Source License

public DefaultUserAuthAccount(Vertx vertx, JsonObject config) {
    EventBus eb = Server.getEventBus(vertx);
    this.neo = new Neo(vertx, eb, null);
    this.vertx = vertx;
    this.config = config;
    EmailFactory emailFactory = new EmailFactory(vertx, config);
    notification = emailFactory.getSender();
    render = new Renders(vertx, config);
    LocalMap<Object, Object> server = vertx.sharedData().getLocalMap("server");
    if (server != null && server.get("smsProvider") != null) {
        smsProvider = (String) server.get("smsProvider");
        final String node = (String) server.get("node");
        smsAddress = (node != null ? node : "") + "entcore.sms";
    } else {/*w ww . ja v  a 2s.co m*/
        smsAddress = "entcore.sms";
    }
    this.allowActivateDuplicateProfiles = getOrElse(config.getJsonArray("allow-activate-duplicate"),
            new JsonArray().add("Relative"));
}

From source file:org.entcore.blog.controllers.BlogController.java

License:Open Source License

@Get("/list/all")
@SecuredAction("blog.list")
public void list(final HttpServerRequest request) {
    getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override//from  w w  w  . j  a v a 2s  .  c  o m
        public void handle(final UserInfos user) {
            if (user != null) {
                final Integer page;

                try {
                    page = (request.params().get("page") != null)
                            ? Integer.parseInt(request.params().get("page"))
                            : null;
                } catch (NumberFormatException e) {
                    badRequest(request, e.getMessage());
                    return;
                }

                final String search = request.params().get("search");

                blog.list(user, page, search, new Handler<Either<String, JsonArray>>() {
                    public void handle(Either<String, JsonArray> event) {
                        if (event.isLeft()) {
                            arrayResponseHandler(request).handle(event);
                            ;
                            return;
                        }

                        final JsonArray blogs = event.right().getValue();

                        if (blogs.size() < 1) {
                            renderJson(request, new JsonArray());
                            return;
                        }

                        final AtomicInteger countdown = new AtomicInteger(blogs.size());
                        final Handler<Void> finalHandler = new Handler<Void>() {
                            public void handle(Void v) {
                                if (countdown.decrementAndGet() <= 0) {
                                    renderJson(request, blogs);
                                }
                            }
                        };

                        for (Object blogObj : blogs) {
                            final JsonObject blog = (JsonObject) blogObj;

                            postService.list(blog.getString("_id"), PostService.StateType.PUBLISHED, user, null,
                                    2, null, new Handler<Either<String, JsonArray>>() {
                                        public void handle(Either<String, JsonArray> event) {
                                            if (event.isRight()) {
                                                blog.put("fetchPosts", event.right().getValue());
                                            }
                                            finalHandler.handle(null);
                                        }
                                    });
                        }

                    }
                });
            } else {
                unauthorized(request);
            }
        }
    });
}

From source file:org.entcore.blog.controllers.BlogController.java

License:Open Source License

@Get("/linker")
public void listBlogsIds(final HttpServerRequest request) {
    getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override/*from  w  w w . ja v a  2s . c om*/
        public void handle(final UserInfos user) {
            if (user != null) {
                blog.list(user, null, null, new Handler<Either<String, JsonArray>>() {
                    public void handle(Either<String, JsonArray> event) {
                        if (event.isLeft()) {
                            arrayResponseHandler(request).handle(event);
                            return;
                        }

                        final JsonArray blogs = event.right().getValue();

                        if (blogs.size() < 1) {
                            renderJson(request, new JsonArray());
                            return;
                        }

                        final AtomicInteger countdown = new AtomicInteger(blogs.size());
                        final Handler<Void> finalHandler = new Handler<Void>() {
                            public void handle(Void v) {
                                if (countdown.decrementAndGet() <= 0) {
                                    renderJson(request, blogs);
                                }
                            }
                        };

                        for (Object blogObj : blogs) {
                            final JsonObject blog = (JsonObject) blogObj;

                            postService.list(blog.getString("_id"), PostService.StateType.PUBLISHED, user, null,
                                    0, null, new Handler<Either<String, JsonArray>>() {
                                        public void handle(Either<String, JsonArray> event) {
                                            if (event.isRight()) {
                                                blog.put("fetchPosts", event.right().getValue());
                                            }
                                            finalHandler.handle(null);
                                        }
                                    });
                        }

                    }
                });
            } else {
                unauthorized(request);
            }
        }
    });
}

From source file:org.entcore.blog.controllers.BlogController.java

License:Open Source License

@Put("/share/json/:blogId")
@SecuredAction(value = "blog.manager", type = ActionType.RESOURCE)
public void shareJsonSubmit(final HttpServerRequest request) {
    final String blogId = request.params().get("blogId");
    if (blogId == null || blogId.trim().isEmpty()) {
        badRequest(request);//from  w  ww  . j a v  a2s.  c  o  m
        return;
    }
    request.setExpectMultipart(true);
    request.endHandler(new Handler<Void>() {
        @Override
        public void handle(Void v) {
            final List<String> actions = request.formAttributes().getAll("actions");
            final String groupId = request.formAttributes().get("groupId");
            final String userId = request.formAttributes().get("userId");
            if (actions == null || actions.isEmpty()) {
                badRequest(request);
                return;
            }
            getUserInfos(eb, request, new Handler<UserInfos>() {
                @Override
                public void handle(final UserInfos user) {
                    if (user != null) {
                        Handler<Either<String, JsonObject>> r = new Handler<Either<String, JsonObject>>() {
                            @Override
                            public void handle(Either<String, JsonObject> event) {
                                if (event.isRight()) {
                                    JsonObject n = event.right().getValue().getJsonObject("notify-timeline");
                                    if (n != null) {
                                        timelineService.notifyShare(request, blogId, user,
                                                new JsonArray().add(n), getBlogUri(request, blogId));
                                    }
                                    renderJson(request, event.right().getValue());
                                } else {
                                    JsonObject error = new JsonObject().put("error", event.left().getValue());
                                    renderJson(request, error, 400);
                                }
                            }
                        };
                        if (groupId != null) {
                            shareService.groupShare(user.getUserId(), groupId, blogId, actions, r);
                        } else if (userId != null) {
                            shareService.userShare(user.getUserId(), userId, blogId, actions, r);
                        } else {
                            badRequest(request);
                        }
                    } else {
                        unauthorized(request);
                    }
                }
            });
        }
    });
}

From source file:org.entcore.blog.events.BlogSearchingEvents.java

License:Open Source License

@Override
public void searchResource(List<String> appFilters, String userId, JsonArray groupIds,
        final JsonArray searchWords, final Integer page, final Integer limit, final JsonArray columnsHeader,
        final String locale, final Handler<Either<String, JsonArray>> handler) {
    if (appFilters.contains(BlogSearchingEvents.class.getSimpleName())) {

        final List<String> groupIdsLst = groupIds.getList();
        final List<DBObject> groups = new ArrayList<DBObject>();
        groups.add(QueryBuilder.start("userId").is(userId).get());
        for (String gpId : groupIdsLst) {
            groups.add(QueryBuilder.start("groupId").is(gpId).get());
        }//from   w w  w  . j a v  a  2s  . c  o  m

        final QueryBuilder rightsQuery = new QueryBuilder().or(
                QueryBuilder.start("visibility").is(VisibilityFilter.PUBLIC.name()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(),
                QueryBuilder.start("visibility").is(VisibilityFilter.PROTECTED.name()).get(),
                QueryBuilder.start("author.userId").is(userId).get(),
                QueryBuilder.start("shared")
                        .elemMatch(new QueryBuilder().or(groups.toArray(new DBObject[groups.size()])).get())
                        .get());

        final JsonObject projection = new JsonObject();
        projection.put("_id", 1);
        //search all blogs of user
        mongo.find(Blog.BLOGS_COLLECTION, MongoQueryBuilder.build(rightsQuery), null, projection,
                new Handler<Message<JsonObject>>() {
                    @Override
                    public void handle(Message<JsonObject> event) {
                        final Either<String, JsonArray> ei = validResults(event);
                        if (ei.isRight()) {
                            final JsonArray blogsResult = ei.right().getValue();

                            final Set<String> setIds = new HashSet<String>();
                            for (int i = 0; i < blogsResult.size(); i++) {
                                final JsonObject j = blogsResult.getJsonObject(i);
                                setIds.add(j.getString("_id"));
                            }

                            //search posts for the blogs found
                            searchPosts(page, limit, searchWords.getList(), setIds,
                                    new Handler<Either<String, JsonArray>>() {
                                        @Override
                                        public void handle(Either<String, JsonArray> event) {
                                            if (event.isRight()) {
                                                if (log.isDebugEnabled()) {
                                                    log.debug(
                                                            "[BlogSearchingEvents][searchResource] The resources searched by user are found");
                                                }
                                                final JsonArray res = formatSearchResult(
                                                        event.right().getValue(), columnsHeader,
                                                        searchWords.getList());
                                                handler.handle(new Right<String, JsonArray>(res));
                                            } else {
                                                handler.handle(new Either.Left<String, JsonArray>(
                                                        event.left().getValue()));
                                            }
                                        }
                                    });
                        } else {
                            handler.handle(new Either.Left<String, JsonArray>(ei.left().getValue()));
                        }
                    }
                });
    } else {
        handler.handle(new Right<String, JsonArray>(new JsonArray()));
    }
}