下面列出了io.vertx.core.json.JsonObject#getString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public ParameterProcessor generate(JsonObject parameter, JsonObject fakeSchema, JsonPointer parameterPointer, ParameterLocation parsedLocation, String parsedStyle, GeneratorContext context) {
SchemaHolder schemas = context.getSchemaHolder(
parameter.getJsonObject("schema", new JsonObject()),
fakeSchema,
parameterPointer.copy().append("schema")
);
return new ParameterProcessorImpl(
parameter.getString("name"),
parsedLocation,
!parameter.getBoolean("required", false),
new SingleValueParameterParser(
parameter.getString("name"),
new ExplodedSimpleObjectValueParser(
ValueParserInferenceUtils.infeerPropertiesParsersForObjectSchema(schemas.getFakeSchema()),
ValueParserInferenceUtils.infeerPatternPropertiesParsersForObjectSchema(schemas.getFakeSchema()),
ValueParserInferenceUtils.infeerAdditionalPropertiesParserForObjectSchema(schemas.getFakeSchema())
)
),
schemas.getValidator()
);
}
public static byte[] createQRCodeLimit(String qrcodeStr, Account mpAccount){
if(!StringUtils.isBlank(qrcodeStr)){
String accessToken = getAccessToken(mpAccount);
String postBody = WxApi.getQrcodeLimitJson(qrcodeStr);
JsonObject jsObj = WxApi.httpsRequest(WxApi.getCreateQrcodeUrl(accessToken), HttpMethod.POST, postBody);
if(jsObj != null){
String ticket = jsObj.getString("ticket");
if(!StringUtils.isBlank(ticket)){
jsObj = WxApi.httpsRequest(WxApi.getShowQrcodeUrl(ticket), HttpMethod.GET);
}
return null;
}
}
return null;
}
@Override
public ParameterProcessor generate(JsonObject parameter, JsonObject fakeSchema, JsonPointer parameterPointer, ParameterLocation parsedLocation, String parsedStyle, GeneratorContext context) {
SchemaHolder schemas = context.getSchemaHolder(
parameter.getJsonObject("schema", new JsonObject()),
fakeSchema,
parameterPointer.copy().append("schema")
);
return new ParameterProcessorImpl(
parameter.getString("name"),
parsedLocation,
!parameter.getBoolean("required", false),
new SingleValueParameterParser(
parameter.getString("name"),
new ExplodedMatrixArrayValueParser(ValueParserInferenceUtils.infeerItemsParserForArraySchema(schemas.getFakeSchema()))
),
schemas.getValidator()
);
}
/**
* Creates a new {@link FileSet} from a json object.
*
* @param vertx the Vert.x instance
* @param root the root of the fileset (directory)
* @param set the configuration
*/
public FileSet(Vertx vertx, File root, JsonObject set) {
this.vertx = vertx;
this.root = root;
this.pattern = set.getString("pattern");
if (this.pattern == null) {
throw new IllegalArgumentException("Each file set needs to contain a `pattern`");
}
this.rawData = set.getBoolean("raw-data", false);
String format = set.getString("format", "json");
this.processor = Processors.get(format);
if (this.processor == null) {
throw new IllegalArgumentException("Unknown configuration format `" + format + "`, supported types are " +
Processors.getSupportedFormats());
}
}
private static AuthProvider authenticateBasic(JsonObject apimanConfig) {
return (authInfo, resultHandler) -> {
String storedUsername = apimanConfig.getString("username");
String storedPassword = apimanConfig.getString("password");
if (storedUsername == null || storedPassword == null) {
resultHandler.handle(Future.failedFuture("Credentials not set in configuration."));
return;
}
String username = authInfo.getString("username");
String password = StringUtils.chomp(authInfo.getString("password"));
if (storedUsername.equals(username) && storedPassword.equals(password)) {
resultHandler.handle(Future.succeededFuture());
} else {
resultHandler.handle(Future.failedFuture("No such user, or password incorrect."));
}
};
}
@Test
public void largeStringId() throws Exception {
final StringBuilder idBuilder = new StringBuilder();
for (int i = 0; i < 1000; i++) {
idBuilder.append(i);
}
final String id = idBuilder.toString();
final RequestBody body =
RequestBody.create(
JSON,
"{\"jsonrpc\":\"2.0\",\"id\":"
+ Json.encode(id)
+ ",\"method\":\"web3_clientVersion\"}");
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 String result = json.getString("result");
assertThat(result).isEqualTo(CLIENT_VERSION);
}
}
@Test
public void web3ClientVersionSuccessful() throws Exception {
final String id = "123";
final RequestBody body =
RequestBody.create(
JSON,
"{\"jsonrpc\":\"2.0\",\"id\":"
+ Json.encode(id)
+ ",\"method\":\"web3_clientVersion\"}");
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 String result = json.getString("result");
assertThat(result).isEqualTo(CLIENT_VERSION);
}
}
/**
* Constructor from JSON
*
* @param options the JSON
*/
public SessionOptions(JsonObject options) {
this.lockDelay = cutSeconds(options.getString(LOCK_KEY));
this.name = options.getString(NAME_KEY);
this.node = options.getString(NODE_KEY);
this.checks = listOf(options.getJsonArray(CHECKS_KEY));
this.behavior = SessionBehavior.of(options.getString(BEHAVIOR_KEY));
this.ttl = cutSeconds(options.getString(TTL_KEY));
}
public T merge(JsonObject document) {
Long id = document.getLong("id");
checkNotNull(id, "id cannot be null");
checkState(id == this.id, "id was %s, expected %s", id, this.id);
setReadMd5(document.getBinary("read_md5"));
setReadSha512(document.getBinary("read_sha512"));
setReadLength(document.getLong("read_length"));
setWriteSha512(document.getBinary("write_sha512"));
setWriteLength(document.getLong("write_length"));
isTinyData = document.getBoolean("is_tiny_data");
tinyData = document.getBinary("tiny_data");
isTinyDataDeleted = document.getBoolean("is_tiny_data_deleted");
String cipherKey = document.getString("container_key_id");
byte[] cipherSalt = document.getBinary("cipher_salt");
segmentCipher = new SegmentCipher(cipherKey, cipherSalt);
JsonArray blobJsonArray = document.getJsonArray("blobs");
this.blobs.clear();
if (blobJsonArray != null) {
for (Object o : blobJsonArray) {
JsonObject jsonObject = (JsonObject) o;
TransientBlobReference transientBlobReference = new TransientBlobReference(this).merge(jsonObject);
this.blobs.add(transientBlobReference);
}
}
return (T) this;
}
/**
* @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 VxApiAuthJwtTokenImpl(JsonObject obj) {
if (obj == null) {
throw new NullPointerException("JwtToken认证方式的配置文件不能为空!");
}
if (obj.getValue("apiTokenName") instanceof String) {
this.apiTokenName = obj.getString("apiTokenName");
} else {
this.apiTokenName = VX_API_JWT_TOKEN_NAME;
}
if (obj.getValue("userTokenName") instanceof String) {
this.userTokenName = obj.getString("userTokenName");
} else {
this.userTokenName = VX_API_USER_TOKEN_NAME;
}
if(obj.getJsonArray("secretKeys") instanceof JsonArray){
this.userKeys=obj.getJsonArray("secretKeys");
}
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);
}
}
public DeleteResponse(JsonObject json) {
super(json);
this.index = json.getString(JSON_FIELD_INDEX);
this.type = json.getString(JSON_FIELD_TYPE);
this.id = json.getString(JSON_FIELD_ID);
this.version = json.getLong(JSON_FIELD_VERSION);
this.deleted = json.getBoolean(JSON_FIELD_DELETED);
}
public static PermissionBasedAuthorization decode(JsonObject json) throws IllegalArgumentException {
Objects.requireNonNull(json);
if (TYPE_PERMISSION_BASED_AUTHORIZATION.equals(json.getString(FIELD_TYPE))) {
PermissionBasedAuthorization result = PermissionBasedAuthorization.create(json.getString(FIELD_PERMISSION));
if (json.getString(FIELD_RESOURCE) != null) {
result.setResource(json.getString(FIELD_RESOURCE));
}
return result;
}
return null;
}
public static Realm createRealm(JsonObject config) {
JndiLdapRealm ldapRealm = new JndiLdapRealm();
JndiLdapContextFactory factory = new JndiLdapContextFactory();
String userDNTemplate = config.getString(LDAP_USER_DN_TEMPLATE_FIELD);
if (userDNTemplate != null) {
ldapRealm.setUserDnTemplate(userDNTemplate);
}
String url = config.getString(LDAP_URL);
if (url != null) {
factory.setUrl(url);
}
String authenticationMechanism = config.getString(LDAP_AUTHENTICATION_MECHANISM);
if (authenticationMechanism != null) {
factory.setAuthenticationMechanism(authenticationMechanism);
}
String contextFactoryClassName = config.getString(LDAP_CONTEXT_FACTORY_CLASS_NAME);
if (contextFactoryClassName != null) {
factory.setContextFactoryClassName(contextFactoryClassName);
}
boolean poolingEnabled = config.getBoolean(LDAP_POOLING_ENABLED, false);
factory.setPoolingEnabled(poolingEnabled);
String referral = config.getString(LDAP_REFERRAL);
if (referral != null) {
factory.setReferral(referral);
}
String systemUsername = config.getString(LDAP_SYSTEM_USERNAME);
if (systemUsername != null) {
factory.setSystemUsername(systemUsername);
}
String systemPassword = config.getString(LDAP_SYSTEM_PASSWORD);
if (systemPassword != null) {
factory.setSystemPassword(systemPassword);
}
ldapRealm.setContextFactory(factory);
ldapRealm.init();
return ldapRealm;
}
private Optional<BigInteger> getStringAsOptionalBigInteger(
final JsonObject object, final String key) {
final String value = object.getString(key);
return Optional.of(new BigInteger(value.substring(2), 16));
}
public MongoClientOptionsParser(Vertx vertx, JsonObject config) {
Objects.requireNonNull(config);
MongoClientSettings.Builder options = MongoClientSettings.builder();
options.codecRegistry(CodecRegistries.fromRegistries(commonCodecRegistry, CodecRegistries.fromCodecs(new JsonObjectCodec(config))));
// All parsers should support connection_string first
String cs = config.getString("connection_string");
ConnectionString connectionString = (cs == null) ? null : new ConnectionString(cs);
String csDatabase = (connectionString != null) ? connectionString.getDatabase() : null;
this.database = csDatabase != null ? csDatabase : config.getString("db_name", MongoClient.DEFAULT_DB_NAME);
// ClusterSettings
ClusterSettings clusterSettings = new ClusterSettingsParser(connectionString, config).settings();
options.applyToClusterSettings(builder -> builder.applySettings(clusterSettings));
// ConnectionPoolSettings
ConnectionPoolSettings connectionPoolSettings = new ConnectionPoolSettingsParser(connectionString, config).settings();
options.applyToConnectionPoolSettings(builder -> builder.applySettings(connectionPoolSettings));
// Credentials
// The previous mongo client supported credentials list but their new implementation supports only
// one credentials. The deprecated code path resorts to using the last credentials if a list is passed
// we are doing the same here.
List<MongoCredential> credentials = new CredentialListParser(config).credentials();
if (!credentials.isEmpty())
options.credential(credentials.get(credentials.size() - 1));
// SocketSettings
SocketSettings socketSettings = new SocketSettingsParser(connectionString, config).settings();
options.applyToSocketSettings(builder -> builder.applySettings(socketSettings));
// Transport type
new StreamTypeParser(config).streamFactory().ifPresent(options::streamFactoryFactory);
// SSLSettings
SslSettings sslSettings = new SSLSettingsParser(connectionString, config).settings(vertx);
options.applyToSslSettings(builder -> builder.applySettings(sslSettings));
// WriteConcern
WriteConcern writeConcern = new WriteConcernParser(connectionString, config).writeConcern();
if (writeConcern != null) {
options.writeConcern(writeConcern);
}
// ReadConcern
maybeReadConcern(connectionString, config).ifPresent(options::readConcern);
// ReadPreference
ReadPreference readPreference = new ReadPreferenceParser(connectionString, config).readPreference();
if (readPreference != null) {
options.readPreference(readPreference);
}
// ServerSettings
ServerSettings serverSettings = new ServerSettingsParser(config).settings();
options.applyToServerSettings(builder -> builder.applySettings(serverSettings));
this.settings = options.build();
}
public HeaderBlob(JsonObject jsonObject) {
this.volume = jsonObject.getString(X_CONTENT_VOLUME);
this.position = jsonObject.getLong(X_CONTENT_POSITION);
this.length = jsonObject.getLong(X_CONTENT_LENGTH);
}
/**
* Starts the bridge.
*
* @param vertx the vert.x instance
* @param publisher the service discovery instance
* @param configuration the bridge configuration if any
* @param completion future to assign with completion status
*/
@Override
public void start(Vertx vertx, ServicePublisher publisher, JsonObject configuration, Promise<Void> completion) {
this.publisher = publisher;
this.vertx = vertx;
DefaultDockerClientConfig.Builder builder = DefaultDockerClientConfig.createDefaultConfigBuilder();
String dockerCertPath = configuration.getString("docker-cert-path");
String dockerCfgPath = configuration.getString("docker-cfg-path");
String email = configuration.getString("docker-registry-email");
String password = configuration.getString("docker-registry-password");
String username = configuration.getString("docker-registry-username");
String host = configuration.getString("docker-host");
boolean tlsVerify = configuration.getBoolean("docker-tls-verify", true);
String registry
= configuration.getString("docker-registry-url", "https://index.docker.io/v1/");
String version = configuration.getString("version");
if (dockerCertPath != null) {
builder.withDockerCertPath(dockerCertPath);
}
if (dockerCfgPath != null) {
builder.withDockerConfig(dockerCfgPath);
}
if (email != null) {
builder.withRegistryEmail(email);
}
if (password != null) {
builder.withRegistryPassword(password);
}
if (username != null) {
builder.withRegistryUsername(username);
}
if (host != null) {
builder.withDockerHost(host);
}
if (registry != null) {
builder.withRegistryUrl(registry);
}
if (version != null) {
builder.withApiVersion(version);
}
builder.withDockerTlsVerify(tlsVerify);
DockerClientConfig config = builder.build();
if (config.getDockerHost().getScheme().equalsIgnoreCase("unix")) {
try {
this.host = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
completion.fail(e);
}
} else {
this.host = config.getDockerHost().getHost();
}
client = DockerClientBuilder.getInstance(config).build();
long period = configuration.getLong("scan-period", 3000L);
if (period > 0) {
timer = vertx.setPeriodic(period, l -> {
scan(null);
});
}
scan(completion);
}
public static String getUserName(Principal principal) {
JsonObject object = new JsonObject(principal.getName());
return object.getString("username");
}
private Future<JsonObject> determineTargetInstanceJson(final JsonObject adapterInstancesJson, final String deviceId,
final List<String> viaGateways, final Span span) {
final JsonArray instancesArray = adapterInstancesJson.getJsonArray(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCES);
if (instancesArray == null || instancesArray.isEmpty()) {
return createAndLogInternalServerErrorFuture(span, "Invalid result JSON; field '"
+ DeviceConnectionConstants.FIELD_ADAPTER_INSTANCES + "' is null or empty");
}
final JsonObject targetInstanceObject;
try {
if (instancesArray.size() == 1) {
targetInstanceObject = instancesArray.getJsonObject(0);
} else {
targetInstanceObject = chooseTargetGatewayAndAdapterInstance(instancesArray);
}
} catch (final ClassCastException e) {
return createAndLogInternalServerErrorFuture(span, "Invalid result JSON: " + e.toString());
}
final String targetDevice = targetInstanceObject.getString(DeviceConnectionConstants.FIELD_PAYLOAD_DEVICE_ID);
final String targetAdapterInstance = targetInstanceObject.getString(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCE_ID);
if (targetDevice == null || targetAdapterInstance == null) {
return createAndLogInternalServerErrorFuture(span, "Invalid result JSON, missing target device and/or adapter instance");
}
if (!targetDevice.equals(deviceId)) {
// target device is a gateway
if (!viaGateways.contains(targetDevice)) {
return createAndLogInternalServerErrorFuture(span,
"Invalid result JSON, target gateway " + targetDevice + " is not in via gateways list");
}
span.setTag(MessageHelper.APP_PROPERTY_GATEWAY_ID, targetDevice);
}
final String choiceInfo = instancesArray.size() > 1 ? " chosen from " + instancesArray.size() + " entries" : "";
final String gatewayInfo = !targetDevice.equals(deviceId) ? " gateway '" + targetDevice + "' and" : "";
final String infoMsg = String.format("command target%s:%s adapter instance '%s'", choiceInfo, gatewayInfo, targetAdapterInstance);
LOG.debug(infoMsg);
span.log(infoMsg);
span.setTag(MessageHelper.APP_PROPERTY_ADAPTER_INSTANCE_ID, targetAdapterInstance);
return Future.succeededFuture(targetInstanceObject);
}
public String sendDataLegacy(final byte[] data, final Box.PublicKey sender, final Box.PublicKey... recipients)
throws IOException {
final JsonObject responseJson = createSendRequestLegacy(data, sender, recipients);
return responseJson.getString("key");
}