下面列出了io.vertx.core.json.JsonObject#containsKey ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void handleMessage(CharSequence charSequence, JsonObject message) {
if (!message.containsKey("reply") || !message.containsKey("payload")) return;
var taskId = message.getLong("reply");
var msg = message.getJsonObject("payload");
var future = pending.remove(taskId);
if (future != null) {
if (!future.isDone()) {
future.complete(msg);
}
} else {
var state = pendingBroadcasts.get(taskId);
if (state != null) {
state.handleReply(msg);
}
}
}
@Nonnull
@Override
public JsonObject update(@Nonnull String userId, @Nonnull String guildId, @Nonnull JsonObject payload) {
log.info("Updating player for user {} in guild {} and payload {}", userId, guildId, payload);
var player = andesite.getPlayer(userId, guildId);
if(payload.containsKey("pause")) {
player.audioPlayer().setPaused(payload.getBoolean("pause"));
}
if(payload.containsKey("position")) {
var track = player.audioPlayer().getPlayingTrack();
if(track != null) {
track.setPosition(asLong(payload.getValue("position"), -1));
}
}
if(payload.containsKey("volume")) {
player.audioPlayer().setVolume(payload.getInteger("volume"));
}
if(payload.containsKey("filters")) {
updateFilters(player, payload.getJsonObject("filters"));
}
return player.encodeState();
}
public static OAuthAccessToken getOAuthAccessToken(String appId, String appSecret, String code) {
OAuthAccessToken token = null;
String tockenUrl = getOAuthTokenUrl(appId, appSecret, code);
JsonObject jsonObject = httpsRequest(tockenUrl, HttpMethod.GET, null);
if (null != jsonObject && !jsonObject.containsKey("errcode")) {
token = new OAuthAccessToken();
token.setAccessToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInteger("expires_in"));
token.setOpenid(jsonObject.getString("openid"));
token.setScope(jsonObject.getString("scope"));
} else if (null != jsonObject) {
token = new OAuthAccessToken();
token.setErrcode(jsonObject.getInteger("errcode"));
}
return token;
}
@Override
public String nextStep(String data) {
if (first) {
first = false;
return "user=" + username + "\1auth=Bearer " + password + "\1\1";
} else {
// quick escape
if (data == null) {
return null;
}
try {
// expect a JSON message on error
JsonObject response = new JsonObject(data);
// the response must contain 3 values
if (
response.containsKey("status") &&
response.containsKey("schemes") &&
response.containsKey("scope")) {
LOG.warn("XOAUTH2 Error Response: " + data);
// if there is a next step we're receiving an error
// protocol expects a empty response
return "";
} else {
// this is something totally different (return null)
return null;
}
} catch (RuntimeException e) {
return null;
}
}
}
@Override
public KafkaProducerRecord<byte[], byte[]> toKafkaRecord(String kafkaTopic, Integer partition, Buffer message) {
Integer partitionFromBody = null;
byte[] key = null;
byte[] value = null;
JsonObject json = message.toJsonObject();
if (!json.isEmpty()) {
if (json.containsKey("key")) {
key = Json.encodeToBuffer(json.getValue("key")).getBytes();
}
if (json.containsKey("value")) {
value = Json.encodeToBuffer(json.getValue("value")).getBytes();
}
if (json.containsKey("partition")) {
partitionFromBody = json.getInteger("partition");
}
if (partition != null && partitionFromBody != null) {
throw new IllegalStateException("Partition specified in body and in request path");
}
if (partition != null) {
partitionFromBody = partition;
}
}
KafkaProducerRecord<byte[], byte[]> record = KafkaProducerRecord.create(kafkaTopic, key, value, partitionFromBody);
return record;
}
public DFModelPOPJ(JsonObject json) {
this.id = json.getString("_id");
this.name = json.getString("name");
this.type = json.getString("type");
this.category = json.getString("category");
this.description = json.getString("description");
this.path = json.getString("path");
this.udf = json.getString("udf");
this.createDate = json.getString("createDate");
this.updateDate = json.getString("updateDate");
this.modelInputPara = (json.containsKey("modelInputPara") && json.getValue("modelInputPara") != null) ?
HelpFunc.mapToHashMapFromJson(json.getJsonObject("modelInputPara")) : null;
this.modelOutputPara = json.getString("modelOutputPara");
this.idTrained = json.getString("idTrained");
}
@Override
public Future<@Nullable String> insertWithOptions(String collection, JsonObject document, @Nullable WriteOption writeOption) {
requireNonNull(collection, "collection cannot be null");
requireNonNull(document, "document cannot be null");
JsonObject encodedDocument = encodeKeyWhenUseObjectId(document);
boolean hasCustomId = document.containsKey(ID_FIELD);
MongoCollection<JsonObject> coll = getCollection(collection, writeOption);
Promise<Void> promise = vertx.promise();
coll.insertOne(encodedDocument).subscribe(new CompletionSubscriber<>(promise));
return promise.future().map(v -> hasCustomId ? null : decodeKeyWhenUseObjectId(encodedDocument).getString(ID_FIELD));
}
private JsonObject extractProducerConfiguration(KafkaConnectorOutgoingConfiguration config) {
JsonObject kafkaConfiguration = JsonHelper.asJsonObject(config.config());
// Acks must be a string, even when "1".
kafkaConfiguration.put(ProducerConfig.ACKS_CONFIG, config.getAcks());
if (!kafkaConfiguration.containsKey(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)) {
log.configServers(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, config.getBootstrapServers());
kafkaConfiguration.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, config.getBootstrapServers());
}
if (!kafkaConfiguration.containsKey(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)) {
log.keyDeserializerOmitted();
kafkaConfiguration.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, config.getKeySerializer());
}
// Max inflight
if (!kafkaConfiguration.containsKey(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION)) {
kafkaConfiguration.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, config.getMaxInflightMessages());
}
kafkaConfiguration.remove("channel-name");
kafkaConfiguration.remove("topic");
kafkaConfiguration.remove("connector");
kafkaConfiguration.remove("partition");
kafkaConfiguration.remove("key");
kafkaConfiguration.remove("max-inflight-messages");
return kafkaConfiguration;
}
protected void assertEquals(JsonObject expected, JsonObject actual) {
//Test cases will fail unless we map the $oid first. This is because the original document is
//transformed with an object ID. Probably shouldn't do that.
if (actual.containsKey("_id")) {
if (actual.getValue("_id") instanceof String) {
actual.put("_id", new JsonObject().put("$oid", actual.getString("_id")));
}
}
super.assertEquals(expected, actual);
}
@Override
protected Buffer getPayload(final JsonObject loraMessage) {
Objects.requireNonNull(loraMessage);
if (loraMessage.containsKey(FIELD_TTN_PAYLOAD_RAW) && loraMessage.getValue(FIELD_TTN_PAYLOAD_RAW) == null) {
// ... this is an empty payload message, still valid.
return Buffer.buffer();
}
return LoraUtils.getChildObject(loraMessage, FIELD_TTN_PAYLOAD_RAW, String.class)
.map(s -> Buffer.buffer(Base64.getDecoder().decode(s)))
.orElseThrow(() -> new LoraProviderMalformedPayloadException("message does not contain Base64 encoded payload property"));
}
private boolean anyRegistrationFieldIsMissing(JsonObject body) {
return !(body.containsKey("username") &&
body.containsKey("password") &&
body.containsKey("email") &&
body.containsKey("city") &&
body.containsKey("deviceId") &&
body.containsKey("makePublic"));
}
private void searchPropAndRemoveInSchema(JsonObject object, String propName) {
if (object.containsKey("allOf") || object.containsKey("anyOf") || object.containsKey("oneOf")) {
object.getJsonArray("allOf", object.getJsonArray("anyOf", object.getJsonArray("oneOf")))
.forEach(j -> searchPropAndRemoveInSchema((JsonObject) j, propName));
} else {
if (object.containsKey("properties")) {
object.getJsonObject("properties").remove(propName);
}
if (object.containsKey("required")) {
object.getJsonArray("required").remove(propName);
}
}
}
private static boolean isEmptyObject(JsonObject json, String key) {
try {
if (json == null) {
return true;
}
if (!json.containsKey(key)) {
return true;
}
JsonObject s = json.getJsonObject(key);
return s == null;
} catch (RuntimeException e) {
return true;
}
}
public static AccessToken getAccessToken(String appId, String appSecret) {
AccessToken token = null;
String tockenUrl = WxApi.getTokenUrl(appId, appSecret);
JsonObject jsonObject = httpsRequest(tockenUrl, HttpMethod.GET, null);
if (null != jsonObject && !jsonObject.containsKey("errcode")) {
token = new AccessToken();
token.setAccessToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInteger("expires_in"));
} else if (null != jsonObject) {
System.out.println("获取AccessToken失败,原因=" + jsonObject.getString("errmsg"));
token = new AccessToken();
token.setErrcode(jsonObject.getInteger("errcode"));
}
return token;
}
public static JSTicket getJSTicket(String token) {
JSTicket jsTicket = null;
String jsTicketUrl = WxApi.getJsApiTicketUrl(token);
JsonObject jsonObject = httpsRequest(jsTicketUrl, HttpMethod.GET, null);
if (null != jsonObject && jsonObject.containsKey("errcode") && jsonObject.getInteger("errcode") == 0) {
jsTicket = new JSTicket();
jsTicket.setTicket(jsonObject.getString("ticket"));
jsTicket.setExpiresIn(jsonObject.getInteger("expires_in"));
} else if (null != jsonObject) {
jsTicket = new JSTicket();
jsTicket.setErrcode(jsonObject.getInteger("errcode"));
}
return jsTicket;
}
/**
* Create a OAuth2Auth provider for Keycloak
*
* @param flow the oauth2 flow to use
* @param config the json config file exported from Keycloak admin console
* @param httpClientOptions custom http client options
*/
static OAuth2Auth create(Vertx vertx, OAuth2FlowType flow, JsonObject config, HttpClientOptions httpClientOptions) {
final OAuth2Options options = new OAuth2Options()
.setHttpClientOptions(httpClientOptions);
options.setFlow(flow);
if (config.containsKey("resource")) {
options.setClientID(config.getString("resource"));
}
// keycloak conversion to oauth2 options
if (config.containsKey("auth-server-url")) {
options.setSite(config.getString("auth-server-url"));
}
if (config.containsKey("credentials") && config.getJsonObject("credentials").containsKey("secret")) {
options.setClientSecret(config.getJsonObject("credentials").getString("secret"));
}
if (config.containsKey("public-client") && config.getBoolean("public-client", false)) {
options.setUseBasicAuthorizationHeader(true);
}
if (config.containsKey("realm")) {
final String realm = config.getString("realm");
options.setAuthorizationPath("/realms/" + realm + "/protocol/openid-connect/auth");
options.setTokenPath("/realms/" + realm + "/protocol/openid-connect/token");
options.setRevocationPath(null);
options.setLogoutPath("/realms/" + realm + "/protocol/openid-connect/logout");
options.setUserInfoPath("/realms/" + realm + "/protocol/openid-connect/userinfo");
// keycloak follows the RFC7662
options.setIntrospectionPath("/realms/" + realm + "/protocol/openid-connect/token/introspect");
// keycloak follows the RFC7517
options.setJwkPath("/realms/" + realm + "/protocol/openid-connect/certs");
}
if (config.containsKey("realm-public-key")) {
options.addPubSecKey(new PubSecKeyOptions()
.setAlgorithm("RS256")
.setPublicKey(config.getString("realm-public-key")));
}
return OAuth2Auth
.create(vertx, options)
.rbacHandler(KeycloakRBAC.create(options));
}
/**
* This is commonly used utility
*
* @param routingContext This is the connect from REST API
* @param webClient This is vertx non-blocking rest client used for forwarding
* @param schemaRegistryRestHost Schema Registry Rest Host
* @param schemaRegistryRestPort Schema Registry Rest Port
* @param successMsg Message to response when succeeded
* @param successCode Status code to response when succeeded
* @param errorMsg Message to response when failed
* @param errorCode Status code to response when failed
*/
public static void addOneSchemaCommon(RoutingContext routingContext, WebClient webClient,
String schemaRegistryRestHost, int schemaRegistryRestPort,
String successMsg, int successCode, String errorMsg, int errorCode) {
JsonObject jsonObj = routingContext.getBodyAsJson();
JsonObject schemaObj = jsonObj.getJsonObject(ConstantApp.SCHEMA_REGISTRY_KEY_SCHEMA);
if(!jsonObj.containsKey("id") && !jsonObj.containsKey(ConstantApp.SCHEMA_REGISTRY_KEY_SUBJECT))
LOG.error(DFAPIMessage.logResponseMessage(9040, "Subject of Schema is missing."));
// get subject from id (web ui assigned) and assign it to subject
String subject = jsonObj.containsKey("id")? jsonObj.getString("id"):
jsonObj.getString(ConstantApp.SCHEMA_REGISTRY_KEY_SUBJECT);
// Set schema name from subject if it does not has name or empty
if(!schemaObj.containsKey("name") || schemaObj.getString("name").isEmpty()) {
schemaObj.put("name", subject);
jsonObj.put(ConstantApp.SCHEMA_REGISTRY_KEY_SCHEMA, schemaObj);
}
String compatibility = jsonObj.containsKey(ConstantApp.SCHEMA_REGISTRY_KEY_COMPATIBILITY) ?
jsonObj.getString(ConstantApp.SCHEMA_REGISTRY_KEY_COMPATIBILITY) : "NONE";
webClient.post(schemaRegistryRestPort, schemaRegistryRestHost,
ConstantApp.SR_REST_URL_SUBJECTS + "/" + subject + ConstantApp.SR_REST_URL_VERSIONS)
.putHeader(ConstantApp.HTTP_HEADER_CONTENT_TYPE, ConstantApp.AVRO_REGISTRY_CONTENT_TYPE)
.sendJsonObject( new JsonObject()
.put(ConstantApp.SCHEMA_REGISTRY_KEY_SCHEMA, schemaObj.toString()),
// Must toString above according SR API spec.
ar -> {
if (ar.succeeded()) {
LOG.info(DFAPIMessage.logResponseMessage(successCode, subject + "-SCHEMA"));
// Once successful, we will update schema compatibility
webClient.put(schemaRegistryRestPort, schemaRegistryRestHost,
ConstantApp.SR_REST_URL_CONFIG + "/" + subject)
.putHeader(ConstantApp.HTTP_HEADER_CONTENT_TYPE,
ConstantApp.AVRO_REGISTRY_CONTENT_TYPE)
.sendJsonObject(new JsonObject()
.put(ConstantApp.SCHEMA_REGISTRY_KEY_COMPATIBILITY, compatibility),
arc -> {
if (arc.succeeded()) {
HelpFunc.responseCorsHandleAddOn(routingContext.response())
.setStatusCode(ConstantApp.STATUS_CODE_OK)
.end(Json.encodePrettily(jsonObj));
LOG.info(DFAPIMessage.logResponseMessage(1017,
successMsg + "-COMPATIBILITY"));
} else {
// If response is failed, repose df ui and still keep the task
HelpFunc.responseCorsHandleAddOn(routingContext.response())
.setStatusCode(ConstantApp.STATUS_CODE_BAD_REQUEST)
.end(DFAPIMessage.getResponseMessage(errorCode,
subject, errorMsg + "-COMPATIBILITY"));
LOG.info(DFAPIMessage.logResponseMessage(errorCode,
subject + "-COMPATIBILITY"));
}
}
);
} else {
// If response is failed, repose df ui and still keep the task
HelpFunc.responseCorsHandleAddOn(routingContext.response())
.setStatusCode(ConstantApp.STATUS_CODE_BAD_REQUEST)
.end(DFAPIMessage.getResponseMessage(errorCode, subject,
errorMsg + "-SCHEMA"));
LOG.info(DFAPIMessage.logResponseMessage(errorCode, subject + "-SCHEMA"));
}
}
);
}
public static boolean isSchemaObject(JsonObject schema) {
return "object".equals(schema.getString("type")) || schema.containsKey("properties");
}
public static void getConfigFromFile() throws ClassCastException{
String name = GlobalConfig.get().getConfigFile();
if (name == null)
return;
String data = GlobalConfig.readConfigFile(name);
JsonObject jsonobj = new JsonObject(data);
if (jsonobj.containsKey(SERVER_ADDR)) {
String server = jsonobj.getString(SERVER_ADDR);
log.debug("CFG:Server address: " + server);
GlobalConfig.get().setServer(server);
}
if (jsonobj.containsKey(SERVER_PORT)) {
int port = jsonobj.getInteger(SERVER_PORT).intValue();
log.debug("CFG:Server port: " + port);
GlobalConfig.get().setPort(port);
}
if (jsonobj.containsKey(LOCAL_PORT)) {
int lport = jsonobj.getInteger(LOCAL_PORT).intValue();
log.debug("CFG:Local port: " + lport);
GlobalConfig.get().setLocalPort(lport);
}
if (jsonobj.containsKey(PASSWORD)) {
String password = jsonobj.getString(PASSWORD);
log.debug("CFG:Password: " + password);
GlobalConfig.get().setPassowrd(password);
}
if (jsonobj.containsKey(METHOD)) {
String method = jsonobj.getString(METHOD);
log.debug("CFG:Crypto method: " + method);
GlobalConfig.get().setMethod(method);
}
if (jsonobj.containsKey(TIMEOUT)) {
int timeout = jsonobj.getInteger(TIMEOUT).intValue();
log.debug("CFG:Timeout: " + timeout);
GlobalConfig.get().setTimeout(timeout);
}
if (jsonobj.containsKey(SERVER_MODE)) {
boolean isServer = jsonobj.getBoolean(SERVER_MODE).booleanValue();
log.debug("CFG:Running on server mode: " + isServer);
GlobalConfig.get().setServerMode(isServer);
}
}
public static AccountFans syncAccountFans(String openId, Account mpAccount){
String accessToken = getAccessToken(mpAccount);
String url = WxApi.getFansInfoUrl(accessToken, openId);
JsonObject jsonObj = WxApi.httpsRequest(url, "GET", null);
if (null != jsonObj) {
if(jsonObj.containsKey("errcode")){
int errorCode = jsonObj.getInteger("errcode");
System.out.println(String.format("获取用户信息失败 errcode:{} errmsg:{}", errorCode, ErrCode.errMsg(errorCode)));
return null;
}else{
AccountFans fans = new AccountFans();
fans.setOpenId(jsonObj.getString("openid"));// 用户的标识
fans.setSubscribeStatus(new Integer(jsonObj.getInteger("subscribe")));// 关注状态(1是关注,0是未关注),未关注时获取不到其余信息
if(jsonObj.containsKey("subscribe_time")){
fans.setSubscribeTime(jsonObj.getString("subscribe_time"));// 用户关注时间
}
if(jsonObj.containsKey("nickname")){// 昵称
try {
String nickname = jsonObj.getString("nickname");
fans.setNickname(nickname.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
if(jsonObj.containsKey("sex")){// 用户的性别(1是男性,2是女性,0是未知)
fans.setGender(jsonObj.getInteger("sex"));
}
if(jsonObj.containsKey("language")){// 用户的语言,简体中文为zh_CN
fans.setLanguage(jsonObj.getString("language"));
}
if(jsonObj.containsKey("country")){// 用户所在国家
fans.setCountry(jsonObj.getString("country"));
}
if(jsonObj.containsKey("province")){// 用户所在省份
fans.setProvince(jsonObj.getString("province"));
}
if(jsonObj.containsKey("city")){// 用户所在城市
fans.setCity(jsonObj.getString("city"));
}
if(jsonObj.containsKey("headimgurl")){// 用户头像
fans.setHeadimgurl(jsonObj.getString("headimgurl"));
}
if(jsonObj.containsKey("remark")){
fans.setRemark(jsonObj.getString("remark"));
}
fans.setStatus(1);
fans.setCreatetime(new Date());
return fans;
}
}
return null;
}