Java Code Examples for io.vertx.core.json.JsonObject#isEmpty()

The following examples show how to use io.vertx.core.json.JsonObject#isEmpty() . 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: UsersWriteToMongo.java    From vxms with Apache License 2.0 6 votes vote down vote up
@Path("/api/users")
@PUT
public void updateUser(RestHandler handler) {
  final JsonObject user = handler.request().body().toJsonObject();
  if (user == null || user.isEmpty()) {
    handler
        .response()
        .stringResponse(f -> f.fail(DefaultResponses.defaultErrorResponse().encode()))
        .execute();
    return;
  }
  handler
      .response()
      .stringResponse(future -> service.handleUpdate(user, future))
      .retry(2)
      .timeout(1000)
      .onError(t -> log.log(Level.WARNING, "ERROR: " + t.getMessage()))
      .onFailureRespond(
          (onError, future) ->
              future.complete(
                  DefaultResponses.defaultErrorResponse(onError.getMessage()).encode()))
      .execute();
}
 
Example 2
Source File: RestDeployHandler.java    From vertx-deploy-tools with Apache License 2.0 6 votes vote down vote up
private void respondFailed(String id, HttpServerRequest request, String message, Throwable t) {

        if (!request.response().ended()) {

            request.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
            JsonObject result = new JsonObject();
            result.put(ApplicationDeployState.OK.name(), HttpUtils.toArray(deployService.getDeployedApplicationsSuccess()));
            result.put(ApplicationDeployState.ERROR.name(), HttpUtils.toArray(deployService.getDeployedApplicationsFailed()));
            result.put("message", message);
            if (result.isEmpty()) {
                request.response().end();
            } else {
                request.response().end(result.encodePrettily());
            }
            if (id != null) {
                awsService.ifPresent(aws -> aws.failBuild(id, message, t));
            }
        }

    }
 
Example 3
Source File: DeepObjectValueParameterParser.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public @Nullable Object parseParameter(Map<String, List<String>> parameters) throws MalformedValueException {
  JsonObject obj = new JsonObject();
  Iterator<Map.Entry<String, List<String>>> it = parameters.entrySet().iterator();
  while (it.hasNext()) {
    Map.Entry<String, List<String>> e = it.next();
    String key = e.getKey();
    if (key.contains(parameterName + "[") && key.charAt(key.length() - 1) == ']') {
      String realParameterName = key.substring(parameterName.length() + 1, key.length() - 1);
      Map.Entry<String, Object> parsed = parseField(realParameterName, e.getValue().get(0));
      if (parsed != null) {
        it.remove();
        obj.put(parsed.getKey(), parsed.getValue());
      }
    }
  }
  return obj.isEmpty() ? null : obj;
}
 
Example 4
Source File: UsersWriteToMongo.java    From vxms with Apache License 2.0 6 votes vote down vote up
@Consume("/api/users/:id-PUT")
public void updateUser(EventbusHandler handler) {
    final JsonObject user = handler.request().body();
    if (user == null || user.isEmpty()) {
        handler.response().stringResponse(f -> f.fail(DefaultResponses.defaultErrorResponse().encode())).execute();
        return;
    }
    handler.
            response().
            stringResponse(future -> handleUpdate(user, future)).
            retry(2).
            timeout(1000).
            onError(t -> log.log(Level.WARNING, "ERROR: " + t.getMessage())).
            onFailureRespond((onError, future) ->
                    future.complete(DefaultResponses.
                            defaultErrorResponse(onError.getMessage()).
                            encode())
            ).
            execute();
}
 
Example 5
Source File: UsersWriteToMongo.java    From vxms with Apache License 2.0 6 votes vote down vote up
@Consume("/api/users-POST")
public void inertUser(EventbusHandler handler) {
    final JsonObject body = handler.request().body();
    if (body == null || body.isEmpty()) {
        handler.response().stringResponse(f -> f.fail(DefaultResponses.defaultErrorResponse("no content").encode())).execute();
        return;
    }
    handler.
            response().
            stringResponse(future -> handleInsert(body, future)).
            retry(2).
            timeout(1000).
            onError(t -> log.log(Level.WARNING, "ERROR: " + t.getMessage())).
            onFailureRespond((onError, future) ->
                    future.complete(DefaultResponses.
                            defaultErrorResponse(onError.getMessage()).
                            encode())
            ).
            execute();
}
 
