Java Code Examples for io.vertx.core.json.JsonObject#getLong()

The following examples show how to use io.vertx.core.json.JsonObject#getLong() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RestClientOptions.java    From vertx-rest-client with Apache License 2.0 6 votes vote down vote up
public RestClientOptions(final JsonObject json) {
    super(json);
    final JsonObject jsonObjectGlobalRequestCacheOptions = json.getJsonObject("globalRequestCacheOptions");
    if (jsonObjectGlobalRequestCacheOptions != null) {
        final RequestCacheOptions requestCacheOptions = new RequestCacheOptions();
        final Integer ttlInMillis = jsonObjectGlobalRequestCacheOptions.getInteger("ttlInMillis");
        final Boolean evictBefore = jsonObjectGlobalRequestCacheOptions.getBoolean("evictBefore");
        if (jsonObjectGlobalRequestCacheOptions.getJsonArray("cachedStatusCodes") != null) {
            final Set<Integer> cachedStatusCodes = jsonObjectGlobalRequestCacheOptions.getJsonArray("cachedStatusCodes")
                    .stream()
                    .map(e -> (Integer) e)
                    .collect(Collectors.toSet());
            requestCacheOptions.withCachedStatusCodes(cachedStatusCodes);
        }

        if (ttlInMillis != null) {
            requestCacheOptions.withExpiresAfterWriteMillis(ttlInMillis);
        }
        if (evictBefore != null) {
            requestCacheOptions.withEvictBefore(evictBefore);
        }
        globalRequestCacheOptions = requestCacheOptions;
    }
    globalHeaders = new CaseInsensitiveHeaders();
    globalRequestTimeoutInMillis = json.getLong("globalRequestTimeoutInMillis", DEFAULT_GLOBAL_REQUEST_TIMEOUT_IN_MILLIS);
}
 
Example 2
Source File: Aggregation.java    From vertx-elasticsearch-service with Apache License 2.0 6 votes vote down vote up
public Aggregation(JsonObject jsonObject) {
    this.index = jsonObject.getString(JSON_FIELD_INDEX);
    this.type = jsonObject.getString(JSON_FIELD_TYPE);
    this.id = jsonObject.getString(JSON_FIELD_ID);
    this.score = jsonObject.getFloat(JSON_FIELD_SCORE);
    this.version = jsonObject.getLong(JSON_FIELD_VERSION);
    this.source = jsonObject.getJsonObject(JSON_FIELD_SOURCE);

    final JsonObject jsonFields = jsonObject.getJsonObject(JSON_FIELD_FIELDS);
    if (jsonFields != null) {
        for (String fieldName : jsonFields.fieldNames()) {
            final List<Object> fieldValues = new LinkedList<>();
            jsonFields.getJsonArray(fieldName).stream().forEach(e -> fieldValues.add(e));
            this.fields.put(fieldName, fieldValues);
        }
    }
}
 
Example 3
Source File: NicoAudioSourceManager.java    From kyoko with MIT License 6 votes vote down vote up
private AudioTrack extractTrackFromHtml(String videoId, Document document) {
    Element element = document.selectFirst("#js-initial-watch-data");
    if (element != null) {
        String data = element.attributes().get("data-api-data");
        if (data == null) {
            return null;
        }

        JsonObject object = new JsonObject(data);
        JsonObject video = object.getJsonObject("video");

        String uploader = object.getJsonObject("owner").getString("nickname");
        String title = video.getString("title");
        long duration = video.getLong("duration") * 1000;

        return new NicoAudioTrack(new AudioTrackInfo(title, uploader, duration, videoId, false, getWatchUrl(videoId)), this);
    }
    return null;
}
 
Example 4
Source File: MarketDataVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 6 votes vote down vote up
/**
 * Read the configuration and set the initial values.
 * @param config the configuration
 */
