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

The following examples show how to use io.vertx.core.json.JsonObject#put() . 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: UpdateOptions.java    From vertx-elasticsearch-service with Apache License 2.0 6 votes vote down vote up
@Override
public JsonObject toJson() {
    final JsonObject json = super.toJson();

    if (getScript() != null) json.put(FIELD_SCRIPT, getScript());
    if (getScriptLang() != null) json.put(FIELD_SCRIPT_LANG, getScriptLang());
    if (getScriptParams() != null) json.put(FIELD_SCRIPT_PARAMS, getScriptParams());
    if (!getFields().isEmpty()) json.put(FIELD_FIELDS, new JsonArray(getFields()));
    if (getRetryOnConflict() != null) json.put(FIELD_RETRY_ON_CONFLICT, getRetryOnConflict());
    if (getDoc() != null) json.put(FIELD_DOC, getDoc());
    if (getUpsert() != null) json.put(FIELD_UPSERT, getUpsert());
    if (getDocAsUpsert() != null) json.put(FIELD_DOC_AS_UPSERT, getDocAsUpsert());
    if (getDetectNoop() != null) json.put(FIELD_DETECT_NOOP, getDetectNoop());
    if (getScriptedUpsert() != null) json.put(FIELD_SCRIPTED_UPSERT, getScriptedUpsert());
    if (getScriptType() != null) json.put(FIELD_SCRIPT_TYPE, getScriptType().name());

    return json;
}
 
Example 2
Source File: DeepObjectValueParameterParser.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public @Nullable Object parseParameter(Map<String, List<String>> parameters) throws MalformedValueException {
  JsonObject obj = new JsonObject();
  Iterator<Map.Entry<String, List<String>>> it = parameters.entrySet().iterator();
  while (it.hasNext()) {
    Map.Entry<String, List<String>> e = it.next();
    String key = e.getKey();
    if (key.contains(parameterName + "[") && key.charAt(key.length() - 1) == ']') {
      String realParameterName = key.substring(parameterName.length() + 1, key.length() - 1);
      Map.Entry<String, Object> parsed = parseField(realParameterName, e.getValue().get(0));
      if (parsed != null) {
        it.remove();
        obj.put(parsed.getKey(), parsed.getValue());
      }
    }
  }
  return obj.isEmpty() ? null : obj;
}
 
Example 3
Source File: SensorDataServiceVertxEBProxy.java    From vertx-in-action with MIT License 6 votes vote down vote up
@Override
public void valueFor(String sensorId, Handler<AsyncResult<JsonObject>> handler){
  if (closed) {
    handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
    return;
  }
  JsonObject _json = new JsonObject();
  _json.put("sensorId", sensorId);

  DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
  _deliveryOptions.addHeader("action", "valueFor");
  _vertx.eventBus().<JsonObject>request(_address, _json, _deliveryOptions, res -> {
    if (res.failed()) {
      handler.handle(Future.failedFuture(res.cause()));
    } else {
      handler.handle(Future.succeededFuture(res.result().body()));
    }
  });
}
 
Example 4
Source File: VxApiEntranceParam.java    From VX-API-Gateway with MIT License 6 votes vote down vote up
/**
 * 将对象装换为JsonObject
 * 
 * @return
 */
public JsonObject toJson() {
	JsonObject json = new JsonObject();
	json.put("paramName", this.paramName);
	json.put("position", this.position);
	json.put("paramType", this.paramType);
	json.put("isNotNull", this.isNotNull);
	if (def != null) {
		json.put("def", this.def);
	}
	if (describe != null) {
		json.put("describe", this.describe);
	}
	if (checkOptions != null) {
		json.put("checkOptions", checkOptions.toJson());
	}
	return json;
}
 
Example 5
Source File: FreeMarkerTemplateTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testTemplateHandlerOnFileSystem(TestContext should) {
  final Async test = should.async();
  TemplateEngine engine = FreeMarkerTemplateEngine.create(vertx);

  final JsonObject context = new JsonObject()
    .put("foo", "badger")
    .put("bar", "fox");

  context.put("context", new JsonObject().put("path", "/test-freemarker-template3.ftl"));

  engine.render(context, "src/test/filesystemtemplates/test-freemarker-template3.ftl", render -> {
    should.assertTrue(render.succeeded());
    should.assertEquals("Hello badger and fox\nRequest path is /test-freemarker-template3.ftl\n", render.result().toString());
    test.complete();
  });
  test.await();
}
 
Example 6
Source File: GridFsDownloadOptions.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
/**
 * Convert to JSON
 *
 * @return the JSON
 */
public JsonObject toJson() {
  JsonObject json = new JsonObject();
  if (revision != null) {
    json.put("revision", revision);
  }

  return json;
}
 
