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

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

Introduction

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

Prototype

public JsonArray getJsonArray(String key) 

Source Link

Document

Get the JsonArray value with the specified key

Usage

From source file:org.folio.auth.permissions_module.impl.MongoPermissionsStore.java

@Override
public Future<JsonArray> getSubPermissions(String permission, String tenant) {
    JsonObject query = new JsonObject().put("permission_name", permission).put("tenant", tenant);
    JsonArray permList = new JsonArray();
    Future<JsonArray> future = Future.future();
    mongoClient.find("permissions", query, res -> {
        if (res.failed() || res.result().size() < 1) {
            future.fail("Query unsuccessful");
        } else {//w  w w .  j  a  v a2s  . c o m
            JsonObject permObject = res.result().get(0);
            future.complete(permObject.getJsonArray("sub_permissions"));
        }
    });
    return future;
}

From source file:org.folio.auth.permissions_module.impl.MongoPermissionsStore.java

@Override
public Future<JsonArray> getExpandedPermissions(String permission, String tenant) {
    //System.out.println("Permissions> Expanding permission '"+ permission + "' on tenant '"+
    //        tenant + "'");
    JsonObject query = new JsonObject().put("permission_name", permission).put("tenant", tenant);
    JsonArray permList = new JsonArray();
    Future<JsonArray> future = Future.future();
    mongoClient.find("permissions", query, res -> {
        if (res.succeeded() && res.result().size() > 0) {
            //System.out.println("Permissions> Successfully queried mongo for '"+ permission + "' on tenant '"+
            //    tenant + "'");
            /*//  w  w w  . ja  v  a2s.  c  o  m
            If there are no subpermissions, go ahead and complete the future with the
            given value of the JsonArray
                    
            If there are subpermissions, create a list of new futures, by calling
            walkPerms for each sub permission, then create a composite future from
            these new futures, with a handler that completes the original
            future when they return
            */
            JsonObject permObj = res.result().get(0);
            permList.add(permission);
            JsonArray subPerms = permObj.getJsonArray("sub_permissions");
            LinkedList<Future> futureList = new LinkedList<>();
            if (subPerms != null && !subPerms.isEmpty()) {
                logger.debug("Permissions> " + subPerms.size() + " subs to process for '" + permission + "'");
                for (Object o : subPerms) {
                    String sub = (String) o;
                    Future<JsonArray> newFuture = getExpandedPermissions(sub, tenant);
                    futureList.add(newFuture);
                }
                logger.debug("Permissions> Creating CompositeFuture to expand " + permission + " into "
                        + futureList.size() + " subs: " + subPerms.encode());
                CompositeFuture compositeFuture = CompositeFuture.all(futureList);
                compositeFuture.setHandler(res2 -> {
                    if (res2.succeeded()) {
                        //Get output of contained futures and complete the future here
                        for (Future f : futureList) {
                            JsonArray arr = (JsonArray) f.result();
                            for (Object o : arr) {
                                permList.add(o);
                            }
                        }
                        future.complete(permList);
                    } else {
                        future.fail("Unable to populate permissions: " + res2.cause().getMessage());
                    }
                });
            } else {
                //System.out.println("Permissions> No sub-permissions found for '" + permission + "'");
                future.complete(permList);
            }
        } else {
            future.fail("No permission '" + permission + "' found for tenant '" + tenant + "'");
        }
    });
    return future;
}

From source file:org.folio.auth.permissions_module.impl.MongoPermissionsStore.java