Example 6
Source File: UsersWriteToMongo.java    From vxms with Apache License 2.0 6 votes vote down vote up
@Path("/api/users")
@POST
public void inertUser(RestHandler handler) {
  final JsonObject body = handler.request().body().toJsonObject();
  if (body == null || body.isEmpty()) {
    handler
        .response()
        .stringResponse(f -> f.fail(DefaultResponses.defaultErrorResponse("no content").encode()))
        .execute();
    return;
  }
  handler
      .response()
      .stringResponse(future -> service.handleInsert(body, future))
      .retry(2)
      .timeout(1000)
      .onError(t -> log.log(Level.WARNING, "ERROR: " + t.getMessage()))
      .onFailureRespond(
          (onError, future) ->
              future.complete(
                  DefaultResponses.defaultErrorResponse(onError.getMessage()).encode()))
      .execute();
}
 
Example 7
Source File: MessageSendTester.java    From enmasse with Apache License 2.0 5 votes vote down vote up
/**
 * Fill up the message with extra payload to get an exact payload size (in bytes).
 * <p>
 * If the payload size if greater than zero, it will always requires {@link #FIXED_JSON_EXTRA_SIZE}
 * of bytes remaining for an empty object and {@link #FIXED_JSON_EXTRA_SIZE} plus one for an object
 * which already contains a field.
 *
 * @param payload The payload to modify.
 * @param payloadSize The target payload size. If this is zero or less, this operation is a no-op.
 * @throws IllegalArgumentException if the target payload size is lower than the already provided
 *         payload.
 */
static Buffer fillWithPayload(final JsonObject payload, final int payloadSize) {

    final Buffer buffer = payload.toBuffer();

    if (payloadSize <= 0) {
        return buffer;
    }

    // if the object is empty, there will be no extra comma
    final int extraComma = payload.isEmpty() ? 0 : 1;
    final int actualSize = buffer.length();
    final int fixed = FIXED_JSON_EXTRA_SIZE + extraComma;

    if (actualSize + fixed > payloadSize) {
        // we are already "too big"
        throw new IllegalArgumentException(String.format("Provided payload size already exceeds maximum (actual: %d + %d, target: %d)",
                actualSize, fixed, payloadSize));
    }

    final int diff = payloadSize - actualSize - fixed;
    final char[] fill = new char[diff];
    Arrays.fill(fill, 'a');
    payload.put("extra", String.valueOf(fill));

    return payload.toBuffer();
}
 
Example 8
Source File: HttpBinaryMessageConverter.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Override
public KafkaProducerRecord<byte[], byte[]> toKafkaRecord(String kafkaTopic, Integer partition, Buffer message) {

    Integer partitionFromBody = null;
    byte[] key = null;
    byte[] value = null;

    JsonObject json = message.toJsonObject();

    if (!json.isEmpty()) {
        if (json.containsKey("key")) {
            key = DatatypeConverter.parseBase64Binary(json.getString("key"));
        }
        if (json.containsKey("value")) {
            value = DatatypeConverter.parseBase64Binary(json.getString("value"));
        }
        if (json.containsKey("partition")) {
            partitionFromBody = json.getInteger("partition");
        }
        if (partition != null && partitionFromBody != null) {
            throw new IllegalStateException("Partition specified in body and in request path");
        }
        if (partition != null) {
            partitionFromBody = partition;
        }
    }

    KafkaProducerRecord<byte[], byte[]> record = KafkaProducerRecord.create(kafkaTopic, key, value, partitionFromBody);

    return record;
}
 