Example 7
Source File: ScriptFieldOption.java    From vertx-elasticsearch-service with Apache License 2.0 5 votes vote down vote up
public JsonObject toJson() {

        final JsonObject jsonObject = new JsonObject();

        if (script != null) jsonObject.put(JSON_FIELD_SCRIPT, script);
        if (scriptType != null) jsonObject.put(JSON_FIELD_SCRIPT_TYPE, scriptType.name());
        if (lang != null) jsonObject.put(JSON_FIELD_LANG, lang);
        if (params != null) jsonObject.put(JSON_FIELD_PARAMS, params);

        return jsonObject;
    }
 
Example 8
Source File: NestedJsonObjectDataObject.java    From vertx-codegen with Apache License 2.0 5 votes vote down vote up
public JsonObject toJson() {
  JsonObject ret = new JsonObject();
  if (value != null) {
    ret.put("value", value);
  }
  return ret;
}
 
Example 9
Source File: CompletionSuggestOption.java    From vertx-elasticsearch-service with Apache License 2.0 5 votes vote down vote up
@Override
public JsonObject toJson() {
    final JsonObject json = new JsonObject();

    if (getText() != null) json.put(FIELD_SUGGESTION_TEXT,getText());
    if (getField() != null) json.put(FIELD_SUGGESTION_FIELD,getField());
    if (getSize() != null) json.put(FIELD_SUGGESTION_SIZE,getSize());

    return json.mergeIn(super.toJson());
}
 
Example 10
Source File: PostgresQueryTest.java    From okapi with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetConnectionFailed1(TestContext context) {
  Async async = context.async();
  JsonObject obj = new JsonObject();
  obj.put("postgres_port", "0");
  FakeHandle h = new FakeHandle(vertx, obj);

  PostgresQuery q = new PostgresQuery(h);
  q.query("select", res -> {
    context.assertTrue(res.failed());
    context.assertEquals(ErrorType.INTERNAL, res.getType());
    context.assertEquals("getConnection failed", res.cause().getMessage());
    async.complete();
  });
}
 
Example 11
Source File: VxApiAuthOptions.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 将对象转为JsonObject
 * 
 * @return
 */
public JsonObject toJson() {
	JsonObject json = new JsonObject();
	json.put("inFactoryName", this.inFactoryName);
	json.put("option", this.option);
	return json;
}
 
Example 12
Source File: JsonAdapterStore.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
static List<CommonCredential> decodeCredentialsHierarchical(final String credentials) {
    final JsonObject json = new JsonObject(credentials);

    final List<CommonCredential> result = new ArrayList<>();

    for (Map.Entry<String, Object> typeEntry : (Iterable<Map.Entry<String, Object>>) () -> json.iterator()) {
        final Object value = typeEntry.getValue();
        if (!(value instanceof JsonObject)) {
            continue;
        }
        final JsonObject jsonValue = (JsonObject) value;
        for (Map.Entry<String, Object> authEntry : (Iterable<Map.Entry<String, Object>>) () -> jsonValue.iterator()) {
            final Object credentialValue = authEntry.getValue();
            if (!(credentialValue instanceof JsonObject)) {
                continue;
            }

            final JsonObject credentialJsonValue = (JsonObject) credentialValue;
            final JsonObject credentialEntry = new JsonObject();
            credentialEntry.put(CredentialsConstants.FIELD_TYPE, typeEntry.getKey());
            credentialEntry.put(CredentialsConstants.FIELD_AUTH_ID, authEntry.getKey());
            copyFields(credentialJsonValue, credentialEntry);
            result.add(credentialEntry.mapTo(CommonCredential.class));
        }
    }

    return result;

}
 
Example 13
Source File: EeaSendTransactionJsonParametersTest.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
@Test
public void transactionWithInvalidPrivateFromThrowsIllegalArgumentException() {
  final JsonObject parameters = validEeaTransactionParameters();
  parameters.put("privateFrom", "invalidThirtyTwoByteData=");

  final JsonRpcRequest request = wrapParametersInRequest(parameters);

  assertThatExceptionOfType(DecodeException.class)
      .isThrownBy(
          () ->
              factory.fromRpcRequestToJsonParam(EeaSendTransactionJsonParameters.class, request));
}
 
Example 14
Source File: ServiceInfo.java    From vert.x-microservice with Apache License 2.0 5 votes vote down vote up
public static JsonObject buildFromServiceInfo(ServiceInfo info) {
    final JsonObject tmp = new JsonObject();
    final JsonArray operationsArray = new JsonArray();
    Stream.of(info.getOperations()).forEach(op -> operationsArray.add(createOperation(op)));
    tmp.put("serviceName", info.getServiceName());
    tmp.put("lastConnection", info.getLastConnection());
    tmp.put("hostName", info.getHostName());
    tmp.put("serviceURL", info.getServiceURL());
    tmp.put("description", info.getDescription());
    tmp.put("port", info.getPort());
    tmp.put("operations", operationsArray);
    return tmp;
}
 
Example 15
Source File: ApolloWSConnectionHandler.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private JsonObject toJsonObject(Throwable t) {
  JsonObject res = new JsonObject().put("message", t.toString());
  if (WebEnvironment.development()) {
    StringWriter sw = new StringWriter();
    try (PrintWriter writer = new PrintWriter(sw)) {
      t.printStackTrace(writer);
      writer.flush();
    }
    res.put("extensions", new JsonObject()
      .put("exception", new JsonObject()
        .put("stacktrace", sw.toString())));
  }
  return res;
}
 