public Future<JsonArray> getPermissionsForUser(String user, String tenant, Boolean expand) {
    JsonObject query = new JsonObject().put("username", user).put("tenant", tenant);
    Future<JsonArray> future = Future.future();
    mongoClient.find("users", query, (AsyncResult<List<JsonObject>> res) -> {
        if (res.result().size() < 1) {
            future.fail("No such user");
        } else {//from  w  w w .  ja  v  a2 s  .  com
            JsonObject userObject = res.result().get(0);
            logger.debug("Permissions> Permissions for user " + user + ": " + userObject.encode());
            JsonArray permissions = userObject.getJsonArray("permissions");
            if (expand) {
                ArrayList<Future> futureList = new ArrayList<>();
                for (Object o : permissions) {
                    String permissionName = (String) o;
                    Future<JsonArray> expandPermissionFuture = this.getExpandedPermissions(permissionName,
                            tenant);
                    futureList.add(expandPermissionFuture);
                }
                logger.debug("Permissions> Assembling CompositeFuture of " + futureList.size()
                        + " permissions to expand");
                CompositeFuture compositeFuture = CompositeFuture.all(futureList);
                compositeFuture.setHandler(res2 -> {
                    if (res2.failed()) {
                        future.fail(res2.cause());
                    } else {
                        JsonArray allPermissions = new JsonArray();
                        for (Future f : futureList) {
                            JsonArray arr = (JsonArray) f.result();
                            for (Object o : arr) {
                                String perm = (String) o;
                                if (!allPermissions.contains(perm)) {
                                    allPermissions.add(perm);
                                }
                            }
                        }
                        logger.debug(
                                "Permissions> Returning list of " + allPermissions.size() + " permissions");
                        future.complete(allPermissions);
                    }
                });
            } else {
                future.complete(permissions);
            }
        }
    });
    return future;
}

From source file:org.folio.auth.permissions_module.MainVerticle.java

private void handlePermission(RoutingContext context) {
    String tenant = context.request().headers().get(TENANT_HEADER);
    String postData = null;//  www .ja  v a  2s  . co m
    if (context.request().method() == HttpMethod.POST) {
        postData = context.getBodyAsString();
    }
    if (context.request().method() == HttpMethod.POST) {
        String permissionName = context.request().getParam("permissionname");
        if (permissionName == null) {
            //Adding new permission
            JsonObject perm;
            String permName;
            JsonArray permSubs;
            try {
                perm = new JsonObject(postData);
            } catch (Exception e) {
                context.response().setStatusCode(400).end("Unable to parse " + postData + " into valid JSON");
                return;
            }
            permName = perm.getString("permission_name");
            if (permName == null) {
                context.response().setStatusCode(400).end("permission_name field is not present");
            }
            permSubs = perm.getJsonArray("sub_permissions");
            store.addPermission(permName, tenant).setHandler(res -> {
                if (res.failed()) {
                    logger.debug("Unable to add permission: " + res.cause().getMessage());
                    context.response().setStatusCode(500).end("Unable to add permission");
                } else {
                    if (permSubs == null) {
                        context.response().setStatusCode(201).end("Permission added");
                    } else {
                        ArrayList<Future> futureList = new ArrayList<>();
                        for (Object o : permSubs) {
                            String sub = (String) o;
                            futureList.add(store.addSubPermission(permName, sub, tenant));
                        }
                        CompositeFuture compFut = CompositeFuture.all(futureList);
                        compFut.setHandler(res2 -> {
                            if (res2.failed()) {
                                logger.debug("Error adding subpermissions: " + res2.cause().getMessage());
                                context.response().setStatusCode(500).end("Error adding sub permission");
                            } else {
                                context.response().setStatusCode(201).end("Permission added");
                            }
                        });
                    }
                }
            });
        } else {
            //Adding new sub-permission
            store.addSubPermission(permissionName, postData, tenant).setHandler(res -> {
                if (!res.succeeded()) {
                    context.response().setStatusCode(500).end("Unable to add permission");
                    return;
                }
                context.response().setStatusCode(201).end("Sub-Permission added");
            });
        }
    } else if (context.request().method() == HttpMethod.GET) {
        String permissionName = context.request().getParam("permissionname");
        if (permissionName == null) {
            context.response().setStatusCode(400).end("You must specify a permission name");
            return;
        }
        //store.getSubPermissions(permissionName, tenant).setHandler(res -> {
        store.getPermission(permissionName, tenant).setHandler(res -> {
            if (!res.succeeded()) {
                context.response().setStatusCode(500).end("Unable to retrieve permissions");
                return;
            }
            context.response().setStatusCode(200).putHeader("Content-Type", "application/json")
                    .end(res.result().encode());
        });
    } else if (context.request().method() == HttpMethod.DELETE) {
        String permissionName = context.request().getParam("permissionname");
        String subPermissionName = context.request().getParam("subpermissionname");
        if (permissionName == null && subPermissionName == null) {
            context.response().setStatusCode(400).end("Unsupported path");
            return;
        } else if (subPermissionName == null) {
            //remove permission
            store.removePermission(permissionName, tenant).setHandler(res -> {
                if (!res.succeeded()) {
                    context.response().setStatusCode(500).end("Unable to delete permission");
                    return;
                }
                context.response().setStatusCode(200).end("Permission deleted");
            });
        } else {
            //remove sub permission
            store.removeSubPermission(permissionName, subPermissionName, tenant).setHandler(res -> {
                if (!res.succeeded()) {
                    context.response().setStatusCode(500).end("Unable to delete subpermission");
                    return;
                }
                context.response().setStatusCode(200).end("Sub permission deleted");
            });
        }
    } else {
        context.response().setStatusCode(400).end("Unsupported method");
    }

}