Example 9
Source File: UserProfileApiVerticle.java    From vertx-in-action with MIT License 5 votes vote down vote up
private void updateUser(RoutingContext ctx) {
  String username = ctx.pathParam("username");
  JsonObject body = jsonBody(ctx);

  JsonObject query = new JsonObject().put("username", username);
  JsonObject updates = new JsonObject();
  if (body.containsKey("city")) {
    updates.put("city", body.getString("city"));
  }
  if (body.containsKey("email")) {
    updates.put("email", body.getString("email"));
  }
  if (body.containsKey("makePublic")) {
    updates.put("makePublic", body.getBoolean("makePublic"));
  }

  if (updates.isEmpty()) {
    ctx.response()
      .setStatusCode(200)
      .end();
    return;
  }
  updates = new JsonObject()
    .put("$set", updates);

  mongoClient
    .rxFindOneAndUpdate("user", query, updates)
    .ignoreElement()
    .subscribe(
      () -> completeEmptySuccess(ctx),
      err -> handleUpdateError(ctx, err));
}
 
Example 10
Source File: HttpJsonMessageConverter.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Override
public KafkaProducerRecord<byte[], byte[]> toKafkaRecord(String kafkaTopic, Integer partition, Buffer message) {

    Integer partitionFromBody = null;
    byte[] key = null;
    byte[] value = null;

    JsonObject json = message.toJsonObject();

    if (!json.isEmpty()) {
        if (json.containsKey("key")) {
            key = Json.encodeToBuffer(json.getValue("key")).getBytes();
        }
        if (json.containsKey("value")) {
            value = Json.encodeToBuffer(json.getValue("value")).getBytes();
        }
        if (json.containsKey("partition")) {
            partitionFromBody = json.getInteger("partition");
        }
        if (partition != null && partitionFromBody != null) {
            throw new IllegalStateException("Partition specified in body and in request path");
        }
        if (partition != null) {
            partitionFromBody = partition;
        }
    }

    KafkaProducerRecord<byte[], byte[]> record = KafkaProducerRecord.create(kafkaTopic, key, value, partitionFromBody);

    return record;
}
 
Example 11
Source File: ExplodedObjectValueParameterParser.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public @Nullable Object parseParameter(Map<String, List<String>> parameters) throws MalformedValueException {
  JsonObject obj = new JsonObject();
  Iterator<Map.Entry<String, List<String>>> it = parameters.entrySet().iterator();
  while (it.hasNext()) {
    Map.Entry<String, List<String>> e = it.next();
    String key = e.getKey();
    Map.Entry<String, Object> parsed = parseField(key, e.getValue().get(0));
    if (parsed != null) {
      it.remove();
      obj.put(parsed.getKey(), parsed.getValue());
    }
  }
  return obj.isEmpty() ? null : obj;
}
 
Example 12
Source File: GraphQLRequest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private Buffer getJsonBody() {
  JsonObject json = new JsonObject();
  if (graphQLQuery != null) {
    json.put("query", graphQLQuery);
  }
  if (operationName != null) {
    json.put("operationName", operationName);
  }
  if (!variables.isEmpty()) {
    json.put("variables", variables);
  }
  return json.isEmpty() ? null : json.toBuffer();
}
 
Example 13
Source File: DeployConfig.java    From vertx-deploy-tools with Apache License 2.0 5 votes vote down vote up
static DeployConfig fromJsonObject(JsonObject config) {
    if (config == null) {
        LOG.error("Unable to read config file");
        throw new IllegalStateException("Unable to read config file");
    }

    String vertxHome = validateRequiredField(VERTX_HOME, config);
    String artifactRepo = validateRequiredField(ARTIFACT_REPO, config);
    String mavenRepo = validateField(MAVEN_REPO_URI, config, "");

    if (mavenRepo.isEmpty()) {
        LOG.warn("'maven.repo.uri', using maven central");
        mavenRepo = MAVEN_CENTRAL;
    }

    DeployConfig deployconfig = new DeployConfig(vertxHome, artifactRepo, mavenRepo)
            .withConfigLocation(config)
            .withServiceConfigLocation(config)
            .withHttpPort(config)
            .withAwsConfig(config)
            .withHttpAuth(config)
            .withAuthToken(config)
            .withCluster(config)
            .withRunDir(config)
            .withLoggerFactoryName(config)
            .withTypedDeploy(config)
            .withPollInterval(config)
            .withRemoteRepoUpdatePolicy(config);

    if (!config.isEmpty()) {
        config.fieldNames().forEach(s -> LOG.info("Unused variable in config '{}',", s));
    }
    return deployconfig;
}
 
