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

The following examples show how to use io.vertx.core.json.JsonObject#getValue() . 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: VaultConfigStore.java    From vertx-config with Apache License 2.0 6 votes vote down vote up
private Future<Buffer> extract(JsonObject json) {
  Promise<Buffer> promise = Promise.promise();
  if (json == null) {
    promise.complete(new JsonObject().toBuffer());
  } else if (config.getString("key") != null) {
    Object value = json.getValue(config.getString("key"));
    if (value == null) {
      promise.complete(new JsonObject().toBuffer());
    } else if (value instanceof String) {
      promise.complete(Buffer.buffer((String) value));
    } else if (value instanceof JsonObject) {
      promise.complete(((JsonObject) value).toBuffer());
    }
  } else {
    promise.complete(json.toBuffer());
  }
  return promise.future();
}
 
Example 2
Source File: VxApiCustomHandlerOptions.java    From VX-API-Gateway with MIT License 6 votes vote down vote up
/**
 * 通过Json对象获得一个实例
 * 
 * @param obj
 * @return
 */
public static VxApiCustomHandlerOptions fromJson(JsonObject obj) {
	if (obj == null) {
		return null;
	}
	VxApiCustomHandlerOptions option = new VxApiCustomHandlerOptions();
	if (obj.getValue("inFactoryName") instanceof String) {
		option.setInFactoryName(obj.getString("inFactoryName"));
	}
	if (obj.getValue("isNext") instanceof Boolean) {
		option.setNext(obj.getBoolean("isNext"));
	}
	if (obj.getValue("option") instanceof JsonObject) {
		option.setOption(obj.getJsonObject("option"));
	}
	return option;
}
 
Example 3
Source File: FileBasedCredentialsService.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets a property value of a given type from a JSON object.
 *
 * @param clazz Type class of the type
 * @param payload The object to get the property from.
 * @param field The name of the property.
 * @param <T> The type of the field.
 * @return The property value or {@code null} if no such property exists or is not of the expected type.
 * @throws NullPointerException if any of the parameters is {@code null}.
 */
protected static <T> T getTypesafeValueForField(final Class<T> clazz, final JsonObject payload,
        final String field) {

    Objects.requireNonNull(clazz);
    Objects.requireNonNull(payload);
    Objects.requireNonNull(field);

    final Object result = payload.getValue(field);

    if (clazz.isInstance(result)) {
        return clazz.cast(result);
    }

    return null;
}
 
Example 4
Source File: CartEventConverter.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
public static void fromJson(JsonObject json, CartEvent obj) {
  if (json.getValue("amount") instanceof Number) {
    obj.setAmount(((Number)json.getValue("amount")).intValue());
  }
  if (json.getValue("cartEventType") instanceof String) {
    obj.setCartEventType(io.vertx.blueprint.microservice.cart.CartEventType.valueOf((String)json.getValue("cartEventType")));
  }
  if (json.getValue("createdAt") instanceof Number) {
    obj.setCreatedAt(((Number)json.getValue("createdAt")).longValue());
  }
  if (json.getValue("id") instanceof Number) {
    obj.setId(((Number)json.getValue("id")).longValue());
  }
  if (json.getValue("productId") instanceof String) {
    obj.setProductId((String)json.getValue("productId"));
  }
  if (json.getValue("userId") instanceof String) {
    obj.setUserId((String)json.getValue("userId"));
  }
}
 
Example 5
Source File: CustomTypeAnnotator.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
public CustomTypeAnnotator(GenerationConfig generationConfig) {
  //called once for each json schema defined
  super(generationConfig);
  //load into a table the custom json schema fields
  for (int j = 0; j < schemaCustomFields.length; j++) {
    JsonObject jo = new JsonObject(schemaCustomFields[j]);
    String fieldName = jo.getString("fieldname");
    Object fieldValue = jo.getValue("fieldvalue");
    JsonObject annotation = jo.getJsonObject("annotation");
    if(annotationLookUp.get(fieldName, fieldValue) == null){
      annotationLookUp.put(fieldName , fieldValue, annotation);
      log.info("Loading custom field " + fieldName + " with value " + fieldValue + " with annotation " + annotation.encode());
    }
  }
}
 
