Java Code Examples for io.vertx.core.json.JsonArray

The following examples show how to use io.vertx.core.json.JsonArray. These examples are extracted from open source projects. 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 Project: smallrye-reactive-messaging   Source File: MqttSink.java    License: 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 2
Source Project: vertx-auth   Source File: MongoAuthImpl.java    License: 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 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);
    }
  };
}
 
Example 4
Source Project: vertx-jooq   Source File: Something.java    License: 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 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();
}
 
Example 6
Source Project: vertx-sql-client   Source File: JsonDataTypeTest.java    License: 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 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);
}
 
Example 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;
    }
  }
}
 
Example 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()); 
  } 
}
 
Example 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);
 
Example 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);
}
 
Example 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);
    }
  };
}
 
Example 13
Source Project: vertx-elasticsearch-service   Source File: Suggestion.java    License: 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 Project: besu   Source File: JsonRpcHttpService.java    License: 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);
    }
  }
}
 
Example 15
Source Project: raml-module-builder   Source File: AdminAPIIT.java    License: Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 16
Source Project: hono   Source File: RegistrationServiceTests.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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;

}
 
Example 17
Source Project: vertx-web   Source File: GraphQLHandlerImpl.java    License: Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 18
Source Project: vertx-web   Source File: RoutingContextImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JsonArray getBodyAsJsonArray() {
  if (body != null) {
    return BodyCodecImpl.JSON_ARRAY_DECODER.apply(body);
  }
  return null;
}
 
Example 19
Source Project: vertx-web   Source File: SplitterCharArrayParser.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 20
Source Project: besu   Source File: AdminJsonRpcHttpServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 21
Source Project: vertx-jooq   Source File: SomethingJsonConversionTest.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 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)
            );
}
 
Example 23
Source Project: vertx-config   Source File: GitConfigStoreTest.java    License: Apache License 2.0 5 votes vote down vote up
@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")));
}
 
Example 24
Source Project: vertx-auth   Source File: OrAuthorizationConverter.java    License: Apache License 2.0 5 votes vote down vote up
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 25
@Override
public String toString(Object value) {
    if (value instanceof JsonArray || value instanceof JsonObject) {
        return value.toString();
    } else {
        return super.toString(value);
    }
}
 
Example 26
Source Project: hono   Source File: DeviceConnectionClientImpl.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@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);
}
 
Example 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;
}
 
Example 28
Source Project: raml-module-builder   Source File: OutStream.java    License: 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 29
Source Project: vertx-stomp   Source File: StompClientOptionsConverter.java    License: 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 Project: vertx-auth   Source File: JDBCAuthorizationImpl.java    License: 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()));
    }
  });
}