io.vertx.core.json.JsonArray Java Examples

The following examples show how to use io.vertx.core.json.JsonArray. 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: QueryableVertxEBProxy.java    From vertx-graphql-service-discovery with Apache License 2.0 6 votes vote down vote up
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()); 
  } 
}
 
Example #2
Source File: PortfolioServiceVertxProxyHandler.java    From vertx-microservices-workshop with Apache License 2.0 6 votes vote down vote up
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);
    }
  };
}
 
Example #3
Source File: Something.java    From vertx-jooq with MIT License 6 votes vote down vote up
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;
}
 
Example #4
Source File: JsonDataTypeTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@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)));
}
 
Example #5
Source File: MapBasedDeviceConnectionServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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: SetterAdderDataObjectConverter.java    From vertx-codegen with Apache License 2.0 6 votes vote down vote up
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;
    }
  }
}
 
Example #7
Source File: HttpJsonMessageConverter.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #8
Source File: MongoAuthImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: MethodWithValidHandlerAsyncResultParams.java    From vertx-codegen with Apache License 2.0 6 votes vote down vote up
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);
 
Example #10
Source File: PermissionEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #11
Source File: MqttSink.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
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));
}
 
Example #12
Source File: ShoppingCartServiceVertxProxyHandler.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
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);
    }
  };
}
 
Example #13
Source File: Suggestion.java    From vertx-elasticsearch-service with Apache License 2.0 6 votes vote down vote up
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)));
        }
    }
}
 
Example #14
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 5 votes vote down vote up
private Completable update(SQLConnection connection, String id, Article article) {
    String sql = "UPDATE articles SET title = ?, url = ? WHERE id = ?";
    JsonArray params = new JsonArray().add(article.getTitle())
        .add(article.getUrl())
        .add(Integer.valueOf(id));
    return connection.rxUpdateWithParams(sql, params)
        .flatMapCompletable(ur ->
            ur.getUpdated() == 0 ?
                Completable
                    .error(new NoSuchElementException("No article with id " + id))
                : Completable.complete()
        )
        .doFinally(connection::close);
}
 
Example #15
Source File: Code2.java    From rxjava2-lab with Apache License 2.0 5 votes vote down vote up
static Single<JsonArray> load() {
    Vertx vertx = Vertx.vertx();
    FileSystem fileSystem = vertx.fileSystem();
    return fileSystem.rxReadFile("src/main/resources/characters.json")
        .map(buffer -> buffer.toString())
        .map(content -> new JsonArray(content));
}
 
Example #16
Source File: KafkaBridgeUtils.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public static void checkSendResponse(JsonObject response, int messageCount) {
    JsonArray offsets = response.getJsonArray("offsets");
    assertThat(offsets.size(), is(messageCount));
    for (int i = 0; i < messageCount; i++) {
        JsonObject metadata = offsets.getJsonObject(i);
        assertThat(metadata.getInteger("partition"), is(0));
        assertThat(metadata.getInteger("offset"), is(i));
        LOGGER.debug("offset size: {}, partition: {}, offset size: {}", offsets.size(), metadata.getInteger("partition"), metadata.getLong("offset"));
    }
}
 
Example #17
Source File: TenantObject.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Checks whether auto-provisioning is enabled for a CA.
 *
 * @param subjectDn The subject DN of the CA to check.
 * @return {@code true} if auto-provisioning is enabled.
 * @throws NullPointerException if the parameter subjectDN is {@code null}.
 */
@JsonIgnore
public boolean isAutoProvisioningEnabled(final String subjectDn) {
    Objects.requireNonNull(subjectDn);
    return getProperty(TenantConstants.FIELD_PAYLOAD_TRUSTED_CA, JsonArray.class, new JsonArray())
            .stream()
            .filter(JsonObject.class::isInstance)
            .map(JsonObject.class::cast)
            .filter(ca -> subjectDn.equals(getProperty(ca, TenantConstants.FIELD_PAYLOAD_SUBJECT_DN, String.class)))
            .map(caInUse -> getProperty(caInUse, TenantConstants.FIELD_AUTO_PROVISIONING_ENABLED, Boolean.class, false))
            .findFirst().orElse(false);
}
 
Example #18
Source File: JDBCStoredProcedureTest.java    From vertx-jdbc-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testStoredProcedure4() {
  client.callWithParams("{call times2(?)}", new JsonArray().add(2), new JsonArray().add("INTEGER"), onSuccess(resultSet -> {
    assertNotNull(resultSet);
    assertEquals(0, resultSet.getResults().size());
    assertEquals(new Integer(4), resultSet.getOutput().getInteger(0));
    testComplete();
  }));

  await();
}
 
Example #19
Source File: ServiceDef.java    From sfs with Apache License 2.0 5 votes vote down vote up
public JsonObject toJsonObject() {
    JsonObject jsonObject = new JsonObject()
            .put("id", id)
            .put("update_ts", toDateTimeString(getLastUpdate()))
            .put("master_node", master)
            .put("data_node", dataNode)
            .put("document_count", documentCount)
            .put("available_processors", availableProcessors)
            .put("free_memory", freeMemory)
            .put("max_memory", maxMemory)
            .put("total_memory", totalMemory);

    if (fileSystem != null) {
        JsonObject jsonFileSystem = fileSystem.toJsonObject();
        jsonObject = jsonObject.put("file_system", jsonFileSystem);
    }

    JsonArray jsonListeners = new JsonArray();
    for (HostAndPort publishAddress : publishAddresses) {
        jsonListeners.add(publishAddress.toString());
    }
    jsonObject.put("publish_addresses", jsonListeners);

    JsonArray jsonVolumes = new JsonArray();
    for (XVolume<? extends XVolume> xVolume : volumes) {
        jsonVolumes.add(xVolume.toJsonObject());
    }
    jsonObject.put("volumes", jsonVolumes);
    return jsonObject;
}
 