From source file:org.jadala.auth.jwt.JsonWebTokenHandler.java

/**
 * Creates a JWT token for further requests. request params must contain valid 
 * email and password combination.//from   ww w .j  a v a  2 s. c  om
 * 
 * json request body:
 * {"email":<EMAIL>, "password":<PASSWORD>}
 * 
 * responses with 
 * status BAD_REQUEST: missing parameter
 * or status UNAUTHORIZED: email/password not valid
 * or status CREATED with content-type "application/json" and response body:
 *  {"jwt":<JWT_TOKEN>}
 * 
 * 
 * @param routingContext 
 */
@Override
public void handle(RoutingContext routingContext) {
    HttpServerResponse response = routingContext.response();
    JsonObject loginForm = null;
    try {
        loginForm = routingContext.getBodyAsJson();
    } catch (DecodeException de) {
        de.printStackTrace();
        response.setStatusCode(HttpResponseStatus.BAD_REQUEST.code()).end();
        return;
    }
    String email = loginForm.getString("email");
    String password = loginForm.getString("password");
    if (email == null || email.length() == 0 || password == null || password.length() == 0) {
        response.setStatusCode(HttpResponseStatus.BAD_REQUEST.code()).end();
        return;
    }
    String query = "{ \"_source\":true," + " \"query\" : " + "{\"filtered\" : " + "{\"filter\" : "
            + "{\"bool\" : " + "{\"must\": [" + "{\"term\":{\"email\":\"" + email + "\"}},"
            + "{\"term\":{ \"password\":\"" + password + "\"}}]}}}}}";
    JsonObject msg = new JsonObject(query);

    vertx.eventBus().send("elastic", msg, ElasticClient.commandOptions("usermanager", "users", "_search"),
            (AsyncResult<Message<JsonObject>> async) -> {

                if (async.failed() || async.result() == null) {
                    response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()).end();
                } else {
                    JsonObject msgBody = async.result().body();
                    JsonObject hits = msgBody.getJsonObject("hits");
                    if (hits == null) {
                        response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()).end();
                        return;
                    }
                    int total = hits.getInteger("total");
                    switch (total) {
                    case 0:
                        response.setStatusCode(HttpResponseStatus.UNAUTHORIZED.code()).end();
                        break;
                    case 1:
                        JsonObject hit = hits.getJsonArray("hits").getJsonObject(0);
                        String token = this.signer.sign(hit.getString("_id"), email);
                        String responseBody;
                        if (hit.containsKey("_source")) {
                            JsonObject source = hit.getJsonObject("_source");
                            source.put("jwt", token);
                            responseBody = source.encode();
                        } else {
                            responseBody = "{\"jwt\":\"" + token + "\"}";
                        }
                        response.setStatusCode(HttpResponseStatus.CREATED.code())
                                .putHeader("content-type", "application/json").end(responseBody);
                        break;
                    default:
                        response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()).end();
                    }
                }

            });
}

From source file:org.jboss.weld.vertx.examples.translator.DataCache.java

License:Apache License

