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

Source Link

Document

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

Usage

From source file:com.cyngn.vertx.bosun.BosunReporter.java

License:Apache License

@Override
public void start(final Future<Void> startedResult) {

    // setup the default config values
    JsonObject config = context.config();
    hosts = config.getJsonArray("hosts", new JsonArray("[{ \"host\" : \"localhost\", \"port\" : 8070}]"));
    address = config.getString("address", DEFAULT_ADDRESS);
    maxTags = config.getInteger("max_tags", OPENTSDB_DEFAULT_MAX_TAGS);
    maxIndexCacheSize = config.getInteger("max_index_cache_size", DEFAULT_UNIQUE_METRICS_INDEXED);
    indexExpiryInMinutes = config.getInteger("index_expiry_minutes", DEFAULT_INDEX_EXPIRY_MINUTES);
    timeout = config.getInteger("default_timeout_ms", DEFAULT_TIMEOUT_MS);

    metricsIndexed = new AtomicInteger(0);
    metricsPut = new AtomicInteger(0);
    metricsErrors = new AtomicInteger(0);

    eventBus = vertx.eventBus();//from w  w w . j a  v a2  s . c  o m

    // create the list of workers
    connections = new ArrayList<>(hosts.size());

    initializeConnections(startedResult);
    createMessageHandlers();
    outputConfig();

    // initialize the in memory index cache
    distinctMetrics = CacheBuilder.newBuilder().maximumSize(maxIndexCacheSize)
            .expireAfterWrite(DEFAULT_INDEX_EXPIRY_MINUTES, TimeUnit.MINUTES)
            .build(new CacheLoader<String, Boolean>() {
                public Boolean load(String key) throws Exception {
                    return true;
                }
            });

    // start listening for incoming messages
    eventBus.consumer(address, this);
    initStatsReporting();
}

From source file:com.groupon.vertx.redis.RedisCommandHandler.java

License:Apache License

/**
 * This handles the incoming Redis command JSON.
 *
 * @param command - The JsonObject containing the commands to send to Redis.
 *//*from w  w w.  j  av  a2 s .  c  o  m*/
public void handle(final Message<JsonObject> command) {
    if (command.body() == null || command.body().size() == 0) {
        log.warn("handleCommand", "failure", new String[] { "reason" }, "Missing message body");
        command.reply(buildReply("error", null, "Invalid message with null or empty."));
        return;
    }

    JsonObject inputJson = command.body();
    boolean isMulti = inputJson.getBoolean("isTransaction", false);
    JsonArray commands = inputJson.getJsonArray("commands", new JsonArray());
    if (commands.size() > 0) {
        LinkedList<RedisCommand> transactionRedisCommands = new LinkedList<>();
        for (Object jsonCommand : commands) {
            RedisCommand redisCommand = getRedisCommand((JsonObject) jsonCommand, command, isMulti);
            if (redisCommand == null) {
                log.warn("handleCommand", "failure", new String[] { "reason" }, "Invalid redis command");
                command.reply(buildReply("error", null, "Invalid redis command"));
                return;
            }
            transactionRedisCommands.add(redisCommand);
        }
        if (isMulti) { //Wrap it with a  MULTI and EXEC block
            transactionRedisCommands.addFirst(new RedisCommand(RedisCommandType.MULTI, null));
            transactionRedisCommands.addLast(new RedisCommand(RedisCommandType.EXEC, null));
            setCommandResponseHandler(Collections.singletonList(transactionRedisCommands.getLast()), command,
                    isMulti);
        } else {
            setCommandResponseHandler(transactionRedisCommands, command, isMulti);
        }
        socket.sendCommand(transactionRedisCommands);
    } else {
        log.warn("handleCommand", "failure", new String[] { "reason" }, "Missing commands");
        command.reply(buildReply("error", null, "Invalid message with no commands"));
    }
}

From source file:de.fraunhofer.fokus.redistest.Query.java

License:Creative Commons License

/**
 * Constructor for a Query object/*w  ww.j a  v  a  2 s. c o m*/
 * @param json - JosonObject, a JSON representation of a Query object
 * @param issuer
 */