Example 16
Source File: PortfolioConverter.java    From microtrader with MIT License 5 votes vote down vote up
public static void toJson(Portfolio obj, JsonObject json) {
  json.put("cash", obj.getCash());
  if (obj.getShares() != null) {
    JsonObject map = new JsonObject();
    obj.getShares().forEach((key,value) -> map.put(key, value));
    json.put("shares", map);
  }
}
 
Example 17
Source File: ServiceDef.java    From sfs with Apache License 2.0 5 votes vote down vote up
public JsonObject toJsonObject() {
    JsonObject jsonObject = new JsonObject()
            .put("id", id)
            .put("update_ts", toDateTimeString(getLastUpdate()))
            .put("master_node", master)
            .put("data_node", dataNode)
            .put("document_count", documentCount)
            .put("available_processors", availableProcessors)
            .put("free_memory", freeMemory)
            .put("max_memory", maxMemory)
            .put("total_memory", totalMemory);

    if (fileSystem != null) {
        JsonObject jsonFileSystem = fileSystem.toJsonObject();
        jsonObject = jsonObject.put("file_system", jsonFileSystem);
    }

    JsonArray jsonListeners = new JsonArray();
    for (HostAndPort publishAddress : publishAddresses) {
        jsonListeners.add(publishAddress.toString());
    }
    jsonObject.put("publish_addresses", jsonListeners);

    JsonArray jsonVolumes = new JsonArray();
    for (XVolume<? extends XVolume> xVolume : volumes) {
        jsonVolumes.add(xVolume.toJsonObject());
    }
    jsonObject.put("volumes", jsonVolumes);
    return jsonObject;
}
 
Example 18
Source File: ConnectionPoolSettingsParserTest.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectionPoolSettings() {
  int maxPoolSize = 42;
  int minPoolSize = maxPoolSize / 2; // min needs to be less then max
  long maxIdleTimeMS = Math.abs(randomLong());
  long maxLifeTimeMS = Math.abs(randomLong());
  // Do not use long because of rounding.
  long waitQueueTimeoutMS = Math.abs(randomLong());
  long maintenanceInitialDelayMS = Math.abs(randomLong());
  long maintenanceFrequencyMS = Math.abs(randomLong());

  JsonObject config = new JsonObject();
  config.put("maxPoolSize", maxPoolSize);
  config.put("minPoolSize", minPoolSize);
  config.put("maxIdleTimeMS", maxIdleTimeMS);
  config.put("maxLifeTimeMS", maxLifeTimeMS);
  config.put("waitQueueTimeoutMS", waitQueueTimeoutMS);
  config.put("maintenanceInitialDelayMS", maintenanceInitialDelayMS);
  config.put("maintenanceFrequencyMS", maintenanceFrequencyMS);

  ConnectionPoolSettings settings = new ConnectionPoolSettingsParser(null, config).settings();
  assertEquals(maxPoolSize, settings.getMaxSize());
  assertEquals(minPoolSize, settings.getMinSize());
  assertEquals(maxIdleTimeMS, settings.getMaxConnectionIdleTime(MILLISECONDS));
  assertEquals(maxLifeTimeMS, settings.getMaxConnectionLifeTime(MILLISECONDS));
  assertEquals(waitQueueTimeoutMS, settings.getMaxWaitTime(MILLISECONDS));
  assertEquals(maintenanceInitialDelayMS, settings.getMaintenanceInitialDelay(MILLISECONDS));
  assertEquals(maintenanceFrequencyMS, settings.getMaintenanceFrequency(MILLISECONDS));
}
 
Example 19
Source File: RbacSecurityContext.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public static String rbacToRole(String namespace, ResourceVerb verb, String resource, String apiGroup) {
    JsonObject object = new JsonObject();
    object.put("type",  "resource");
    object.put("namespace", namespace);
    object.put("verb", verb);
    object.put("resource", resource);
    object.put("apiGroup", apiGroup);
    return object.toString();
}
 
Example 20
Source File: CircuitBreakerMetrics.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
private void addLatency(JsonObject json, Histogram histogram, String prefix) {
  json.put(prefix + "LatencyMean", histogram.getMean());
  json.put(prefix + "Latency", new JsonObject()
    .put("0", histogram.getValueAtPercentile(0))
    .put("25", histogram.getValueAtPercentile(25))
    .put("50", histogram.getValueAtPercentile(50))
    .put("75", histogram.getValueAtPercentile(75))
    .put("90", histogram.getValueAtPercentile(90))
    .put("95", histogram.getValueAtPercentile(95))
    .put("99", histogram.getValueAtPercentile(99))
    .put("99.5", histogram.getValueAtPercentile(99.5))
    .put("100", histogram.getValueAtPercentile(100)));
}