void init(JsonObject config) {
  period = config.getLong("period", 3000L);
  variation = config.getInteger("variation", 100);
  name = config.getString("name");
  Objects.requireNonNull(name);
  symbol = config.getString("symbol", name);
  stocks = config.getInteger("volume", 10000);
  price = config.getDouble("price", 100.0);

  value = price;
  ask = price + random.nextInt(variation / 2);
  bid = price + random.nextInt(variation / 2);

  share = stocks / 2;

  System.out.println("Initialized " + name);
}
 
Example 5
Source File: MarketDataVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 6 votes vote down vote up
/**
 * Read the configuration and set the initial values.
 * @param config the configuration
 */
void init(JsonObject config) {
  period = config.getLong("period", 3000L);
  variation = config.getInteger("variation", 100);
  name = config.getString("name");
  Objects.requireNonNull(name);
  symbol = config.getString("symbol", name);
  stocks = config.getInteger("volume", 10000);
  price = config.getDouble("price", 100.0);

  value = price;
  ask = price + random.nextInt(variation / 2);
  bid = price + random.nextInt(variation / 2);

  share = stocks / 2;

  System.out.println("Initialized " + name);
}
 
Example 6
Source File: BlobReference.java    From sfs with Apache License 2.0 5 votes vote down vote up
public T merge(JsonObject jsonObject) {
    volumeId = jsonObject.getString("volume_id");
    position = jsonObject.getLong("position");
    readSha512 = jsonObject.getBinary("read_sha512");
    readLength = jsonObject.getLong("read_length");
    acknowledged = jsonObject.getBoolean("acknowledged");
    deleted = jsonObject.getBoolean("deleted");
    verifyFailCount = jsonObject.getInteger("verify_fail_count", 0);

    return (T) this;
}
 
Example 7
Source File: Hits.java    From vertx-elasticsearch-service with Apache License 2.0 5 votes vote down vote up
public Hits(JsonObject jsonObject) {
    this.total = jsonObject.getLong(JSON_FIELD_TOTAL);
    this.maxScore = jsonObject.getFloat(JSON_FIELD_MAX_SCORE);

    final JsonArray jsonHits = jsonObject.getJsonArray(JSON_FIELD_HITS);
    if(jsonHits != null) {
        for (int i=0;i<jsonHits.size();i++) {
            hits.add(new Hit(jsonHits.getJsonObject(i)));
        }
    }
}
 
Example 8
Source File: LocalSessionStoreImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public SessionStore init(Vertx vertx, JsonObject options) {
  // initialize a secure random
  this.random = VertxContextPRNG.current(vertx);
  this.vertx = vertx;
  this.reaperInterval = options.getLong("reaperInterval", DEFAULT_REAPER_INTERVAL);
  localMap = vertx.sharedData().getLocalMap(options.getString("mapName", DEFAULT_SESSION_MAP_NAME));
  setTimer();

  return this;
}
 
Example 9
Source File: MongoClientBulkWriteResult.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor from JSON
 * 
 * @param mongoClientBulkWriteResultJson
 */
public MongoClientBulkWriteResult(JsonObject mongoClientBulkWriteResultJson) {
  insertedCount = mongoClientBulkWriteResultJson.getLong(INSERTED_COUNT, DEFAULT_INSERTED_COUNT);
  matchedCount = mongoClientBulkWriteResultJson.getLong(MATCHED_COUNT, DEFAULT_MATCHED_COUNT);
  deletedCount = mongoClientBulkWriteResultJson.getLong(DELETED_COUNT, DEFAULT_DELETED_COUNT);
  modifiedCount = mongoClientBulkWriteResultJson.getLong(MODIFIED_COUNT, DEFAULT_MODIFIED_COUNT);
  JsonArray upsertArray = mongoClientBulkWriteResultJson.getJsonArray(UPSERTS);
  if (upsertArray != null)
    this.upserts = upsertArray.stream().filter(object -> object instanceof JsonObject)
        .map(object -> (JsonObject) object).collect(Collectors.toList());
}
 