Example 6
Source File: CredentialsObject.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static void checkHashedPassword(final JsonObject secret) {
    final Object hashFunction = secret.getValue(CredentialsConstants.FIELD_SECRETS_HASH_FUNCTION);
    if (!(hashFunction instanceof String)) {
        throw new IllegalStateException("missing/invalid hash function");
    }
    final Object hashedPwd = secret.getValue(CredentialsConstants.FIELD_SECRETS_PWD_HASH);
    if (!(hashedPwd instanceof String)) {
        throw new IllegalStateException("missing/invalid password hash");
    }
}
 
Example 7
Source File: VxApiEntranceParam.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 通过JsonObject实例化一个对象
 * 
 * @param obj
 * @return
 */
public static VxApiEntranceParam fromJson(JsonObject obj) {
	if (obj == null) {
		return null;
	}
	VxApiEntranceParam option = new VxApiEntranceParam();
	if (obj.getValue("paramName") instanceof String) {
		option.setParamName(obj.getString("paramName"));
	}
	if (obj.getValue("describe") instanceof String) {
		option.setDescribe(obj.getString("describe"));
	}
	if (obj.getValue("isNotNull") instanceof Boolean) {
		option.setNotNull(obj.getBoolean("isNotNull"));
	}
	if (obj.getValue("position") instanceof String) {
		option.setPosition(ParamPositionEnum.valueOf(obj.getString("position")));
	}
	if (obj.getValue("paramType") instanceof String) {
		option.setParamType(ParamTypeEnum.valueOf(obj.getString("paramType")));
	}
	if (obj.getValue("def") != null) {
		option.setDef(obj.getValue("def"));
	}
	if (obj.getValue("checkOptions") instanceof JsonObject) {
		option.setCheckOptions(VxApiParamCheckOptions.fromJson(obj.getJsonObject("checkOptions")));
	} else if (obj.getValue("checkOptions") instanceof String) {
		option.setCheckOptions(VxApiParamCheckOptions.fromJson(new JsonObject(obj.getString("checkOptions"))));
	}
	return option;
}
 
Example 8
Source File: VxApiApplicationConverter.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
public static void fromJson(JsonObject json, VxApiApplicationOptions obj) {
	if (json.getValue("appName") instanceof String) {
		obj.setAppName((String) json.getValue("appName"));
	}
	if (json.getValue("describe") instanceof String) {
		obj.setDescribe((String) json.getValue("describe"));
	}
	if (json.getValue("contentLength") instanceof Number) {
		obj.setContentLength(((Number) json.getValue("contentLength")).longValue());
	}
	if (json.getValue("scope") instanceof Number) {
		obj.setScope(((Number) json.getValue("scope")).intValue());
	}
	if (json.getValue("sessionTimeOut") instanceof Number) {
		obj.setSessionTimeOut(((Number) json.getValue("sessionTimeOut")).longValue());
	}
	if (json.getValue("sessionCookieName") instanceof String) {
		obj.setSessionCookieName((String) json.getValue("sessionCookieName"));
	}
	if (json.getValue("portOptions") instanceof JsonObject) {
		obj.setServerOptions(
				Json.decodeValue(json.getJsonObject("portOptions").toString(), VxApiServerOptions.class));
	}
	if (json.getValue("corsOptions") instanceof JsonObject) {
		obj.setCorsOptions(Json.decodeValue(json.getJsonObject("corsOptions").toString(), VxApiCorsOptions.class));
	}
}
 
Example 9
Source File: MongoClientImpl.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
JsonObject encodeKeyWhenUseObjectId(JsonObject json) {
  if (!useObjectId) return json;

  Object idString = json.getValue(ID_FIELD, null);
  if (idString instanceof String && ObjectId.isValid((String) idString)) {
    json.put(ID_FIELD, new JsonObject().put(JsonObjectCodec.OID_FIELD, idString));
  }

  return json;
}
 
Example 10
Source File: VxApiAuthSessionTokenImpl.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * @param obj
 *          通过一个JsonObject实例化一个对象 <br>
 *          obj.apiTokenName = API中token的名字<br>
 *          obj.userTokenName = 用户token在请求中的名字<br>
 *          obj.userTokenScope =
 *          用户token在请求中的名字所在的位置枚举类型{@link ParamPositionEnum} 默认在HEADER中<br>
 *          obj.authFailContentType =
 *          验证不通过时返回的Content-Type枚举类型{@link ContentTypeEnum} 默认为JSON_UTF8<br>
 *          obj.authFailResult = 验证不通过时的返回结果 默认为
 *          {@link ResultFormat}.formatAsNull({@link HTTPStatusCodeMsgEnum}.C401)<br>
 */