Example 14
Source File: RestDeployHandler.java    From vertx-deploy-tools with Apache License 2.0 5 votes vote down vote up
private void respond(DeployRequest deployRequest, HttpServerRequest request) {
    request.response().setStatusCode(HttpResponseStatus.OK.code());
    awsService.ifPresent(aws -> aws.updateAndGetRequest(DeployState.SUCCESS, deployRequest.getId().toString()));
    if (!request.response().ended() && !deployRequest.withElb() && !deployRequest.withAutoScaling()) {
        JsonObject result = new JsonObject();
        result.put(ApplicationDeployState.OK.name(), HttpUtils.toArray(deployService.getDeployedApplicationsSuccess()));
        result.put(ApplicationDeployState.ERROR.name(), HttpUtils.toArray(deployService.getDeployedApplicationsFailed()));
        if (result.isEmpty()) {
            request.response().end();
        } else {
            request.response().end(result.encodePrettily());
        }
    }
}
 
Example 15
Source File: KafkaUserQuotasOperator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
private boolean configJsonIsEmpty(JsonObject json) {
    validateJsonVersion(json);
    JsonObject config = json.getJsonObject("config");
    return config.isEmpty();
}
 
Example 16
Source File: ScramShaCredentials.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
private boolean configJsonIsEmpty(JsonObject json) {
    validateJsonVersion(json);
    JsonObject config = json.getJsonObject("config");
    return config.isEmpty();
}
 
Example 17
Source File: MessageHelper.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private static Message addProperties(
        final Message message,
        final ResourceIdentifier target,
        final TenantObject tenant,
        final JsonObject deviceDefaultProperties,
        final boolean useDefaults,
        final boolean useJmsVendorProps) {

    final long maxTtl = Optional.ofNullable(tenant)
            .map(t -> Optional.ofNullable(t.getResourceLimits())
                .map(limits -> limits.getMaxTtl())
                .orElse(TenantConstants.UNLIMITED_TTL))
            .orElse(TenantConstants.UNLIMITED_TTL);

    if (useDefaults) {
        final JsonObject defaults = Optional.ofNullable(tenant)
                .map(t -> t.getDefaults().copy())
                .orElseGet(() -> new JsonObject());
        if (deviceDefaultProperties != null) {
            defaults.mergeIn(deviceDefaultProperties);
        }

        if (!defaults.isEmpty()) {
            addDefaults(message, target, defaults, maxTtl);
        }
    }
    if (Strings.isNullOrEmpty(message.getContentType())) {
        // set default content type if none has been specified when creating the
        // message nor a default content type is available
        message.setContentType(CONTENT_TYPE_OCTET_STREAM);
    }
    if (useJmsVendorProps) {
        addJmsVendorProperties(message);
    }

    // make sure that device provided TTL is capped at max TTL (if set)
    // AMQP spec defines TTL as milliseconds
    final long maxTtlMillis = maxTtl * 1000L;
    if (target.hasEventEndpoint() && maxTtl != TenantConstants.UNLIMITED_TTL) {
        if (message.getTtl() == 0) {
            LOG.debug("setting event's TTL to tenant's max TTL [{}ms]", maxTtlMillis);
            setTimeToLive(message, Duration.ofSeconds(maxTtl));
        } else if (message.getTtl() > maxTtlMillis) {
            LOG.debug("limiting device provided TTL [{}ms] to max TTL [{}ms]", message.getTtl(), maxTtlMillis);
            setTimeToLive(message, Duration.ofSeconds(maxTtl));
        } else {
            LOG.trace("keeping event's TTL [0 < {}ms <= max TTL ({}ms)]", message.getTtl(), maxTtlMillis);
        }
    }
    return message;
}
 