Example 10
Source File: ConnectionPoolSettingsParser.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
public ConnectionPoolSettingsParser(ConnectionString connectionString, JsonObject config) {
  ConnectionPoolSettings.Builder settings = ConnectionPoolSettings.builder();
  if (connectionString != null) {
    settings.applyConnectionString(connectionString);
  } else {
    Integer maxPoolSize = config.getInteger("maxPoolSize");
    if (maxPoolSize != null) {
      settings.maxSize(maxPoolSize);
    }
    Integer minPoolSize = config.getInteger("minPoolSize");
    if (minPoolSize != null) {
      settings.minSize(minPoolSize);
    }
    Long maxIdleTimeMS = config.getLong("maxIdleTimeMS");
    if (maxIdleTimeMS != null) {
      settings.maxConnectionIdleTime(maxIdleTimeMS, MILLISECONDS);
    }
    Long maxLifeTimeMS = config.getLong("maxLifeTimeMS");
    if (maxLifeTimeMS != null) {
      settings.maxConnectionLifeTime(maxLifeTimeMS, MILLISECONDS);
    }
    Long waitQueueTimeoutMS = config.getLong("waitQueueTimeoutMS");
    if (waitQueueTimeoutMS != null) {
      settings.maxWaitTime(waitQueueTimeoutMS, MILLISECONDS);
    }
    Long maintenanceInitialDelayMS = config.getLong("maintenanceInitialDelayMS");
    if (maintenanceInitialDelayMS != null) {
      settings.maintenanceInitialDelay(maintenanceInitialDelayMS, MILLISECONDS);
    }
    Long maintenanceFrequencyMS = config.getLong("maintenanceFrequencyMS");
    if (maintenanceFrequencyMS != null) {
      settings.maintenanceFrequency(maintenanceFrequencyMS, MILLISECONDS);
    }
  }

  this.settings = settings.build();
}
 
Example 11
Source File: AbstractOptions.java    From vertx-elasticsearch-service with Apache License 2.0 5 votes vote down vote up
protected AbstractOptions(JsonObject json) {

        routing = json.getString(FIELD_ROUTING);
        parent = json.getString(FIELD_PARENT);
        version = json.getLong(FIELD_VERSION);
        versionType = Optional.ofNullable(json.getString(FIELD_VERSION_TYPE)).map(VersionType::valueOf).orElse(null);
    }
 
Example 12
Source File: UserData.java    From kyoko with MIT License 5 votes vote down vote up
public UserData(@NotNull JsonObject object) {
    this.id = Objects.requireNonNull(object).getLong("id");
    this.blacklisted = object.getBoolean("blacklisted");
    this.flags = object.getInteger("flags", 0);
    this.language = Language.valueOfSafe(object.getString("language", "DEFAULT"));
    this.color = object.getInteger("color", 0xff4757);
    this.image = object.getString("image", "default");
    this.voted = object.getLong("voted");
}
 
Example 13
Source File: GuildData.java    From kyoko with MIT License 5 votes vote down vote up
public GuildData(@NotNull JsonObject object) {
    this.id = Objects.requireNonNull(object).getLong("id");
    this.language = Language.valueOfSafe(object.getString("language", "DEFAULT"));
    this.prefixes = JsonUtil.toListString(object, "prefixes");
    this.features = JsonUtil.toListString(object, "features");
    this.premium = object.getLong("premium", 0L);
    this.flags = object.getInteger("flags", 0);
}
 
Example 14
Source File: JsObject.java    From vertx-codetrans with Apache License 2.0 4 votes vote down vote up
@CodeTranslate
public void getLongFromIdentifier() throws Exception {
  JsonObject obj = new JsonObject().put("port", 8080l);
  JsonTest.o = obj.getLong("port");
}
 
Example 15
Source File: WebAuthnImpl.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
/**
 * @param webAuthnResponse - Data from navigator.credentials.get
 * @param authr            - Credential from Database
 */