public Query(JsonObject json, String issuer) {
    familyName = NameHelper.toStringArray(json.getJsonArray("familyName", null));
    firstName = NameHelper.toStringArray(json.getJsonArray("firstName", null));
    placeOfBirth = json.getString("placeOfBirth", null);
    yearOfBirth = DateQuery.toDateQuery(json.getJsonObject("yearOfBirth", null));
    monthOfBirth = DateQuery.toDateQuery(json.getJsonObject("monthOfBirth", null));
    dayOfBirth = DateQuery.toDateQuery(json.getJsonObject("dayOfBirth", null));
    gender = json.getString("gender", null);
    JsonArray tmp = json.getJsonArray("familyNameFltr");
    if (tmp != null) {
        familyNameFltr = NameHelper.toStringArray(tmp);
    }
    tmp = json.getJsonArray("firstNameFltr");
    if (tmp != null) {
        firstNameFltr = NameHelper.toStringArray(tmp);
    }
    String stmp = json.getString("placeOfBirthFltr");
    if (stmp != null) {
        placeOfBirthFltr = stmp;
    }
    this.issuer = issuer;
    pseudonymized = json.getBoolean("pseudonymized", false);

}

From source file:io.engagingspaces.graphql.query.QueryResult.java

License:Open Source License

/**
 * Creates a new {@link QueryResult} from
 * its json representation.//from   w ww  .java 2 s. c  om
 *
 * @param json the json object
 */
public QueryResult(JsonObject json) {
    this.data = json.getJsonObject("data", new JsonObject());
    this.succeeded = json.getBoolean("succeeded", false);
    List<QueryError> queryErrors = json.getJsonArray("errors", new JsonArray()).stream()
            .map(error -> new QueryError((JsonObject) error)).collect(Collectors.toList());
    this.errors = queryErrors == null ? Collections.emptyList() : Collections.unmodifiableList(queryErrors);
}

From source file:io.flowly.auth.ExtJwtAuthProvider.java

License:Open Source License

@Override
public void authenticate(JsonObject authInfo, Handler<AsyncResult<User>> resultHandler) {
    try {//from   www .  j  ava 2 s .co  m
        final JsonObject payload = jwt.decode(authInfo.getString("jwt"));

        final JsonObject options = authInfo.getJsonObject("options", EMPTY_OBJECT);

        // All dates in JWT are of type NumericDate
        // a NumericDate is: numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until
        // the specified UTC date/time, ignoring leap seconds
        final long now = System.currentTimeMillis() / 1000;

        if (payload.containsKey("exp") && !options.getBoolean("ignoreExpiration", false)) {
            if (now >= payload.getLong("exp")) {
                resultHandler.handle(Future.failedFuture("Expired JWT token: exp <= now"));
                return;
            }
        }

        if (payload.containsKey("iat")) {
            Long iat = payload.getLong("iat");
            // issue at must be in the past
            if (iat > now) {
                resultHandler.handle(Future.failedFuture("Invalid JWT token: iat > now"));
                return;
            }
        }

        if (payload.containsKey("nbf")) {
            Long nbf = payload.getLong("nbf");
            // not before must be after now
            if (nbf > now) {
                resultHandler.handle(Future.failedFuture("Invalid JWT token: nbf > now"));
                return;
            }
        }

        if (options.containsKey("audience")) {
            JsonArray audiences = options.getJsonArray("audience", EMPTY_ARRAY);
            JsonArray target = payload.getJsonArray("aud", EMPTY_ARRAY);

            if (Collections.disjoint(audiences.getList(), target.getList())) {
                resultHandler
                        .handle(Future.failedFuture("Invalid JWT audience. expected: " + audiences.encode()));
                return;
            }
        }

        if (options.containsKey("issuer")) {
            if (!options.getString("issuer").equals(payload.getString("iss"))) {
                resultHandler.handle(Future.failedFuture("Invalid JWT issuer"));
                return;
            }
        }

        resultHandler.handle(Future.succeededFuture(new ExtJwtUser(payload, permissionsClaimKey)));

    } catch (RuntimeException e) {
        resultHandler.handle(Future.failedFuture(e));
    }
}

From source file:io.flowly.auth.ExtJwtUser.java

License:Open Source License

public ExtJwtUser(JsonObject jwtToken, String permissionsClaimKey) {
    this.jwtToken = jwtToken;
    this.permissions = jwtToken.getJsonArray(permissionsClaimKey, null);
}

From source file:io.knotx.repository.impl.RepositoryConnectorProxyImpl.java

License:Apache License

