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

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

Introduction

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

Prototype

public JsonObject getJsonObject(String key) 

Source Link

Document

Get the JsonObject value with the specified key

Usage

From source file:org.etourdot.vertx.marklogic.model.options.RolesOptions.java

License:Open Source License

public RolesOptions(JsonObject jsonObject) {
    super(jsonObject);
    ofNullable(jsonObject.getJsonObject("role")).ifPresent(o -> role = new Role(o));
}

From source file:org.etourdot.vertx.marklogic.model.options.SearchOptions.java

License:Open Source License

public SearchOptions(JsonObject jsonObject) {
    this();/*from   www.  j  a  va2s.  c  om*/
    requireNonNull(jsonObject);

    ofNullable(jsonObject.getJsonArray(CATEGORIES)).ifPresent(this::categories);
    ofNullable(jsonObject.getJsonArray(COLLECTIONS)).ifPresent(this::collections);
    ofNullable(jsonObject.getString(DIRECTORY)).ifPresent(this::directory);
    ofNullable(jsonObject.getLong(START)).ifPresent(this::start);
    ofNullable(jsonObject.getLong(PAGELEN)).ifPresent(this::pageLen);
    ofNullable(jsonObject.getString(VIEW)).ifPresent(this::view);
    ofNullable(jsonObject.getString(EXPRESSION)).ifPresent(this::expression);
    ofNullable(jsonObject.getJsonObject(QBE)).ifPresent(this::qbe);
    ofNullable(jsonObject.getJsonObject(STRUCT_QUERY)).ifPresent(this::structuredQuery);
}

From source file:org.folio.auth.login_module.impl.MongoAuthSource.java

@Override
public Future<AuthResult> authenticate(JsonObject credentials, String tenant) {
    Future<AuthResult> future = Future.future();
    String username = credentials.getString("username");
    String password = credentials.getString("password");
    if (username == null || password == null) {
        return Future.failedFuture("Credentials must contain a username and password");
    }//www. jav a2s.c o  m
    JsonObject query = new JsonObject().put("username", username).put("tenant", tenant);
    logger.debug("Calling MongoDB to retrieve credentials");
    mongoClient.find("credentials", query, res -> {
        if (res.succeeded() && !res.result().isEmpty()) {
            JsonObject user = res.result().get(0);
            String storedHash = user.getString("hash");
            String storedSalt = user.getString("salt");
            String calculatedHash = authUtil.calculateHash(password, storedSalt);
            if (calculatedHash.equals(storedHash)) {
                future.complete(new AuthResult(true, username, user.getJsonObject("metadata")));
                logger.debug("Future completed (good)");
            } else {
                future.complete(new AuthResult(false, username, user.getJsonObject("metadata")));
                logger.debug("Future completed (bad)");
            }
        } else {
            //username not found
            logger.error("No such user: " + username);
            future.complete(new AuthResult(false, username, null));
        }
        logger.debug("Lambda completed");
    });
    logger.debug("Returning");
    return future;
}

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

private void handleUser(RoutingContext ctx) {
    String tenant = ctx.request().headers().get("X-Okapi-Tenant");
    String requestBody = null;//  ww w .j a  v a 2  s .  co m
    if (ctx.request().method() == HttpMethod.POST || ctx.request().method() == HttpMethod.PUT) {
        requestBody = ctx.getBodyAsString();
    }
    if (ctx.request().method() == HttpMethod.POST) {
        JsonObject postData = new JsonObject(requestBody);
        JsonObject credentials = postData.getJsonObject("credentials");
        JsonObject metadata = postData.getJsonObject("metadata");
        authSource.addAuth(credentials, metadata, tenant).setHandler(res -> {
            if (!res.succeeded()) {
                ctx.response().setStatusCode(500).end("Unable to add user");
            } else {
                ctx.response().setStatusCode(201).end("Added user");
            }
        });

    } else if (ctx.request().method() == HttpMethod.PUT) {
        String username = ctx.request().getParam("username");
        JsonObject postData = new JsonObject(requestBody);
        JsonObject credentials = postData.getJsonObject("credentials");
        JsonObject metadata = postData.getJsonObject("metadata");
        if (!credentials.getString("username").equals(username)) {
            ctx.response().setStatusCode(400).end("Invalid user");
            return;
        }
        authSource.updateAuth(credentials, metadata, tenant).setHandler(res -> {
            if (!res.succeeded()) {
                ctx.response().setStatusCode(500).end("Unable to update user");
            } else {
                ctx.response().setStatusCode(200).end("Updated user");
            }
        });
    } else if (ctx.request().method() == HttpMethod.DELETE) {
        String username = ctx.request().getParam("username");
        authSource.deleteAuth(username, tenant).setHandler(res -> {
            if (!res.succeeded()) {
                ctx.response().setStatusCode(500).end("Unable to remove user");
            } else {
                ctx.response().setStatusCode(200).end("Deleted user");
            }
        });
    } else {
        ctx.response().setStatusCode(400).end("Unsupported operation");
        return;
    }
}

From source file:org.hawkular.apm.examples.vertx.opentracing.common.VertxMessageExtractAdapter.java

License:Apache License

public VertxMessageExtractAdapter(final JsonObject obj) {
    // Convert to single valued map
    this.map = new HashMap<>();

    JsonObject header = obj.getJsonObject("_apmHeader");
    if (header != null) {
        header.forEach(entry -> map.put(entry.getKey(), entry.getValue().toString()));
        // Remove header
        obj.remove("_apmHeader");
    }// w ww .  java  2 s.c  om
}

From source file:org.hawkular.apm.examples.vertx.opentracing.common.VertxMessageInjectAdapter.java

License:Apache License

public VertxMessageInjectAdapter(final JsonObject obj) {
    header = obj.getJsonObject("_apmHeader");
    if (header == null) {
        header = new JsonObject();
        obj.put("_apmHeader", header);
    }/*w ww  .  j a  v a 2  s . co m*/
}

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./*w w w . j a  v  a  2  s.c o m*/
 * 
 * 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.jspare.forvertx.web.auth.DefaultBasicAuthProvider.java

License:Apache License

@Override
protected void doAuthenticate(Handler<AsyncResult<User>> handler, String username, String password) {
    try {/*  w w  w .j  av a 2  s .c  o m*/
        String users = my(ResourceLoader.class).readFileToString(this.resource);
        JsonObject data = new JsonObject(users);

        if (data.containsKey(username) && data.getJsonObject(username).getString(PASSWORD).equals(password)) {

            handler.handle(Future.succeededFuture(new AbstractUser() {

                @Override
                public JsonObject principal() {
                    return data.getJsonObject(username);
                }

                @Override
                public void setAuthProvider(io.vertx.ext.auth.AuthProvider arg0) {
                }

                @Override
                protected void doIsPermitted(String authority, Handler<AsyncResult<Boolean>> resultPermitted) {

                    resultPermitted
                            .handle(Future.succeededFuture(principal().getJsonArray(ROLE).contains(authority)));
                }
            }));
        }

        return;

    } catch (IOException e) {

        log.warn(DEFAULT_ERROR);
    }

    handler.handle(Future.failedFuture(DEFAULT_ERROR));
}

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);/* w  w w  .  j a v a 2 s.  com*/
    }

    // 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;// w w w  .j  a  va2  s.c  om
    }

    // 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));
    }
}