private long verifyWebAuthNGet(JsonObject webAuthnResponse, byte[] clientDataJSON, JsonObject clientData, JsonObject authr) throws IOException, AttestationException {

  JsonObject response = webAuthnResponse.getJsonObject("response");

  // STEP 25 parse auth data
  byte[] authenticatorData = b64dec.decode(response.getString("authenticatorData"));
  AuthenticatorData authrDataStruct = new AuthenticatorData(authenticatorData);

  if (!authrDataStruct.is(AuthenticatorData.USER_PRESENT)) {
    throw new RuntimeException("User was NOT present durring authentication!");
  }

  // TODO: assert the algorithm to be SHA-256 clientData.getString("hashAlgorithm") ?

  // STEP 26 hash clientDataJSON with sha256
  byte[] clientDataHash = hash(clientDataJSON);
  // STEP 27 create signature base by concat authenticatorData and clientDataHash
  Buffer signatureBase = Buffer.buffer()
    .appendBytes(authenticatorData)
    .appendBytes(clientDataHash);

  // STEP 28 format public key
  try (JsonParser parser = CBOR.cborParser(authr.getString("publicKey"))) {
    // the decoded credential primary as a JWK
    JWK publicKey = COSE.toJWK(CBOR.parse(parser));

    // STEP 29 convert signature to buffer
    byte[] signature = b64dec.decode(response.getString("signature"));

    // STEP 30 verify signature
    boolean verified = publicKey.verify(signature, signatureBase.getBytes());

    if (!verified) {
      throw new AttestationException("Failed to verify the signature!");
    }

    if (authrDataStruct.getSignCounter() <= authr.getLong("counter")) {
      throw new AttestationException("Authr counter did not increase!");
    }

    // return the counter so it can be updated on the store
    return authrDataStruct.getSignCounter();
  }
}
 