private List<String> putIfAbsent(Object data) {
    if (data instanceof JsonObject) {
        JsonObject dataObject = (JsonObject) data;
        String word = dataObject.getString("word");
        if (word != null) {
            List<String> translations;
            JsonArray translationsArray = dataObject.getJsonArray("translations");
            if (translationsArray != null) {
                translations = new ArrayList<>();
                for (Object element : translationsArray) {
                    translations.add(element.toString());
                }//from   w  ww  . j  a v  a 2s. c om
                translations = Collections.unmodifiableList(translations);
            } else {
                translations = Collections.emptyList();
            }
            putIfAbsent(word, translations);
            return translations;
        }
    }
    return null;
}

From source file:org.mustertech.webapp.vertxutils.VerticleDeployer.java

License:Open Source License

private static Promise<JsonObject, Exception, Double> deployWithOpts(JsonObject opt) {
    Deferred<JsonObject, Exception, Double> deffered = new DeferredObject<JsonObject, Exception, Double>();
    DeploymentOptions deployOpts = new DeploymentOptions();

    // Check and set Config option
    if (opt.containsKey("config")) {
        JsonObject vertCfg = opt.getJsonObject("config");
        deployOpts.setConfig(vertCfg);//from w  w  w  .  j  av  a  2s. c o m
    }

    // Check and set ExtraClasspath option
    if (opt.containsKey("extCps")) {
        JsonArray extCps = opt.getJsonArray("extCps");
        Iterator<Object> cpIter = extCps.iterator();

        ArrayList<String> extCpsList = new ArrayList<String>();
        while (cpIter.hasNext()) {
            extCpsList.add((String) cpIter.next());
        }

        deployOpts.setExtraClasspath(extCpsList);
    }

    // Check and set Isolated-Group option
    if (opt.containsKey("isolatedGrp")) {
        deployOpts.setIsolationGroup(opt.getString("isolatedGrp"));
    }

    // Check and set Isolated-Classes option
    if (opt.containsKey("isolatedCls")) {
        JsonArray isoCls = opt.getJsonArray("isolatedCls");
        Iterator<Object> clsIter = isoCls.iterator();

        ArrayList<String> isoClsList = new ArrayList<String>();
        while (clsIter.hasNext()) {
            isoClsList.add((String) clsIter.next());
        }

        deployOpts.setIsolatedClasses(isoClsList);
    }

    // Check and set HA option
    deployOpts.setHa(opt.containsKey("isHa") && opt.getBoolean("isHa"));

    // Check and set instances option
    deployOpts.setInstances(opt.containsKey("nInst") ? opt.getInteger("nInst").intValue() : 1);

    // Check and set Worker/MT option
    Boolean isWorker = (opt.containsKey("isWorker") && opt.getBoolean("isWorker"));
    if (isWorker) {
        deployOpts.setWorker(true);
        deployOpts.setMultiThreaded(opt.containsKey("isMt") && opt.getBoolean("isMt"));
    }

    String vertName = opt.getString("name");

    // Finally, deploy the verticle
    vertx.deployVerticle(vertName, deployOpts, ar -> {
        if (ar.succeeded()) {
            JsonObject resObj = new JsonObject();
            resObj.put("verticleName", vertName).put("deployId", ar.result());

            deffered.resolve(resObj);
        } else {
            Throwable thr = ar.cause();
            String defErr = vertName + " => Could not be deployed!";
            deffered.reject(
                    (null != thr.getMessage()) ? new Exception(thr.getMessage()) : new Exception(defErr));
        }
    });

    return deffered.promise();
}

From source file:org.mustertech.webapp.vertxutils.VerticleDeployer.java

License:Open Source License