Example 18
Source File: MetricsTest.java    From vertx-dropwizard-metrics with Apache License 2.0 4 votes vote down vote up
@Test
public void testHttpMetricsOnClose() throws Exception {
  int requests = 6;
  CountDownLatch latch = new CountDownLatch(requests);

  HttpClient client = vertx.createHttpClient(new HttpClientOptions());
  HttpServer server = vertx.createHttpServer(new HttpServerOptions().setHost("localhost").setPort(8081)).requestHandler(req -> {
    req.response().end();
  }).listen(ar -> {
    assertTrue(ar.succeeded());
    for (int i = 0; i < requests; i++) {
      client.get(8081, "localhost", "/some/uri", resp -> {
        latch.countDown();
      });
    }
  });

  awaitLatch(latch);

  client.close();
  server.close(ar -> {
    assertTrue(ar.succeeded());
    vertx.runOnContext(v -> testComplete());
  });

  await();

  JsonObject metrics;
  long start = System.currentTimeMillis();
  // This allows http server metrics to be completely removed from the registry
  do {
    metrics = metricsService.getMetricsSnapshot(server);
    if (metrics != null && metrics.isEmpty()) {
      break;
    }
    MILLISECONDS.sleep(100);
  } while (System.currentTimeMillis() - start < 5000);
  assertNotNull(metrics);
  assertEquals(Collections.emptyMap(), metrics.getMap());

  metrics = metricsService.getMetricsSnapshot(client);
  assertNotNull(metrics);
  assertNull(metrics.getJsonObject("connections.max-pool-size"));
}
 
Example 19
Source File: FileBasedCredentialsService.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Get the credentials associated with the authId and the given type. If type is null, all credentials associated
 * with the authId are returned (as JsonArray inside the return value).
 *
 * @param tenantId The id of the tenant the credentials belong to.
 * @param authId The authentication identifier to look up credentials for.
 * @param type The type of credentials to look up.
 * @param span The active OpenTracing span for this operation.
 * @return The credentials object of the given type or {@code null} if no matching credentials exist.
 */
private JsonObject getSingleCredentials(final String tenantId, final String authId, final String type,
        final JsonObject clientContext, final Span span) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(authId);
    Objects.requireNonNull(type);

    final ConcurrentMap<String, JsonArray> credentialsForTenant = credentials.get(tenantId);
    if (credentialsForTenant == null) {
        TracingHelper.logError(span, "no credentials found for tenant");
        return null;
    }

    final JsonArray authIdCredentials = credentialsForTenant.get(authId);
    if (authIdCredentials == null) {
        TracingHelper.logError(span, "no credentials found for auth-id");
        return null;
    }

    for (final Object authIdCredentialEntry : authIdCredentials) {
        final JsonObject authIdCredential = (JsonObject) authIdCredentialEntry;

        if (!type.equals(authIdCredential.getString(CredentialsConstants.FIELD_TYPE))) {
            // credentials type doesn't match ... continue search
            continue;
        }

        if (Boolean.FALSE.equals(authIdCredential.getBoolean(CredentialsConstants.FIELD_ENABLED, true))) {
            // do not report disabled
            continue;
        }

        if (clientContext != null && !clientContext.isEmpty()) {

            final JsonObject extensionProperties = authIdCredential.getJsonObject(RegistryManagementConstants.FIELD_EXT, new JsonObject());

            final boolean credentialsOnRecordMatchClientContext = clientContext.stream()
                    .filter(entry -> entry.getValue() != null)
                    .allMatch(entry -> {
                        final Object valueOnRecord = extensionProperties.getValue(entry.getKey());
                        LOG.debug("comparing client context property [name: {}, value: {}] to value on record: {}",
                                entry.getKey(), entry.getValue(), valueOnRecord);
                        if (valueOnRecord == null) {
                            return true;
                        } else {
                            return entry.getValue().equals(valueOnRecord);
                        }
                    });

            if (!credentialsOnRecordMatchClientContext) {
                continue;
            }

        }

        // copy
        final var authIdCredentialCopy = authIdCredential.copy();
        final var secrets = authIdCredentialCopy.getJsonArray(CredentialsConstants.FIELD_SECRETS);

        for (final Iterator<Object> i = secrets.iterator(); i.hasNext();) {

            final Object o = i.next();
            if (!(o instanceof JsonObject)) {
                i.remove();
                continue;
            }

            final JsonObject secret = (JsonObject) o;
            if (Boolean.FALSE.equals(secret.getBoolean(CredentialsConstants.FIELD_ENABLED, true))) {
                i.remove();
            }
        }

        if (secrets.isEmpty()) {
            // no more secrets left
            continue;
        }

        // return the first entry that matches
        return authIdCredentialCopy;
    }

    // we ended up with no match
    if (clientContext != null) {
        TracingHelper.logError(span, "no credentials found with matching type and client context");
    } else {
        TracingHelper.logError(span, "no credentials found with matching type");
    }

    return null;
}
 