Example #20
Source File: JsonReaderTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testArray() {
    String body = new JsonArray().add("Hello").add("World").toString();
    given().contentType(ContentType.JSON).body(body)
            .post(URL_PREFIX + "array/sync")
            .then().statusCode(200).body(equalTo("Hello World"));
}
 
Example #21
Source File: ReadPreferenceParser.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
ReadPreferenceParser(ConnectionString connectionString, JsonObject config) {
  ReadPreference connStringReadPreference = connectionString != null ? connectionString.getReadPreference() : null;
  if (connStringReadPreference != null) {
    // Prefer connection string's read preference
    readPreference = connStringReadPreference;
  } else {
    ReadPreference rp;
    String rps = config.getString("readPreference");
    if (rps != null) {
      JsonArray readPreferenceTags = config.getJsonArray("readPreferenceTags");
      if (readPreferenceTags == null) {
        rp = ReadPreference.valueOf(rps);
        if (rp == null) throw new IllegalArgumentException("Invalid ReadPreference " + rps);
      } else {
        // Support advanced ReadPreference Tags
        List<TagSet> tagSet = new ArrayList<>();
        readPreferenceTags.forEach(o -> {
          String tagString = (String) o;
          List<Tag> tags = Stream.of(tagString.trim().split(","))
              .map(s -> s.split(":"))
              .filter(array -> {
                if (array.length != 2) {
                  throw new IllegalArgumentException("Invalid readPreferenceTags value '" + tagString + "'");
                }
                return true;
              }).map(array -> new Tag(array[0], array[1])).collect(Collectors.toList());

          tagSet.add(new TagSet(tags));
        });
        rp = ReadPreference.valueOf(rps, tagSet);
      }
    } else {
      rp = null;
    }

    readPreference = rp;
  }
}
 
Example #22
Source File: OutStream.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #23
Source File: AccountDao.java    From AlipayWechatPlatform with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 更新微信支付配置
 */
public void updateWxPay(JsonObject acc, Handler<Integer> callback) {
    Integer id = acc.getInteger(ID);
    if(id == null){
        throw new IllegalArgumentException("Account ID cannot be null!!!");
    }
    StringBuilder sql = new StringBuilder("update awp_account set ");
    JsonArray params = new JsonArray();
    boolean moreThanOne = false;
    String mchid = acc.getString(MCHID);
    if (mchid != null && !mchid.equals("")) {
        sql.append("mchId=?");
        params.add(mchid);
        moreThanOne = true;
    }
    String mchkey = acc.getString(MCHKEY);
    if (mchkey != null && !mchkey.equals("")) {
        if (moreThanOne) sql.append(",");
        sql.append("mchKey=?");
        params.add(mchkey);
        moreThanOne = true;
    }
    Integer wxpayon = acc.getInteger(WXPAYON);
    if (wxpayon != null) {
        if (moreThanOne) sql.append(",");
        sql.append("wxPayOn=?");
        params.add(wxpayon);
    }
    sql.append(" where id=?");
    params.add(id);
    update(sql.toString(), params, callback);
}
 
Example #24
Source File: JDBCTypesTestBase.java    From vertx-jdbc-client with Apache License 2.0 5 votes vote down vote up
private void assertUpdate(UpdateResult result, int updated, boolean generatedKeys) {
  assertNotNull(result);
  assertEquals(updated, result.getUpdated());
  if (generatedKeys) {
    JsonArray keys = result.getKeys();
    assertNotNull(keys);
    assertEquals(updated, keys.size());
    Set<Integer> numbers = new HashSet<>();
    for (int i = 0; i < updated; i++) {
      assertTrue(keys.getValue(i) instanceof Integer);
      assertTrue(numbers.add(i));
    }
  }
}
 
Example #25
Source File: OrAuthorizationConverter.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public static JsonObject encode(OrAuthorization value) throws IllegalArgumentException {
  Objects.requireNonNull(value);

  JsonObject result = new JsonObject();
  result.put(FIELD_TYPE, TYPE_AND_AUTHORIZATION);
  JsonArray authorizations = new JsonArray();
  result.put(FIELD_AUTHORIZATIONS, authorizations);
  for (Authorization authorization : value.getAuthorizations()) {
    authorizations.add(AuthorizationConverter.encode(authorization));
  }
  return result;
}
 
Example #26
Source File: TupleTest.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonArray() {
  Tuple tuple = of(jsonArray);
  assertEquals(jsonArray, tuple.getJsonArray(0));
  tuple = of((Object)new Object[]{jsonArray});
  JsonArray[] array = tuple.getJsonArrayArray(0);
  assertEquals(1, array.length);
  assertEquals(jsonArray, array[0]);
}
 
Example #27
Source File: ClusterHealthCheckImpl.java    From vertx-infinispan with Apache License 2.0 5 votes vote down vote up
private JsonObject convert(ClusterHealth clusterHealth) {
  return new JsonObject()
    .put("healthStatus", clusterHealth.getHealthStatus().name())
    .put("clusterName", clusterHealth.getClusterName())
    .put("numberOfNodes", clusterHealth.getNumberOfNodes())
    .put("nodeNames", clusterHealth.getNodeNames().stream()
      .collect(JsonArray::new, JsonArray::add, JsonArray::addAll));
}
 
Example #28
Source File: JDBCAuthorizationImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@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()));
    }
  });
}
 
Example #29
Source File: StompClientOptionsConverter.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
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());
  }
}
 
Example #30
Source File: JsonRpcHttpService.java    From besu with Apache License 2.0 5 votes vote down vote up
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);
    }
  }
}