Java Code Examples for io.vertx.core.json.JsonObject#getJsonArray()
The following examples show how to use
io.vertx.core.json.JsonObject#getJsonArray() .
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: JsonRpcHttpServiceTest.java From besu with Apache License 2.0 | 6 votes |
@Test public void ethAccountsSuccessful() throws Exception { final String id = "123"; final RequestBody body = RequestBody.create( JSON, "{\"jsonrpc\":\"2.0\",\"id\":" + Json.encode(id) + ",\"method\":\"eth_accounts\"}"); 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 JsonArray result = json.getJsonArray("result"); assertThat(result.size()).isEqualTo(0); } }
Example 2
Source File: HelpFunc.java From df_data_service with Apache License 2.0 | 6 votes |
/** * Mapping rest state to df status category * @param taskStatus * @return */ public static String getTaskStatusFlink(JsonObject taskStatus) { if(taskStatus.containsKey("state")) { // Check sub-task status ony if the high level task is RUNNING if(taskStatus.getString("state").equalsIgnoreCase(ConstantApp.DF_STATUS.RUNNING.name()) && taskStatus.containsKey("vertices")) { JsonArray subTask = taskStatus.getJsonArray("vertices"); String status = ConstantApp.DF_STATUS.RUNNING.name(); for (int i = 0; i < subTask.size(); i++) { if (!subTask.getJsonObject(i).getString("status") .equalsIgnoreCase(ConstantApp.DF_STATUS.RUNNING.name())) { status = ConstantApp.DF_STATUS.RWE.name(); break; } } return status; } else { return taskStatus.getString("state"); } } else { return ConstantApp.DF_STATUS.NONE.name(); } }
Example 3
Source File: Account.java From sfs with Apache License 2.0 | 6 votes |
public T merge(JsonObject document) { JsonArray metadataJsonObject = document.getJsonArray("metadata", new JsonArray()); metadata.withJsonObject(metadataJsonObject); setNodeId(document.getString("node_id")); String createTimestamp = document.getString("create_ts"); String updateTimestamp = document.getString("update_ts"); if (createTimestamp != null) { setCreateTs(fromDateTimeString(createTimestamp)); } if (updateTimestamp != null) { setUpdateTs(fromDateTimeString(updateTimestamp)); } return (T) this; }
Example 4
Source File: DeviceConnectionClientImplTest.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * Verifies that the client includes the required information in the <em>get-cmd-handling-adapter-instances</em> operation * request message sent to the device connection service. */ @Test public void testGetCommandHandlingAdapterInstancesIncludesRequiredInformationInRequest() { final String deviceId = "deviceId"; final String gatewayId = "gw-1"; // WHEN getting last known gateway information client.getCommandHandlingAdapterInstances(deviceId, Collections.singletonList(gatewayId), span.context()); // THEN the message being sent contains the device ID in its properties final Message sentMessage = verifySenderSend(); assertThat(MessageHelper.getDeviceId(sentMessage)).isEqualTo(deviceId); assertThat(sentMessage.getMessageId()).isNotNull(); assertThat(sentMessage.getSubject()).isEqualTo(DeviceConnectionConstants.DeviceConnectionAction.GET_CMD_HANDLING_ADAPTER_INSTANCES.getSubject()); // and the 'via' gateway ID in the payload final JsonObject msgJsonPayload = MessageHelper.getJsonPayload(sentMessage); assertThat(msgJsonPayload).isNotNull(); final JsonArray gatewaysJsonArray = msgJsonPayload.getJsonArray(DeviceConnectionConstants.FIELD_GATEWAY_IDS); assertThat(gatewaysJsonArray.getList().iterator().next()).isEqualTo(gatewayId); }
Example 5
Source File: MapBasedDeviceConnectionServiceTest.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * 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); }
Example 6
Source File: CoordinateParser.java From vertx-consul-client with Apache License 2.0 | 6 votes |
static Coordinate parse(JsonObject json) { Coordinate coordinate = new Coordinate() .setNode(json.getString(NODE_KEY)); JsonObject coord = json.getJsonObject(COORD_KEY); if (coord != null) { coordinate .setAdj(coord.getFloat(ADJ_KEY, 0f)) .setErr(coord.getFloat(ERR_KEY, 0f)) .setHeight(coord.getFloat(HEIGHT_KEY, 0f)); JsonArray arr = coord.getJsonArray(VEC_KEY); coordinate.setVec(arr == null ? null : arr.stream() .map(o -> o instanceof Number ? ((Number) o).floatValue() : 0f) .collect(Collectors.toList())); } return coordinate; }
Example 7
Source File: WebVerticle.java From vertx-starter with Apache License 2.0 | 6 votes |
public WebVerticle() { try { JsonObject starterData = Util.loadStarterData(); JsonObject defaults = starterData.getJsonObject("defaults"); JsonArray versions = starterData.getJsonArray("versions"); JsonArray stack = starterData.getJsonArray("stack"); validationHandler = new ValidationHandler(defaults, versions, stack); generationHandler = new GenerationHandler(); metadataHandler = new MetadataHandler(defaults, versions, stack); } catch (IOException e) { throw new RuntimeException(e); } }
Example 8
Source File: OpenAPI3Utils.java From vertx-web with Apache License 2.0 | 5 votes |
public static JsonObject generateFakeSchema(JsonObject schema, OpenAPIHolder holder) { JsonObject fakeSchema = holder.solveIfNeeded(schema).copy(); String combinatorKeyword = fakeSchema.containsKey("allOf") ? "allOf" : fakeSchema.containsKey("anyOf") ? "anyOf" : fakeSchema.containsKey("oneOf") ? "oneOf" : null; if (combinatorKeyword != null) { JsonArray schemasArray = fakeSchema.getJsonArray(combinatorKeyword); JsonArray processedSchemas = new JsonArray(); for (int i = 0; i < schemasArray.size(); i++) { JsonObject innerSchema = holder.solveIfNeeded(schemasArray.getJsonObject(i)); processedSchemas.add(innerSchema.copy()); schemasArray.getJsonObject(i).mergeIn(innerSchema); if ("object".equals(innerSchema.getString("type")) || innerSchema.containsKey("properties")) fakeSchema = fakeSchema.mergeIn(innerSchema, true); } fakeSchema.remove(combinatorKeyword); fakeSchema.put("x-" + combinatorKeyword, processedSchemas); } if (fakeSchema.containsKey("properties")) { JsonObject propsObj = fakeSchema.getJsonObject("properties"); for (String key : propsObj.fieldNames()) { propsObj.put(key, holder.solveIfNeeded(propsObj.getJsonObject(key))); } } if (fakeSchema.containsKey("items")) { fakeSchema.put("items", holder.solveIfNeeded(fakeSchema.getJsonObject("items"))); } return fakeSchema; }
Example 9
Source File: TenantServiceImpl.java From enmasse with Apache License 2.0 | 5 votes |
private Set<X500Principal> anchors(final IoTProject project) { if (project != null && project.getStatus() == null || project.getStatus().getAccepted() == null || project.getStatus().getAccepted().getConfiguration() == null) { // no configuration yet return Collections.emptySet(); } final JsonObject config = JsonObject.mapFrom(project.getStatus().getAccepted().getConfiguration()); final JsonArray trustAnchors = config.getJsonArray(TenantConstants.FIELD_PAYLOAD_TRUSTED_CA); if (trustAnchors == null) { return Collections.emptySet(); } final Set<X500Principal> result = new HashSet<>(); for (Object value : trustAnchors) { if (!(value instanceof JsonObject)) { continue; } final JsonObject trustAnchor = (JsonObject) value; if (!trustAnchor.getBoolean(TenantConstants.FIELD_ENABLED, true)) { continue; } final String subjectDn = trustAnchor.getString(TenantConstants.FIELD_PAYLOAD_SUBJECT_DN); if (Strings.isNullOrEmpty(subjectDn)) { continue; } result.add(new X500Principal(subjectDn)); } return result; }
Example 10
Source File: Container.java From sfs with Apache License 2.0 | 5 votes |
public T merge(JsonObject document) { checkState(getParent().getId().equals(document.getString("account_id"))); setOwnerGuid(document.getString("owner_guid")); JsonArray metadataJsonObject = document.getJsonArray("metadata", new JsonArray()); getMetadata().withJsonObject(metadataJsonObject); setNodeId(document.getString("node_id")); String createTimestamp = document.getString("create_ts"); String updateTimestamp = document.getString("update_ts"); if (createTimestamp != null) { setCreateTs(fromDateTimeString(createTimestamp)); } if (updateTimestamp != null) { setUpdateTs(fromDateTimeString(updateTimestamp)); } setObjectReplicas(document.containsKey("object_replicas") ? document.getInteger("object_replicas") : NOT_SET); if (document.containsKey("object_write_consistency")) { WriteConsistency writeConsistency = WriteConsistency.fromValueIfExists(document.getString("object_write_consistency")); // null is node default setObjectWriteConsistency(writeConsistency); } else { // null is node default setObjectWriteConsistency(null); } return (T) this; }
Example 11
Source File: HttpJsonMessageConverter.java From strimzi-kafka-bridge with Apache License 2.0 | 5 votes |
@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; }
Example 12
Source File: SuggestionEntry.java From vertx-elasticsearch-service with Apache License 2.0 | 5 votes |
public SuggestionEntry(JsonObject jsonObject) { this.text = jsonObject.getString(JSON_FIELD_TEXT); this.offset = jsonObject.getInteger(JSON_FIELD_OFFSET); this.length = jsonObject.getInteger(JSON_FIELD_LENGTH); final JsonArray jsonOptions = jsonObject.getJsonArray(JSON_FIELD_OPTIONS); if (jsonOptions != null) { for (int i = 0; i < jsonOptions.size(); i++) { options.add(new SuggestionEntryOption(jsonOptions.getJsonObject(i))); } } }
Example 13
Source File: ServiceParser.java From vertx-consul-client with Apache License 2.0 | 5 votes |
static Service parseNodeInfo(String nodeName, String nodeAddress, JsonObject serviceInfo) { JsonArray tagsArr = serviceInfo.getJsonArray(AGENT_SERVICE_TAGS); return new Service() .setNode(nodeName) .setNodeAddress(nodeAddress) .setId(serviceInfo.getString(AGENT_SERVICE_ID)) .setAddress(serviceInfo.getString(AGENT_SERVICE_ADDRESS)) .setMeta(mapStringString(serviceInfo.getJsonObject(AGENT_SERVICE_META))) .setName(serviceInfo.getString(AGENT_SERVICE_SERVICE)) .setTags(listOf(tagsArr)) .setPort(serviceInfo.getInteger(AGENT_SERVICE_PORT)); }
Example 14
Source File: ClientAccesses.java From nubes with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public static ClientAccesses fromJsonObject(JsonObject json) { ClientAccesses accesses = new ClientAccesses(); JsonArray array = json.getJsonArray("history"); if (array != null) { accesses.history = array.getList(); } return accesses; }
Example 15
Source File: HttpBinaryMessageConverter.java From strimzi-kafka-bridge with Apache License 2.0 | 5 votes |
@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; }
Example 16
Source File: OrAuthorizationConverter.java From vertx-auth with Apache License 2.0 | 5 votes |
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; }
Example 17
Source File: XObject.java From sfs with Apache License 2.0 | 5 votes |
public T merge(JsonObject document) { this.versions.clear(); this.ownerGuid = document.getString("owner_guid"); this.nodeId = document.getString("node_id"); JsonArray jsonVerionArray = document.getJsonArray("versions"); if (jsonVerionArray != null) { for (Object o : jsonVerionArray) { JsonObject versionDocument = (JsonObject) o; Long id = versionDocument.getLong("id"); if (id == null) { checkNotNull(id, "id is null for %s", document.encodePrettily()); } TransientVersion transientVersion = new TransientVersion(this, id) .merge(versionDocument); versions.add(transientVersion); } } String createTimestamp = document.getString("create_ts"); String updateTimestamp = document.getString("update_ts"); if (createTimestamp != null) { setCreateTs(fromDateTimeString(createTimestamp)); } if (updateTimestamp != null) { setUpdateTs(fromDateTimeString(updateTimestamp)); } return (T) this; }
Example 18
Source File: MailConfig.java From vertx-mail-client with Apache License 2.0 | 4 votes |
/** * construct config object from Json representation * * @param config the config to copy */ public MailConfig(JsonObject config) { super(config); hostname = config.getString("hostname", DEFAULT_HOST); port = config.getInteger("port", DEFAULT_PORT); String starttlsOption = config.getString("starttls"); if (starttlsOption != null) { starttls = StartTLSOptions.valueOf(starttlsOption.toUpperCase(Locale.ENGLISH)); } else { starttls = DEFAULT_TLS; } String loginOption = config.getString("login"); if (loginOption != null) { login = LoginOption.valueOf(loginOption.toUpperCase(Locale.ENGLISH)); } else { login = DEFAULT_LOGIN; } username = config.getString("username"); password = config.getString("password"); // Handle these for compatiblity if (config.containsKey("keyStore")) { setKeyStore(config.getString("keyStore")); } if (config.containsKey("keyStorePassword")) { setKeyStorePassword(config.getString("keyStorePassword")); } authMethods = config.getString("authMethods"); ownHostname = config.getString("ownHostname"); maxPoolSize = config.getInteger("maxPoolSize", DEFAULT_MAX_POOL_SIZE); keepAlive = config.getBoolean("keepAlive", DEFAULT_KEEP_ALIVE); allowRcptErrors = config.getBoolean("allowRcptErrors", DEFAULT_ALLOW_RCPT_ERRORS); userAgent = config.getString("userAgent", DEFAULT_USER_AGENT); enableDKIM = config.getBoolean("enableDKIM", DEFAULT_ENABLE_DKIM); JsonArray dkimOps = config.getJsonArray("dkimSignOptions"); if (dkimOps != null) { dkimSignOptions = new ArrayList<>(); dkimOps.stream().map(dkim -> new DKIMSignOptions((JsonObject)dkim)).forEach(dkimSignOptions::add); } pipelining = config.getBoolean("pipelining", DEFAULT_ENABLE_PIPELINING); }
Example 19
Source File: OAuth2AuthProviderImpl.java From vertx-auth with Apache License 2.0 | 4 votes |
private void validateUser(User user, Handler<AsyncResult<User>> handler) { if (!user.attributes().containsKey("accessToken")) { // nothing else to do handler.handle(Future.succeededFuture(user)); return; } // the user object is a JWT so we should validate it as mandated by OIDC final JWTOptions jwtOptions = config.getJWTOptions(); // basic validation passed, the token is not expired, // the spec mandates that that a few extra checks are performed final JsonObject payload; try { payload = user.attributes().getJsonObject("accessToken"); } catch (RuntimeException e) { handler.handle(Future.failedFuture("User accessToken isn't a JsonObject")); return; } if (jwtOptions.getAudience() != null) { JsonArray target; if (payload.getValue("aud") instanceof String) { target = new JsonArray().add(payload.getValue("aud", "")); } else { target = payload.getJsonArray("aud", new JsonArray()); } if (Collections.disjoint(jwtOptions.getAudience(), target.getList())) { handler.handle(Future.failedFuture("Invalid JWT audience. expected: " + Json.encode(jwtOptions.getAudience()))); return; } } if (jwtOptions.getIssuer() != null) { if (!jwtOptions.getIssuer().equals(payload.getString("iss"))) { handler.handle(Future.failedFuture("Invalid JWT issuer")); return; } } handler.handle(Future.succeededFuture(user)); }
Example 20
Source File: CustomTypeAnnotator.java From raml-module-builder with Apache License 2.0 | 4 votes |
@Override public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) { super.propertyField(field, clazz, propertyName, propertyNode); // Optionally annotates arrays with ElementsNotNull and ElementsPattern if(isArray(propertyNode)) { if(isItemsNotNull(propertyNode)) { field.annotate(ElementsNotNull.class); } Optional<String> pattern = getPattern(propertyNode); if(pattern.isPresent()) { field.annotate(ElementsPattern.class).param(REGEXP, pattern.get()); } } JsonObject annotation = fields2annotate.get(propertyName); if(annotation != null){ String annotationType = annotation.getString("type"); JsonArray annotationMembers = annotation.getJsonArray("values"); log.info("Attempting to annotate " + propertyName + " with " + annotationType); JClass annClazz = null; try { annClazz = new JCodeModel().ref(Class.forName(annotationType)); } catch (ClassNotFoundException e) { log.error("annotation of type " + annotationType + " which is used on field " + propertyName + " can not be found (class not found)......"); throw new RuntimeException(e); } //annotate the field with the requested annotation JAnnotationUse ann = field.annotate(annClazz); if(annotationMembers != null){ //add members to the annotation if they exist //for example for Size, min and max int memberCount = annotationMembers.size(); for (int i = 0; i < memberCount; i++) { //a member is something like {"max", 5} JsonObject member = annotationMembers.getJsonObject(i); member.getMap().entrySet().forEach( entry -> { String memberKey = entry.getKey(); Object memberValue = entry.getValue(); //find the type of the member value so we can create it correctly String valueType = memberValue.getClass().getName(); if(valueType.toLowerCase().endsWith("string")){ ann.param(memberKey, (String)memberValue); } else if(valueType.toLowerCase().endsWith("integer")){ ann.param(memberKey, (Integer)memberValue); } else if(valueType.toLowerCase().endsWith("boolean")){ ann.param(memberKey, (Boolean)memberValue); } else if(valueType.toLowerCase().endsWith("double")){ ann.param(memberKey, (Double)memberValue); } }); } } } }