Java源码示例:io.vertx.core.json.JsonArray
示例1
private Buffer convert(Object payload) {
if (payload instanceof JsonObject) {
return new Buffer(((JsonObject) payload).toBuffer());
}
if (payload instanceof JsonArray) {
return new Buffer(((JsonArray) payload).toBuffer());
}
if (payload instanceof String || payload.getClass().isPrimitive()) {
return new Buffer(io.vertx.core.buffer.Buffer.buffer(payload.toString()));
}
if (payload instanceof byte[]) {
return new Buffer(io.vertx.core.buffer.Buffer.buffer((byte[]) payload));
}
if (payload instanceof Buffer) {
return (Buffer) payload;
}
if (payload instanceof io.vertx.core.buffer.Buffer) {
return new Buffer((io.vertx.core.buffer.Buffer) payload);
}
// Convert to Json
return new Buffer(Json.encodeToBuffer(payload));
}
示例2
@Override
public void insertUser(String username, String password, List<String> roles, List<String> permissions,
Handler<AsyncResult<String>> resultHandler) {
JsonObject principal = new JsonObject();
principal.put(getUsernameField(), username);
if (roles != null) {
principal.put(mongoAuthorizationOptions.getRoleField(), new JsonArray(roles));
}
if (permissions != null) {
principal.put(mongoAuthorizationOptions.getPermissionField(), new JsonArray(permissions));
}
if (getHashStrategy().getSaltStyle() == HashSaltStyle.COLUMN) {
principal.put(getSaltField(), DefaultHashStrategy.generateSalt());
}
User user = createUser(principal);
String cryptPassword = getHashStrategy().computeHash(password, user);
principal.put(getPasswordField(), cryptPassword);
mongoClient.save(getCollectionName(), user.principal(), resultHandler);
}
示例3
private Handler<AsyncResult<Set<Character>>> createSetCharHandler(Message msg) {
return res -> {
if (res.failed()) {
if (res.cause() instanceof ServiceException) {
msg.reply(res.cause());
} else {
msg.reply(new ServiceException(-1, res.cause().getMessage()));
}
} else {
JsonArray arr = new JsonArray();
for (Character chr: res.result()) {
arr.add((int) chr);
}
msg.reply(arr);
}
};
}
示例4
public Something(
Integer someid,
String somestring,
Long somehugenumber,
Short somesmallnumber,
Integer someregularnumber,
Double somedouble,
SomethingSomeenum someenum,
JsonObject somejsonobject,
JsonArray somejsonarray,
LocalDateTime sometimestamp
) {
this.someid = someid;
this.somestring = somestring;
this.somehugenumber = somehugenumber;
this.somesmallnumber = somesmallnumber;
this.someregularnumber = someregularnumber;
this.somedouble = somedouble;
this.someenum = someenum;
this.somejsonobject = somejsonobject;
this.somejsonarray = somejsonarray;
this.sometimestamp = sometimestamp;
}
示例5
@Override
public Buffer toMessages(KafkaConsumerRecords<byte[], byte[]> records) {
JsonArray jsonArray = new JsonArray();
for (int i = 0; i < records.size(); i++) {
JsonObject jsonObject = new JsonObject();
KafkaConsumerRecord<byte[], byte[]> record = records.recordAt(i);
jsonObject.put("topic", record.topic());
jsonObject.put("key", record.key() != null ?
Json.decodeValue(Buffer.buffer(record.key())) : null);
jsonObject.put("value", record.value() != null ?
Json.decodeValue(Buffer.buffer(record.value())) : null);
jsonObject.put("partition", record.partition());
jsonObject.put("offset", record.offset());
jsonArray.add(jsonObject);
}
return jsonArray.toBuffer();
}
示例6
@Test
public void testDecodeJsonObject(TestContext ctx) {
String script = "SELECT JSON_OBJECT(\n" +
" 'test_string', 'hello',\n" +
" 'test_number', 12345,\n" +
" 'test_boolean', true,\n" +
" 'test_null', null,\n" +
" 'test_json_object', JSON_OBJECT('key', 'value'),\n" +
" 'test_json_array', JSON_ARRAY(1, 2, 3)\n" +
" ) json;";
JsonObject expected = new JsonObject()
.put("test_string", "hello")
.put("test_number", 12345)
.put("test_boolean", true)
.put("test_null", (Object) null)
.put("test_json_object", new JsonObject().put("key", "value"))
.put("test_json_array", new JsonArray().add(1).add(2).add(3));
testDecodeJson(ctx, script, expected, row -> ctx.assertEquals(expected, row.get(JsonObject.class, 0)));
}
示例7
/**
* Asserts the the given result JSON of the <em>getCommandHandlingAdapterInstances</em> method contains an
* "adapter-instances" entry with the given device id and adapter instance id.
*/
private void assertGetInstancesResultMapping(final JsonObject resultJson, final String deviceId,
final String adapterInstanceId) {
assertNotNull(resultJson);
final JsonArray adapterInstancesJson = resultJson
.getJsonArray(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCES);
assertNotNull(adapterInstancesJson);
boolean entryFound = false;
for (int i = 0; i < adapterInstancesJson.size(); i++) {
final JsonObject entry = adapterInstancesJson.getJsonObject(i);
if (deviceId.equals(entry.getString(DeviceConnectionConstants.FIELD_PAYLOAD_DEVICE_ID))) {
entryFound = true;
assertEquals(adapterInstanceId, entry.getString(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCE_ID));
}
}
assertTrue(entryFound);
}
示例8
public static void fromJson(Iterable<java.util.Map.Entry<String, Object>> json, SetterAdderDataObject obj) {
for (java.util.Map.Entry<String, Object> member : json) {
switch (member.getKey()) {
case "values":
if (member.getValue() instanceof JsonArray) {
java.util.ArrayList<java.lang.String> list = new java.util.ArrayList<>();
((Iterable<Object>)member.getValue()).forEach( item -> {
if (item instanceof String)
list.add((String)item);
});
obj.setValues(list);
}
break;
}
}
}
示例9
private <T> List<T> convertList(List list) {
if (list.isEmpty()) {
return (List<T>) list;
}
Object elem = list.get(0);
if (!(elem instanceof Map) && !(elem instanceof List)) {
return (List<T>) list;
} else {
Function<Object, T> converter;
if (elem instanceof List) {
converter = object -> (T) new JsonArray((List) object);
} else {
converter = object -> (T) new JsonObject((Map) object);
}
return (List<T>) list.stream().map(converter).collect(Collectors.toList());
}
}
示例10
void methodWithSetHandlerParams(
Handler<AsyncResult<Set<Byte>>> setByteHandler,
Handler<AsyncResult<Set<Short>>> setShortHandler,
Handler<AsyncResult<Set<Integer>>> setIntHandler,
Handler<AsyncResult<Set<Long>>> setLongHandler,
Handler<AsyncResult<Set<Float>>> setFloatHandler,
Handler<AsyncResult<Set<Double>>> setDoubleHandler,
Handler<AsyncResult<Set<Boolean>>> setBooleanHandler,
Handler<AsyncResult<Set<Character>>> setCharHandler,
Handler<AsyncResult<Set<String>>> setStrHandler,
Handler<AsyncResult<Set<VertxGenClass1>>> setGen1Handler,
Handler<AsyncResult<Set<VertxGenClass2>>> setGen2Handler,
Handler<AsyncResult<Set<JsonObject>>> setJsonObjectHandler,
Handler<AsyncResult<Set<JsonArray>>> setJsonArrayHandler,
// Handler<AsyncResult<Set<Void>>> setVoidHandler,
Handler<AsyncResult<Set<TestDataObject>>> setDataObjectHandler,
Handler<AsyncResult<Set<TestEnum>>> setEnumHandler,
Handler<AsyncResult<Set<Object>>> setObjectHandler);
示例11
/**
* Specification state :
* Requesting multiple permissions might be appropriate, for example, in cases where the resource server expects the requesting party
* to need access to several related resources if they need access to any one of the resources
*
* Means : Body can either be a JsonArray or a JsonObject, we need to handle both case.
*
* See <a href="https://docs.kantarainitiative.org/uma/wg/rec-oauth-uma-federated-authz-2.0.html#permission-endpoint">here</a>
* @param context RoutingContext
* @return List of PermissionRequest
*/
private Single<List<PermissionTicketRequest>> extractRequest(RoutingContext context) {
List<PermissionTicketRequest> result;
Object json;
try {
json = context.getBody().toJson();
}
catch (RuntimeException err) {
return Single.error(new InvalidRequestException("Unable to parse body permission request"));
}
if(json instanceof JsonArray) {
result = convert(((JsonArray)json).getList());
} else {
result = Arrays.asList(((JsonObject)json).mapTo(PermissionTicketRequest.class));
}
return Single.just(result);
}
示例12
private Handler<AsyncResult<List<Character>>> createListCharHandler(Message msg) {
return res -> {
if (res.failed()) {
if (res.cause() instanceof ServiceException) {
msg.reply(res.cause());
} else {
msg.reply(new ServiceException(-1, res.cause().getMessage()));
}
} else {
JsonArray arr = new JsonArray();
for (Character chr: res.result()) {
arr.add((int) chr);
}
msg.reply(arr);
}
};
}
示例13
public Suggestion(JsonObject jsonObject) {
this.name = jsonObject.getString(JSON_FIELD_NAME);
this.size = jsonObject.getInteger(JSON_FIELD_SIZE);
final String jsonSuggestionType = jsonObject.getString(JSON_FIELD_SUGGESTION_TYPE);
if (jsonSuggestionType != null) {
this.suggestionType = SuggestionType.valueOf(jsonSuggestionType);
}
final JsonArray jsonEntries = jsonObject.getJsonArray(JSON_FIELD_ENTRIES);
if (jsonEntries != null) {
for (int i = 0; i < jsonEntries.size(); i++) {
entries.add(new SuggestionEntry(jsonEntries.getJsonObject(i)));
}
}
}
示例14
private void handleJsonRPCRequest(final RoutingContext routingContext) {
// first check token if authentication is required
final String token = getAuthToken(routingContext);
if (authenticationService.isPresent() && token == null) {
// no auth token when auth required
handleJsonRpcUnauthorizedError(routingContext, null, JsonRpcError.UNAUTHORIZED);
} else {
// Parse json
try {
final String json = routingContext.getBodyAsString().trim();
if (!json.isEmpty() && json.charAt(0) == '{') {
final JsonObject requestBodyJsonObject =
ContextKey.REQUEST_BODY_AS_JSON_OBJECT.extractFrom(
routingContext, () -> new JsonObject(json));
AuthenticationUtils.getUser(
authenticationService,
token,
user -> handleJsonSingleRequest(routingContext, requestBodyJsonObject, user));
} else {
final JsonArray array = new JsonArray(json);
if (array.size() < 1) {
handleJsonRpcError(routingContext, null, JsonRpcError.INVALID_REQUEST);
return;
}
AuthenticationUtils.getUser(
authenticationService,
token,
user -> handleJsonBatchRequest(routingContext, array, user));
}
} catch (final DecodeException ex) {
handleJsonRpcError(routingContext, null, JsonRpcError.PARSE_ERROR);
}
}
}
示例15
@Test
public void getAdminPostgresLoad(TestContext context) {
new AdminAPI().getAdminPostgresLoad("postgres", okapiHeaders, context.asyncAssertSuccess(response -> {
assertThat(response.getStatus(), is(HttpStatus.HTTP_OK.toInt()));
assertThat(response.getMediaType(), is(MediaType.APPLICATION_JSON_TYPE));
JsonArray jsonArray = new JsonArray(body(response));
JsonObject jsonObject = jsonArray.getJsonObject(0);
assertThat(jsonObject.getInteger("connections"), is(greaterThan(-1)));
}), vertx.getOrCreateContext());
}
示例16
/**
* Assert a set of devices.
* <p>
* This will read the devices and expect them to be found and match the provided device information.
*
* @param devices The devices and device information.
* @return A future, reporting the assertion status.
*/
protected Future<?> assertDevices(final Map<String, Device> devices) {
Future<?> current = Future.succeededFuture();
for (final Map.Entry<String, Device> entry : devices.entrySet()) {
final var device = entry.getValue();
current = current.compose(ok -> assertDevice(TENANT, entry.getKey(), Optional.empty(),
r -> {
assertThat(r.isOk());
assertThat(r.getPayload()).isNotNull();
assertThat(r.getResourceVersion()).isNotNull(); // may be empty, but not null
assertThat(r.getCacheDirective()).isNotNull(); // may be empty, but not null
assertThat(r.getPayload().isEnabled()).isEqualTo(device.isEnabled());
assertThat(r.getPayload().getVia()).isEqualTo(device.getVia());
},
r -> {
if (device.isEnabled()) {
assertThat(r.isOk());
assertThat(r.getPayload()).isNotNull();
final JsonArray actualVias = r.getPayload().getJsonArray(RegistryManagementConstants.FIELD_VIA, new JsonArray());
assertThat(actualVias).hasSameElementsAs(device.getVia());
} else {
assertThat(r.getStatus()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND);
assertThat(r.getPayload()).isNull();
}
}));
}
return current;
}
示例17
private void executeBatch(RoutingContext rc, GraphQLBatch batch) {
@SuppressWarnings("rawtypes")
CompositeFuture all = StreamSupport.stream(batch.spliterator(), false)
.map(q -> (Future) execute(rc, q))
.collect(collectingAndThen(toList(), CompositeFuture::all));
all.map(cf -> new JsonArray(cf.list()).toBuffer())
.onComplete(ar -> sendResponse(rc, ar));
}
示例18
@Override
public JsonArray getBodyAsJsonArray() {
if (body != null) {
return BodyCodecImpl.JSON_ARRAY_DECODER.apply(body);
}
return null;
}
示例19
@Override
public JsonArray parse(String serialized) throws MalformedValueException {
return Arrays
.stream(serialized.split(separator, -1))
.map(this::parseValue)
.reduce(new JsonArray(), JsonArray::add, JsonArray::addAll);
}
示例20
protected void assertPeerResultMatchesPeer(
final JsonArray result, final Collection<PeerConnection> peerList) {
int i = -1;
for (final PeerConnection peerConn : peerList) {
final JsonObject peerJson = result.getJsonObject(++i);
final int jsonVersion = Integer.decode(peerJson.getString("version"));
final String jsonClient = peerJson.getString("name");
final List<Capability> caps = getCapabilities(peerJson.getJsonArray("caps"));
final int jsonPort = Integer.decode(peerJson.getString("port"));
final Bytes jsonNodeId = Bytes.fromHexString(peerJson.getString("id"));
final PeerInfo jsonPeer = new PeerInfo(jsonVersion, jsonClient, caps, jsonPort, jsonNodeId);
assertThat(peerConn.getPeerInfo()).isEqualTo(jsonPeer);
}
}
示例21
@Override
protected Something newPojoWithRandomValues() {
Random random = new Random();
Something something = new Something();
something.setSomeid(random.nextInt());
something.setSomedouble(random.nextDouble());
something.setSomehugenumber(random.nextLong());
something.setSomejsonarray(new JsonArray().add(1).add(2).add(3));
something.setSomejsonobject(new JsonObject().put("key", "value"));
something.setSomesmallnumber((short) random.nextInt(Short.MAX_VALUE));
something.setSomestring("my_string");
return something;
}
示例22
@Test
public void testDeleteByQuerySimpleRx(TestContext testContext) throws Exception {
final Async async = testContext.async();
final JsonObject source = new JsonObject()
.put("user", source_user)
.put("message", source_message)
.put("obj", new JsonObject()
.put("array", new JsonArray()
.add("1")
.add("2")));
final UUID documentId = UUID.randomUUID();
final IndexOptions indexOptions = new IndexOptions().setId(documentId.toString());
rxService.index(index, type, source, indexOptions)
.flatMap(result -> {
final ObservableFuture<Void> observableFuture = RxHelper.observableFuture();
vertx.setTimer(2000, id -> observableFuture.toHandler().handle(Future.succeededFuture()));
return observableFuture;
})
.flatMap(aVoid -> {
final DeleteByQueryOptions deleteByQueryOptions = new DeleteByQueryOptions().setTimeoutInMillis(1000l);
return rxService.deleteByQuery(index, deleteByQueryOptions.setQuery(new JsonObject().put("ids", new JsonObject().put("values", new JsonArray().add(documentId.toString())))));
})
.subscribe(
deleteByQueryResponse -> {
assertDeleteByQuerySimple(testContext, deleteByQueryResponse);
async.complete();
},
error -> testContext.fail(error)
);
}
示例23
@Test
public void testWithExistingRepoOnTheWrongBranch() throws Exception {
git.close();
root = new File("target/junk/work");
git = connect(bareRoot, root);
add(git, root, new File("src/test/resources/files/a.json"), "dir");
push(git);
branch = "dev";
add(git, root, new File("src/test/resources/files/b.json"), "dir");
push(git);
retriever = ConfigRetriever.create(vertx, new ConfigRetrieverOptions()
.setScanPeriod(1000)
.addStore(new ConfigStoreOptions().setType("git").setConfig(new JsonObject()
.put("url", bareRoot.getAbsolutePath())
.put("path", "target/junk/work")
.put("filesets", new JsonArray()
.add(new JsonObject().put("pattern", "dir/*.json"))
))));
AtomicBoolean done = new AtomicBoolean();
retriever.getConfig(ar -> {
assertThat(ar.succeeded()).isTrue();
assertThat(ar.result().getString("a.name")).isEqualTo("A");
done.set(true);
});
await().untilAtomic(done, is(true));
updateA();
await().until(() ->
"A2".equals(retriever.getCachedConfig().getString("a.name"))
&& "B".equalsIgnoreCase(retriever.getCachedConfig().getString("b.name")));
}
示例24
public static OrAuthorization decode(JsonObject json) throws IllegalArgumentException {
Objects.requireNonNull(json);
if (TYPE_AND_AUTHORIZATION.equals(json.getString(FIELD_TYPE))) {
OrAuthorization result = OrAuthorization.create();
JsonArray authorizations = json.getJsonArray(FIELD_AUTHORIZATIONS);
for (int i = 0; i < authorizations.size(); i++) {
JsonObject authorization = authorizations.getJsonObject(i);
result.addAuthorization(AuthorizationConverter.decode(authorization));
}
return result;
}
return null;
}
示例25
@Override
public String toString(Object value) {
if (value instanceof JsonArray || value instanceof JsonObject) {
return value.toString();
} else {
return super.toString(value);
}
}
示例26
@Override
public Future<JsonObject> getCommandHandlingAdapterInstances(final String deviceId, final List<String> viaGateways, final SpanContext context) {
Objects.requireNonNull(deviceId);
final Promise<DeviceConnectionResult> resultTracker = Promise.promise();
final Map<String, Object> properties = createDeviceIdProperties(deviceId);
final JsonObject payload = new JsonObject();
payload.put(DeviceConnectionConstants.FIELD_GATEWAY_IDS, new JsonArray(viaGateways));
final Span currentSpan = newChildSpan(context, "get command handling adapter instances");
TracingHelper.setDeviceTags(currentSpan, getTenantId(), deviceId);
createAndSendRequest(
DeviceConnectionConstants.DeviceConnectionAction.GET_CMD_HANDLING_ADAPTER_INSTANCES.getSubject(),
properties,
payload.toBuffer(),
RequestResponseApiConstants.CONTENT_TYPE_APPLICATION_JSON,
resultTracker,
null,
currentSpan);
return mapResultAndFinishSpan(resultTracker.future(), result -> {
switch (result.getStatus()) {
case HttpURLConnection.HTTP_OK:
return result.getPayload();
default:
throw StatusCodeMapper.from(result);
}
}, currentSpan);
}
示例27
@Override
public List<KafkaProducerRecord<byte[], byte[]>> toKafkaRecords(String kafkaTopic, Integer partition, Buffer messages) {
List<KafkaProducerRecord<byte[], byte[]>> records = new ArrayList<>();
JsonObject json = messages.toJsonObject();
JsonArray jsonArray = json.getJsonArray("records");
for (Object obj : jsonArray) {
JsonObject jsonObj = (JsonObject) obj;
records.add(toKafkaRecord(kafkaTopic, partition, jsonObj.toBuffer()));
}
return records;
}
示例28
public OutStream(RowSet<Row> result) {
JsonArray ar = new JsonArray();
RowIterator<Row> it = result.iterator();
while (it.hasNext()) {
Row row = it.next();
JsonObject o = new JsonObject();
for (int i = 0; i < row.size(); i++) {
o.put(row.getColumnName(i), row.getValue(i));
}
ar.add(o);
}
data = ar.encode();
}
示例29
public static void toJson(StompClientOptions obj, java.util.Map<String, Object> json) {
if (obj.getAcceptedVersions() != null) {
JsonArray array = new JsonArray();
obj.getAcceptedVersions().forEach(item -> array.add(item));
json.put("acceptedVersions", array);
}
json.put("autoComputeContentLength", obj.isAutoComputeContentLength());
json.put("bypassHostHeader", obj.isBypassHostHeader());
if (obj.getHeartbeat() != null) {
json.put("heartbeat", obj.getHeartbeat());
}
if (obj.getHost() != null) {
json.put("host", obj.getHost());
}
if (obj.getLogin() != null) {
json.put("login", obj.getLogin());
}
if (obj.getPasscode() != null) {
json.put("passcode", obj.getPasscode());
}
json.put("port", obj.getPort());
json.put("trailingLine", obj.isTrailingLine());
json.put("useStompFrame", obj.isUseStompFrame());
if (obj.getVirtualHost() != null) {
json.put("virtualHost", obj.getVirtualHost());
}
}
示例30
@Override
public void getAuthorizations(User user, Handler<AsyncResult<Void>> resultHandler) {
client.getConnection(connectionResponse -> {
if (connectionResponse.succeeded()) {
String username = user.principal().getString(usernameKey);
if (username != null) {
JsonArray params = new JsonArray().add(username);
SQLConnection connection = connectionResponse.result();
getRoles(connection, params, roleResponse -> {
if (roleResponse.succeeded()) {
Set<Authorization> authorizations = new HashSet<>(roleResponse.result());
getPermissions(connection, params, permissionResponse -> {
if (permissionResponse.succeeded()) {
authorizations.addAll(permissionResponse.result());
user.authorizations().add(getId(), authorizations);
resultHandler.handle(Future.succeededFuture());
} else {
resultHandler.handle(Future.failedFuture(permissionResponse.cause()));
}
connection.close();
});
} else {
resultHandler.handle(Future.failedFuture(roleResponse.cause()));
connection.close();
}
});
} else {
resultHandler.handle(Future.failedFuture("Couldn't get the username"));
connectionResponse.result().close();
}
} else {
resultHandler.handle(Future.failedFuture(connectionResponse.cause()));
}
});
}