Example 20
Source File: Stadium.java    From demo-mesh-arena with Apache License 2.0 4 votes vote down vote up
private JsonObject bounce(RoutingContext ctx, Segment segment, int excludeWall) {
  if (isOutside(segment.start())) {
    return new JsonObject();
  }
  Point goalA = GOAL_A.getCrossingPoint(segment);
  if (goalA != null) {
    // Team B scored!
    scoreB++;
    resetBall(ctx);
    return new JsonObject().put("scored", "visitors");
  }
  Point goalB = GOAL_B.getCrossingPoint(segment);
  if (goalB != null) {
    // Team A scored!
    scoreA++;
    resetBall(ctx);
    return new JsonObject().put("scored", "locals");
  }
  double minDistance = -1;
  Point collision = null;
  int bounceWall = -1;
  for (int i = 0; i < ARENA_SEGMENTS.length; i++) {
    if (i == excludeWall) {
      continue;
    }
    Segment wall = ARENA_SEGMENTS[i];
    Point tempCollision = wall.getCrossingPoint(segment);
    if (tempCollision != null) {
      double dist = tempCollision.diff(segment.start()).size();
      // minDistance is used to keep only the first wall encountered; if any wall was encounted first, forget this one.
      if (minDistance < 0 || dist < minDistance) {
        minDistance = dist;
        collision = tempCollision;
        bounceWall = i;
      }
    }
  }
  if (collision != null) {
    // Calculate bouncing vector and position of resulting position
    Point d = segment.end().diff(collision).normalize();
    Point p = ARENA_SEGMENTS[bounceWall].start().diff(collision).normalize();
    double dAngle = Math.acos(d.x());
    if (d.y() > 0) {
      dAngle = 2 * Math.PI - dAngle;
    }
    double pAngle = Math.acos(p.x());
    if (p.y() > 0) {
      pAngle = 2 * Math.PI - pAngle;
    }
    double dpAngle = 2 * pAngle - dAngle;
    while (dpAngle >= 2 * Math.PI) {
      dpAngle -= 2 * Math.PI;
    }
    Point result = collision.add(new Point(Math.cos(dpAngle), -Math.sin(dpAngle)).mult(segment.size() - minDistance));
    Segment resultVector = new Segment(collision, result);
    // Recursive call to check if the result vector itself is bouncing again
    JsonObject recResult = bounce(ctx, resultVector, bounceWall);
    if (recResult.isEmpty()) {
      // No bounce in recursive call => return new vector
      Point normalized = resultVector.derivate().normalize();
      return new JsonObject()
          .put("x", result.x())
          .put("y", result.y())
          .put("dx", normalized.x())
          .put("dy", normalized.y());
    }
    return recResult;
  }
  return new JsonObject();
}