public static void deploy(final Vertx vertx, final String cfgJson, Handler<AsyncResult<JsonObject>> handler) {
    if (null == vertx) {
        NullPointerException e = new NullPointerException("NULL vertxutils instance is passed!");
        handler.handle(makeAsyncResult(e, null));

        return;/*from  ww w . j  a  v a 2  s. co m*/
    }

    // Store the vertx instance
    VerticleDeployer.vertx = vertx;

    try {
        InputStream schStream = VerticleDeployer.class.getResourceAsStream("/schema/deploy-schema.json");
        StringWriter strWriter = new StringWriter();

        IOUtils.copy(schStream, strWriter, "UTF-8");
        JsonValidator.validateJson(strWriter.toString(), cfgJson);
        IOUtils.closeQuietly(schStream);

        JsonObject cfgObj = new JsonObject(cfgJson);
        JsonObject globalCfg = null;
        JsonObject optObj = null, optCfg = null;
        JsonArray deployOpts = cfgObj.getJsonArray("deployOpts");

        int optsLen = deployOpts.size();
        ArrayList<Promise<JsonObject, Exception, Double>> promises = new ArrayList<Promise<JsonObject, Exception, Double>>();

        if (cfgObj.containsKey("globalConf")) {
            globalCfg = cfgObj.getJsonObject("globalConf");
        }

        for (int idx = 0; idx < optsLen; idx++) {
            optObj = (JsonObject) deployOpts.getJsonObject(idx);

            if (cfgObj.containsKey("appendGlobal") && cfgObj.getBoolean("appendGlobal")) {
                if (optObj.containsKey("config")) {
                    optCfg = optObj.getJsonObject("config");

                    if (!optCfg.containsKey("global")) {
                        optCfg.put("global", globalCfg);
                    }
                } else {
                    optCfg = new JsonObject();

                    optCfg.put("global", globalCfg);
                    optObj.put("config", optCfg);
                }
            }

            promises.add(deployWithOpts(optObj));
        }

        DeferredManager defMgr = new DefaultDeferredManager();

        defMgr.when(promises.toArray(new Promise[] {})).done(new DoneCallback<MultipleResults>() {
            public void onDone(MultipleResults results) {
                JsonArray resArr = new JsonArray();
                Iterator<OneResult> oneResIter = results.iterator();

                while (oneResIter.hasNext()) {
                    resArr.add(oneResIter.next().getResult());
                }

                JsonObject resObj = new JsonObject();
                resObj.put("deployInfo", resArr);

                handler.handle(makeAsyncResult(null, resObj));
            }
        }).fail(new FailCallback<OneReject>() {
            public void onFail(OneReject err) {
                handler.handle(makeAsyncResult((Throwable) err.getReject(), null));
            }
        });
    } catch (Exception e) {
        handler.handle(makeAsyncResult(e, null));
    }
}

From source file:org.sfs.auth.SimpleAuthProvider.java

License:Apache License

@Override
public Observable<Void> open(VertxContext<Server> vertxContext) {
    JsonObject config = vertxContext.verticle().config();
    JsonObject jsonObject = config.getJsonObject("auth");
    if (jsonObject != null) {
        for (String roleName : jsonObject.fieldNames()) {
            Role role = fromValueIfExists(roleName);
            checkState(role != null, "%s is not a valid role", roleName);
            JsonArray jsonUsers = jsonObject.getJsonArray(roleName);
            if (jsonUsers != null) {
                for (Object o : jsonUsers) {
                    JsonObject jsonUser = (JsonObject) o;
                    String id = getField(jsonUser, "id");
                    String username = getField(jsonUser, "username");
                    String password = getField(jsonUser, "password");
                    roles.put(role, new User(id, username, password));
                }// w  w w.j  av a2s  .com
            }
        }
    } else {
        roles.clear();
    }
    return aVoid();
}

From source file:org.sfs.filesystem.volume.DigestBlob.java

License:Apache License

public DigestBlob(JsonObject jsonObject) {
    super(jsonObject);
    digests = new HashMap<>();
    JsonArray jsonArray = jsonObject.getJsonArray("X-Computed-Digests");
    if (jsonArray != null) {
        for (Object o : jsonArray) {
            JsonObject jsonDigest = (JsonObject) o;
            String digestName = jsonDigest.getString("name");
            byte[] value = jsonDigest.getBinary("value");
            Optional<MessageDigestFactory> oMessageDigestFactory = fromValueIfExists(digestName);
            if (oMessageDigestFactory.isPresent()) {
                MessageDigestFactory messageDigestFactory = oMessageDigestFactory.get();
                withDigest(messageDigestFactory, value);
            }//from ww w . java 2 s .  c om
        }
    }
}