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

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

Introduction

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

Prototype

public boolean containsKey(String key) 

Source Link

Document

Does the JSON object contain the specified key?

Usage

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.//  ww  w .  j av  a2 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.jspare.forvertx.web.auth.DefaultBasicAuthProvider.java

License:Apache License

@Override
protected void doAuthenticate(Handler<AsyncResult<User>> handler, String username, String password) {
    try {/*from w w  w  .  j  a  v  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);//from  w  w  w  .ja v a2s.  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;/* ww  w  .j a va 2s. c o 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.integration.java.BaseTestVerticle.java

License:Apache License

@Before
public void before(TestContext context) {
    vertx = rule.vertx();//from   w w  w  .j  a v a 2 s  . c o m
    Async async = context.async();
    aVoid().flatMap(aVoid -> {
        String clusteruuid = UUID.randomUUID().toString();
        try {
            rootTmpDir = createTempDirectory("");
            esTempDir = createTempDirectory(rootTmpDir, format("test-cluster-%s", clusteruuid));
            tmpDir = createTempDirectory(rootTmpDir, valueOf(currentTimeMillis()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        int esPort = findFreePort(9300, 9400);
        esHost = "127.0.0.1:" + esPort;
        esClusterName = format("test-cluster-%s", clusteruuid);
        esNodeName = format("test-server-node-%s", clusteruuid);

        Builder settings = settingsBuilder();
        settings.put("script.groovy.sandbox.enabled", false);
        settings.put("cluster.name", esClusterName);
        settings.put("node.name", esNodeName);
        settings.put("http.enabled", false);
        settings.put("discovery.zen.ping.multicast.enabled", false);
        settings.put("discovery.zen.ping.unicast.hosts", esHost);
        settings.put("transport.tcp.port", esPort);
        settings.put("network.host", "127.0.0.1");
        settings.put("node.data", true);
        settings.put("node.master", true);
        settings.put("path.home", esTempDir);
        esNode = nodeBuilder().settings(settings).node();
        esClient = esNode.client();

        JsonObject verticleConfig;

        Buffer buffer = vertx.fileSystem().readFileBlocking(
                currentThread().getContextClassLoader().getResource("intgtestconfig.json").getFile());
        verticleConfig = new JsonObject(buffer.toString(UTF_8));
        verticleConfig.put("fs.home", tmpDir.toString());

        if (!verticleConfig.containsKey("elasticsearch.cluster.name")) {
            verticleConfig.put("elasticsearch.cluster.name", esClusterName);
        }

        if (!verticleConfig.containsKey("elasticsearch.node.name")) {
            verticleConfig.put("elasticsearch.node.name", esNodeName);
        }

        if (!verticleConfig.containsKey("elasticsearch.discovery.zen.ping.unicast.hosts")) {
            verticleConfig.put("elasticsearch.discovery.zen.ping.unicast.hosts", new JsonArray().add(esHost));
        }

        if (!verticleConfig.containsKey("http.listen.addresses")) {
            int freePort = findFreePort(6677, 7777);
            verticleConfig.put("http.listen.addresses",
                    new JsonArray().add(HostAndPort.fromParts("127.0.0.1", freePort).toString()));
        }

        HostAndPort hostAndPort = HostAndPort
                .fromString(verticleConfig.getJsonArray("http.listen.addresses").getString(0));

        HttpClientOptions httpClientOptions = new HttpClientOptions();
        httpClientOptions.setDefaultPort(hostAndPort.getPort()).setDefaultHost(hostAndPort.getHostText())
                .setMaxPoolSize(25).setConnectTimeout(1000).setKeepAlive(false).setLogActivity(true);

        HttpClientOptions httpsClientOptions = new HttpClientOptions();
        httpsClientOptions.setDefaultPort(hostAndPort.getPort()).setDefaultHost(hostAndPort.getHostText())
                .setMaxPoolSize(25).setConnectTimeout(1000).setKeepAlive(false).setLogActivity(true)
                .setSsl(true);
        httpClient = vertx.createHttpClient(httpClientOptions);
        httpsClient = vertx.createHttpClient(httpsClientOptions);

        SfsServer sfsServer = new SfsServer();

        ObservableFuture<String> handler = RxHelper.observableFuture();
        vertx.deployVerticle(sfsServer, new DeploymentOptions().setConfig(verticleConfig), handler.toHandler());
        return handler.map(new ToVoid<>()).doOnNext(aVoid1 -> {
            vertxContext = sfsServer.vertxContext();
            checkState(vertxContext != null, "VertxContext was null on Verticle %s", sfsServer);
        }).onErrorResumeNext(throwable -> {
            throwable.printStackTrace();
            return cleanup().flatMap(aVoid1 -> Observable.<Void>error(throwable));
        });
    }).subscribe(new TestSubscriber(context, async));
}

From source file:org.sfs.util.ConfigHelper.java

License:Apache License

public static Iterable<String> getArrayFieldOrEnv(JsonObject config, String name,
        Iterable<String> defaultValue) {
    String envVar = formatEnvVariable(name);
    //USED_ENV_VARS.add(envVar);
    if (config.containsKey(name)) {
        JsonArray values = config.getJsonArray(name);
        if (values != null) {
            Iterable<String> iterable = FluentIterable.from(values).filter(Predicates.notNull())
                    .filter(input -> input instanceof String).transform(input -> input.toString());
            log(name, envVar, name, iterable);
            return iterable;
        }/*  w w  w  .  ja  v a2  s  .  com*/
    } else {
        String value = System.getenv(envVar);
        if (value != null) {
            log(name, envVar, envVar, value);
            return Splitter.on(',').split(value);
        }
    }
    log(name, envVar, null, defaultValue);
    return defaultValue;
}