public VxApiAuthSessionTokenImpl(JsonObject obj) {
	if (obj == null) {
		throw new NullPointerException("SessionToken认证方式的配置文件不能为空!");
	}
	if (obj.getValue("apiTokenName") instanceof String) {
		this.apiTokenName = obj.getString("apiTokenName");
	} else {
		this.apiTokenName = VX_API_SESSION_TOKEN_NAME;
	}
	if (obj.getValue("userTokenName") instanceof String) {
		this.userTokenName = obj.getString("userTokenName");
	} else {
		this.userTokenName = VX_API_USER_TOKEN_NAME;
	}
	if (obj.getValue("userTokenScope") instanceof String) {
		this.userTokenScope = ParamPositionEnum.valueOf(obj.getString("userTokenScope"));
	} else {
		this.userTokenScope = ParamPositionEnum.HEADER;
	}
	if (obj.getValue("authFailContentType") instanceof String) {
		this.authFailContentType = ContentTypeEnum.valueOf(obj.getString("authFailContentType"));
	} else {
		this.authFailContentType = ContentTypeEnum.JSON_UTF8;
	}
	if (obj.getValue("authFailResult") instanceof String) {
		this.authFailResult = obj.getString("authFailResult");
	} else {
		this.authFailResult = ResultFormat.formatAsNull(HTTPStatusCodeMsgEnum.C401);
	}
}
 
Example 11
Source File: VxApiAuthOptions.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 通过Json对象获得一个实例
 * 
 * @param obj
 * @return
 */
public static VxApiAuthOptions fromJson(JsonObject obj) {
	if (obj == null) {
		return null;
	}
	VxApiAuthOptions option = new VxApiAuthOptions();
	if (obj.getValue("inFactoryName") instanceof String) {
		option.setInFactoryName(obj.getString("inFactoryName"));
	}

	if (obj.getValue("option") instanceof JsonObject) {
		option.setOption(obj.getJsonObject("option"));
	}
	return option;
}
 
Example 12
Source File: VxApiServerEntranceHttpOptions.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 通过一个JsonObject获得一个实例
 * 
 * @param obj
 * @return
 */
public static VxApiServerEntranceHttpOptions fromJson(JsonObject obj) {
	if (obj == null) {
		return null;
	}
	VxApiServerEntranceHttpOptions option = new VxApiServerEntranceHttpOptions();
	if (obj.getValue("balanceType") instanceof String) {
		option.setBalanceType(LoadBalanceEnum.valueOf(obj.getString("balanceType")));
	}
	if (obj.getValue("serverUrls") instanceof JsonArray) {
		List<VxApiServerURL> list = new ArrayList<>();
		obj.getJsonArray("serverUrls").forEach(va -> {
			if (va instanceof JsonObject) {
				list.add(VxApiServerURL.fromJson((JsonObject) va));
			} else if (va instanceof String) {
				list.add(VxApiServerURL.fromJson(new JsonObject(va.toString())));
			}
		});
		option.setServerUrls(list);
	}
	if (obj.getValue("method") instanceof String) {
		option.setMethod(HttpMethod.valueOf(obj.getString("method")));
	}
	if (obj.getValue("timeOut") instanceof Number) {
		option.setTimeOut(((Number) obj.getValue("timeOut")).longValue());
	}
	if (obj.getValue("retryTime") instanceof Number) {
		option.setRetryTime(((Number) obj.getValue("retryTime")).longValue());
	}
	if (obj.getValue("params") instanceof JsonArray) {
		List<VxApiParamOptions> params = new ArrayList<>();
		obj.getJsonArray("params").forEach(va -> {
			params.add(VxApiParamOptions.fromJson((JsonObject) va));
		});
		option.setParams(params);
	}

	return option;
}
 
Example 13
Source File: StoreConverter.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
public static void fromJson(JsonObject json, Store obj) {
  if (json.getValue("description") instanceof String) {
    obj.setDescription((String)json.getValue("description"));
  }
  if (json.getValue("name") instanceof String) {
    obj.setName((String)json.getValue("name"));
  }
  if (json.getValue("openTime") instanceof Number) {
    obj.setOpenTime(((Number)json.getValue("openTime")).longValue());
  }
  if (json.getValue("sellerId") instanceof String) {
    obj.setSellerId((String)json.getValue("sellerId"));
  }
}
 