Example 16
Source File: KafkaConsumerVerticle.java    From vertx-kafka-service with Apache License 2.0 4 votes vote down vote up
KafkaConsumerConfiguration createKafkaConsumerConfiguration(final JsonObject config, final long instanceId) {
    final String clientIdPrefix = getMandatoryStringConfig(config, KafkaConsumerProperties.KEY_CLIENT_ID);

    final String topic = getMandatoryStringConfig(config, KafkaConsumerProperties.KEY_KAFKA_TOPIC);
    final String consumerGroup = getMandatoryStringConfig(config, KafkaConsumerProperties.KEY_GROUP_ID);

    final Boolean strictOrderingEnabled = config.getBoolean(KafkaConsumerProperties.KEY_STRICT_ORDERING, true);

    final Double messagesPerSecond = config.getDouble(KafkaConsumerProperties.KEY_MESSAGES_PER_SECOND, -1D);
    final Integer maxPollRecords = config.getInteger(KafkaConsumerProperties.KEY_MAX_POLL_RECORDS, 500);
    final Long maxPollIntervalMs = config.getLong(KafkaConsumerProperties.KEY_MAX_POLL_INTERVAL_MS, 300000L);
    final double maxPollIntervalSeconds = maxPollIntervalMs / 1000D;

    final Double effectiveMessagesPerSecond;
    if ((!strictOrderingEnabled) && messagesPerSecond < 0D) {
        effectiveMessagesPerSecond = NON_STRICT_ORDERING_MESSAGES_PER_SECOND_DEFAULT;
        LOG.warn("Strict ordering is disabled but no message limit given, limiting to {}", effectiveMessagesPerSecond);
    } else {
        effectiveMessagesPerSecond = messagesPerSecond;
    }

    final long effectiveMaxPollIntervalMs;
    if (effectiveMessagesPerSecond > 0D && effectiveMessagesPerSecond < (maxPollRecords / maxPollIntervalSeconds)) {
        effectiveMaxPollIntervalMs = (long) Math.ceil(maxPollRecords / effectiveMessagesPerSecond * 1000) * 2;
        LOG.warn("The configuration limits to handling {} messages per seconds, but number of polled records is {} that should be handled in {}ms." +
                        " This will cause the consumer to be marked as dead if there are more messages on the topic than are handled per second." +
                        " Setting the maxPollInterval to {}ms",
                effectiveMessagesPerSecond, maxPollRecords, maxPollIntervalMs, effectiveMaxPollIntervalMs);
    } else {
        effectiveMaxPollIntervalMs = maxPollIntervalMs;
    }

    return KafkaConsumerConfiguration.create(
            consumerGroup,
            clientIdPrefix + "-" + instanceId,
            topic,
            getMandatoryStringConfig(config, KafkaConsumerProperties.KEY_BOOTSTRAP_SERVERS),
            config.getString(KafkaConsumerProperties.KEY_OFFSET_RESET, "latest"),
            config.getInteger(KafkaConsumerProperties.KEY_MAX_UNACKNOWLEDGED, 100),
            config.getLong(KafkaConsumerProperties.KEY_MAX_UNCOMMITTED_OFFSETS, 1000L),
            config.getLong(KafkaConsumerProperties.KEY_ACK_TIMEOUT_SECONDS, 240L),
            config.getLong(KafkaConsumerProperties.KEY_COMMIT_TIMEOUT_MS, 5 * 60 * 1000L),
            config.getInteger(KafkaConsumerProperties.KEY_MAX_RETRIES, Integer.MAX_VALUE),
            config.getInteger(KafkaConsumerProperties.KEY_INITIAL_RETRY_DELAY_SECONDS, 1),
            config.getInteger(KafkaConsumerProperties.KEY_MAX_RETRY_DELAY_SECONDS, 10),
            config.getLong(KafkaConsumerProperties.KEY_EVENT_BUS_SEND_TIMEOUT, DeliveryOptions.DEFAULT_TIMEOUT),
            effectiveMessagesPerSecond,
            config.getBoolean(KafkaConsumerProperties.KEY_COMMIT_ON_PARTITION_CHANGE, true),
            strictOrderingEnabled,
            maxPollRecords,
            effectiveMaxPollIntervalMs,
            COMMA_LIST_SPLITTER.splitToList(config.getString(KafkaConsumerProperties.KEY_METRIC_CONSUMER_CLASSES, "")),
            config.getString(KafkaConsumerProperties.KEY_METRIC_DROPWIZARD_REGISTRY_NAME, "")
    );
}
 
Example 17
Source File: MetricsTest.java    From vertx-dropwizard-metrics with Apache License 2.0 4 votes vote down vote up
private Long getCount(JsonObject metric) {
  assertNotNull(metric);
  Long actual = metric.getLong("count");
  return actual;
}
 
Example 18
Source File: DashboardWebAppVerticle.java    From vertx-in-action with MIT License 4 votes vote down vote up
private int compareStepsCountInReverseOrder(JsonObject a, JsonObject b) {
  Long first = a.getLong("stepsCount");
  Long second = b.getLong("stepsCount");
  return second.compareTo(first);
}
 
Example 19
Source File: MongoClientUpdateResult.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
/**
 * Constructor from JSON
 * @param mongoClientUpdateResultJson
 */
public MongoClientUpdateResult(JsonObject mongoClientUpdateResultJson) {
  docMatched = mongoClientUpdateResultJson.getLong(DOC_MATCHED, DEFAULT_DOCMATCHED);
  docUpsertedId = mongoClientUpdateResultJson.getJsonObject(UPSERTED_ID, null);
  docModified = mongoClientUpdateResultJson.getLong(DOC_MODIFIED, DEFAULT_DOCMODIFIED);
}
 
Example 20
Source File: OffsetAndMetadata.java    From vertx-kafka-client with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor (from JSON representation)
 *
 * @param json  JSON representation
 */
public OffsetAndMetadata(JsonObject json) {
  this.offset = json.getLong("offset");
  this.metadata = json.getString("metadata");
}