下面列出了io.vertx.core.json.JsonObject#put ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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;
}
@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()));
}
});
}
@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();
}
/**
* 将对象装换为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;
}
@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;
}
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;
}
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)));
}
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();
}
@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));
}
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;
}
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);
}
}
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;
}
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;
}
@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));
}
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;
}
/**
* 将对象转为JsonObject
*
* @return
*/
public JsonObject toJson() {
JsonObject json = new JsonObject();
json.put("inFactoryName", this.inFactoryName);
json.put("option", this.option);
return json;
}
@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();
});
}
@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());
}
public JsonObject toJson() {
JsonObject ret = new JsonObject();
if (value != null) {
ret.put("value", value);
}
return ret;
}
/**
* Convert to JSON
*
* @return the JSON
*/
public JsonObject toJson() {
JsonObject json = new JsonObject();
if (revision != null) {
json.put("revision", revision);
}
return json;
}