Example 14
Source File: ConsulClientOptions.java    From vertx-consul-client with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor from JSON
 *
 * @param json the JSON
 */
public ConsulClientOptions(JsonObject json) {
  super(json);
  ConsulClientOptionsConverter.fromJson(json, this);
  if (json.getValue("host") instanceof String) {
    setHost((String)json.getValue("host"));
  } else {
    setHost(CONSUL_DEFAULT_HOST);
  }
  if (json.getValue("port") instanceof Number) {
    setPort(((Number)json.getValue("port")).intValue());
  } else {
    setPort(CONSUL_DEFAULT_PORT);
  }
}
 
Example 15
Source File: TestRestServerVerticle.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestServerVerticleWithHttp2(@Mocked Transport transport, @Mocked Vertx vertx,
    @Mocked Context context,
    @Mocked JsonObject jsonObject, @Mocked Future<Void> startFuture) {
  URIEndpointObject endpointObject = new URIEndpointObject("http://127.0.0.1:8080?protocol=http2");
  new Expectations() {
    {
      transport.parseAddress("http://127.0.0.1:8080?protocol=http2");
      result = endpointObject;
    }
  };
  Endpoint endpiont = new Endpoint(transport, "http://127.0.0.1:8080?protocol=http2");

  new Expectations() {
    {
      context.config();
      result = jsonObject;
      jsonObject.getValue(AbstractTransport.ENDPOINT_KEY);
      result = endpiont;
    }
  };
  RestServerVerticle server = new RestServerVerticle();
  boolean status = false;
  try {
    server.init(vertx, context);
    server.start(startFuture);
  } catch (Exception e) {
    status = true;
  }
  Assert.assertFalse(status);
}
 
Example 16
Source File: Order.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
public Order(JsonObject json) {
  OrderConverter.fromJson(json, this);
  if (json.getValue("products") instanceof String) {
    this.products = new JsonArray(json.getString("products"))
      .stream()
      .map(e -> (JsonObject) e)
      .map(ProductTuple::new)
      .collect(Collectors.toList());
  }
}
 
Example 17
Source File: JsonRpcHttpServiceTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void getBlockByHashForUnknownBlock() throws Exception {
  final String id = "123";
  final String blockHashString =
      "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d15273321";
  final Hash blockHash = Hash.fromHexString(blockHashString);
  final RequestBody body =
      RequestBody.create(
          JSON,
          "{\"jsonrpc\":\"2.0\",\"id\":"
              + Json.encode(id)
              + ",\"method\":\"eth_getBlockByHash\", \"params\": [\""
              + blockHashString
              + "\",true]}");

  // Setup mocks
  when(blockchainQueries.blockByHash(eq(blockHash))).thenReturn(Optional.empty());

  try (final Response resp = client.newCall(buildPostRequest(body)).execute()) {
    assertThat(resp.code()).isEqualTo(200);
    // Check general format of result
    final JsonObject json = new JsonObject(resp.body().string());
    testHelper.assertValidJsonRpcResult(json, id);
    // Check result
    final Object result = json.getValue("result");
    // For now, no block will be returned so we should get null
    assertThat(result).isNull();
  }
}
 
Example 18
Source File: VertxExtensionModule.java    From vertx-lang-groovy with Apache License 2.0 4 votes vote down vote up
public static Object putAt(JsonObject json, String key, Object value) {
  Object prev = json.getValue(key);
  json.put(key, value);
  return prev;
}
 
Example 19
Source File: NestedJsonObjectDataObject.java    From vertx-codegen with Apache License 2.0 4 votes vote down vote up
public NestedJsonObjectDataObject(JsonObject json) {
  value = (String)json.getValue("value");
}
 
Example 20
Source File: MongoClientImpl.java    From vertx-mongo-client with Apache License 2.0 3 votes vote down vote up
private JsonObject decodeKeyWhenUseObjectId(JsonObject json) {
  if (!useObjectId) return json;

  Object idField = json.getValue(ID_FIELD, null);
  if (!(idField instanceof JsonObject)) return json;

  Object idString = ((JsonObject) idField).getValue(JsonObjectCodec.OID_FIELD, null);
  if (!(idString instanceof String)) return json;

  json.put(ID_FIELD, idString);

  return json;
}