public RepositoryConnectorProxyImpl(Vertx vertx, JsonObject configuration) {
    clientOptions = configuration.getJsonObject("clientOptions", new JsonObject());
    clientDestination = configuration.getJsonObject("clientDestination");
    allowedRequestHeaders = configuration.getJsonArray("allowedRequestHeaders", new JsonArray()).stream()
            .map(object -> (String) object).map(new StringToPatternFunction()).collect(Collectors.toList());
    httpClient = createHttpClient(vertx);
}

From source file:io.nitor.api.backend.NitorBackend.java

License:Apache License

private void setupServices(JsonObject configRoot, HttpServerOptions httpServerOptions, Router router,
        ServiceRouterBuilder routeBuilder, HttpClient httpClient, CookieSessionHandler sessionHandler,
        JsonObject adAuth, boolean isOrigReqHttps) {
    JsonArray services = configRoot.getJsonArray("services", new JsonArray());
    services.forEach(s -> {// w w  w.  jav a  2  s  . co  m
        JsonObject service = (JsonObject) s;
        String type = service.getString("type", "<missing>");
        String logMsg = "Setting up service '" + type + "' on route '" + service.getString("route") + "'";
        switch (type) {
        case "proxy":
            setupProxy(service, routeBuilder, httpServerOptions, isOrigReqHttps);
            break;
        case "static":
            setupStaticFiles(service, routeBuilder);
            break;
        case "s3":
            setupS3(service, routeBuilder);
            break;
        case "lambda":
            setupLambda(service, routeBuilder);
            break;
        case "graph":
            setupGraph(service, routeBuilder, adAuth, sessionHandler, httpClient);
            break;
        case "virtualHost":
            String virtualHost = service.getString("host");
            logMsg += " for virtual host '" + virtualHost + "'";
            setupServices(service, httpServerOptions, null, routeBuilder.virtualHostHandler(virtualHost),
                    httpClient, sessionHandler, adAuth, isOrigReqHttps);
            break;
        case "cache":
            setupCache(service, routeBuilder);
            break;
        default: {
            RuntimeException ex = new RuntimeException("No support for service '" + type + "'");
            logger.fatal("service config failure", ex);
            throw ex;
        }
        }
        logger.info(logMsg);
    });
    if (router != null) {
        routeBuilder.registerHandlers(router);
    }
}

From source file:io.nitor.api.backend.s3.S3Handler.java

License:Apache License

public S3Handler(Vertx vertx, JsonObject conf, int routeLength) {
    this.routeLength = routeLength;

    indexFile = conf.getString("indexFile", "index.html");

    String staticPathConfig = conf.getString("staticPaths");
    staticPaths = staticPathConfig != null ? Pattern.compile(staticPathConfig) : null;

    String region = resolveRegion(conf).toString();
    this.s3Host = ("us-east-1".equals(region) ? "s3" : "s3-" + region) + ".amazonaws.com";

    String bucket = conf.getString("bucket");
    String basePath = '/' + bucket + '/' + conf.getString("path", "");
    basePathComponents = PathComponent.splitPath(basePath);

    AwsCredentialsProvider secretsProvider = resolveCredentialsProvider(conf);
    signer = new AWSRequestSigner(region, s3Host, secretsProvider);

    JsonArray operations = conf.getJsonArray("operations", new JsonArray().add("GET"));
    operations.forEach(op -> allowedMethods.add(HttpMethod.valueOf(op.toString())));

    http = vertx.createHttpClient(new HttpClientOptions()
            .setConnectTimeout((int) SECONDS.toMillis(conf.getInteger("connectTimeout", 5)))
            .setIdleTimeout((int) SECONDS.toSeconds(conf.getInteger("idleTimeout", 60)))
            .setMaxPoolSize(conf.getInteger("maxPoolSize", 100)).setPipelining(false).setMaxWaitQueueSize(100)
            .setUsePooledBuffers(true).setProtocolVersion(HTTP_1_1).setMaxRedirects(5)
            .setTryUseCompression(false));
}

From source file:net.kuujo.vertigo.cluster.ClusterOptions.java

License:Apache License

@SuppressWarnings("unchecked")
public ClusterOptions(JsonObject options) {
    this.clustered = options.containsKey("clustered") ? options.getBoolean("clustered")
            : options.getString("cluster") != null;
    this.clusterAddress = options.getString("cluster", clusterAddress);
    this.nodeAddress = options.getString("node", nodeAddress);
    this.nodes = new HashSet(options.getJsonArray("nodes", new JsonArray()).getList());
}