From source file:org.sfs.util.ConfigHelper.java

License:Apache License

public static String getFieldOrEnv(JsonObject config, String name, String defaultValue) {
    String envVar = formatEnvVariable(name);
    //USED_ENV_VARS.add(envVar);
    if (config.containsKey(name)) {
        Object value = config.getValue(name);
        if (value != null) {
            String valueAsString = value.toString();
            log(name, envVar, name, valueAsString);
            return valueAsString;
        }/*from w  ww. j  av  a2 s  .c om*/
    } else {
        String value = System.getenv(envVar);
        if (value != null) {
            log(name, envVar, envVar, value);
            return value;
        }
    }
    log(name, envVar, null, defaultValue);
    return defaultValue;
}

From source file:org.sfs.vo.Container.java

License:Apache License

public T merge(JsonObject document) {

    checkState(getParent().getId().equals(document.getString("account_id")));

    setOwnerGuid(document.getString("owner_guid"));

    JsonArray metadataJsonObject = document.getJsonArray("metadata", new JsonArray());
    getMetadata().withJsonObject(metadataJsonObject);

    setNodeId(document.getString("node_id"));

    String createTimestamp = document.getString("create_ts");
    String updateTimestamp = document.getString("update_ts");

    if (createTimestamp != null) {
        setCreateTs(fromDateTimeString(createTimestamp));
    }/*from w  w w.ja  v  a  2  s.co  m*/
    if (updateTimestamp != null) {
        setUpdateTs(fromDateTimeString(updateTimestamp));
    }

    setObjectReplicas(
            document.containsKey("object_replicas") ? document.getInteger("object_replicas") : NOT_SET);

    return (T) this;
}

From source file:pt.davidafsilva.slacker.api.AbstractSlackerExecutor.java

License:Open Source License

@Override
public void start(final Future<Void> startFuture) throws Exception {
    LOGGER.info("starting {0}..", identifier());

    // start the HELLO slacker protocol
    final JsonObject helloMessage = new JsonObject().put("i", identifier()).put("d", description()).put("v",
            version());/* ww w.  j  a  v a 2s.com*/
    vertx.eventBus().send("reg.slacker-server", helloMessage, result -> {
        if (result.succeeded() && JsonObject.class.isInstance(result.result().body())) {
            final JsonObject response = (JsonObject) result.result().body();
            if (response.containsKey("a")) {
                // everything went smoothly - register the listener and complete the startup
                registerListener(response.getString("a"));
                LOGGER.info("successfully registered {0} executor", identifier());
                startFuture.complete();
            } else {
                failStart(startFuture, "no address to bind was received");
            }
        } else {
            // something unexpected happened
            failStart(startFuture,
                    Optional.ofNullable(result.cause()).map(Throwable::getMessage).orElse("invalid response"));
        }
    });
}

From source file:pt.davidafsilva.slacker.server.HttpServerConfiguration.java

License:Open Source License

/**
 * Validates the options for runtime and if there are missing options, fails the start of this
 * verticle./* w  ww  .j av  a 2  s  . co m*/
 *
 * @param config   the current configuration
 * @param required the required properties
 * @throws IllegalStateException if the provided configuration is invalid
 */
private static void validateOptions(final JsonObject config, final ConfigurationVariable... required) {
    final String[] missing = Arrays.stream(required).map(ConfigurationVariable::name)
            .filter(prop -> !config.containsKey(prop)).toArray(String[]::new);
    if (missing.length > 0) {
        throw new IllegalStateException(String.format(MISSING_PROPERTIES, Arrays.toString(missing)));
    }
}