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

The following examples show how to use io.vertx.core.json.JsonArray#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: ConsulServiceImporterTest.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
private JsonArray find(String service) {
  JsonArray array = new JsonArray();
  services.stream().filter(json -> json.getJsonObject("Service").getString("Service").equalsIgnoreCase(service)).forEach(array::add);
  if (! array.isEmpty()) {
    return array;
  }
  return null;
}
 
Example 2
Source File: KubernetesServiceImporter.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
private static void manageUnknownService(Record record, JsonObject service, String type) {
  JsonObject spec = service.getJsonObject("spec");
  JsonArray ports = spec.getJsonArray("ports");
  if (ports != null && !ports.isEmpty()) {
    if (ports.size() > 1) {
      LOGGER.warn("More than one ports has been found for " + record.getName() + " - taking the " +
        "first one to build the record location");
    }
    JsonObject port = ports.getJsonObject(0);
    JsonObject location = port.copy();

    if (isExternalService(service)) {
      location.put("host", spec.getString("externalName"));
    } else {
      //Number or name of the port to access on the pods targeted by the service.
      Object targetPort = port.getValue("targetPort");
      if (targetPort instanceof Integer) {
        location.put("internal-port", (Integer) targetPort);
      }
      location.put("host", spec.getString("clusterIP"));
    }

    record.setLocation(location).setType(type);
  } else {
    throw new IllegalStateException("Cannot extract the location from the service " + record + " - no port");
  }
}
 
Example 3
Source File: KubernetesServiceImporter.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
private static void manageHttpService(Record record, JsonObject service) {
  JsonObject spec = service.getJsonObject("spec");
  JsonArray ports = spec.getJsonArray("ports");

  if (ports != null && !ports.isEmpty()) {
    if (ports.size() > 1) {
      LOGGER.warn("More than one port has been found for " + record.getName() + " - taking the first" +
        " one to extract the HTTP endpoint location");
    }

    JsonObject port = ports.getJsonObject(0);
    Integer p = port.getInteger("port");

    record.setType(HttpEndpoint.TYPE);

    HttpLocation location = new HttpLocation(port.copy());

    if (isExternalService(service)) {
      location.setHost(spec.getString("externalName"));
    } else {
      location.setHost(spec.getString("clusterIP"));
    }

    if (isTrue(record.getMetadata().getString("ssl")) || p != null && p == 443) {
      location.setSsl(true);
    }
    record.setLocation(location.toJson());
  } else {
    throw new IllegalStateException("Cannot extract the HTTP URL from the service " + record + " - no port");
  }
}
 
Example 4
Source File: AbstractRegistrationService.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Gets the list of gateways that may act on behalf of a given device.
 * <p>
 * To compile this list of gateways, this default implementation gets the list of gateways from the value of the
 * {@link RegistryManagementConstants#FIELD_VIA} property in the device's registration information and resolves
 * the members of the groups that are in the {@link RegistryManagementConstants#FIELD_VIA_GROUPS} property of the device.
 * <p>
 * Subclasses may override this method to provide a different means to determine the supported gateways.
 *
 * @param tenantId The tenant id.
 * @param deviceId The device id.
 * @param registrationInfo The device's registration information.
 * @param span The active OpenTracing span for this operation. It is not to be closed in this method! An
 *            implementation should log (error) events on this span and it may set tags and use this span as the
 *            parent for any spans created in this method.
 * @return A future indicating the outcome of the operation.
 *         <p>
 *         The future will succeed with the list of gateways as a JSON array of Strings (never {@code null})
 *         or it will fail with a {@link ServiceInvocationException} indicating the cause of the failure.
 */
protected Future<JsonArray> getSupportedGatewaysForDevice(
        final String tenantId,
        final String deviceId,
        final JsonObject registrationInfo,
        final Span span) {

    final JsonArray via = convertObjectToJsonArray(registrationInfo.getValue(RegistryManagementConstants.FIELD_VIA));
    final JsonArray viaGroups = convertObjectToJsonArray(registrationInfo.getValue(RegistryManagementConstants.FIELD_VIA_GROUPS));

    final Future<JsonArray> resultFuture;
    if (viaGroups.isEmpty()) {
        resultFuture = Future.succeededFuture(via);
    } else {
        resultFuture = resolveGroupMembers(tenantId, viaGroups, span).compose(groupMembers -> {
            for (final Object gateway : groupMembers) {
                if (!via.contains(gateway)) {
                    via.add(gateway);
                }
            }
            return Future.succeededFuture(via);
        }).recover(thr -> {
            LOG.debug("failed to resolve group members", thr);
            TracingHelper.logError(span, "failed to resolve group members: " + thr.getMessage());
            return Future.failedFuture(thr);
        });
    }
    return resultFuture;
}
 
Example 5
Source File: CredentialsObject.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Checks if this credentials object contains secrets that comply with the Credentials
 * API specification.
 *
 * @param secretValidator a custom check that is performed for each secret in addition
 *                        to the standard checks. The validator
 *                        should throw an exception to indicate a failure to
 *                        validate the secret.
 * @throws NullPointerException if the validator is {@code null}.
 * @throws IllegalStateException if no secrets are set or any of the secrets' not-before
 *         and not-after properties are malformed or if the given validator fails for any
 *         of the secrets.
 */
public void checkSecrets(final BiConsumer<String, JsonObject> secretValidator) {

    Objects.requireNonNull(secretValidator);
    final JsonArray secrets = getSecrets();
    if (secrets == null || secrets.isEmpty()) {

        throw new IllegalStateException("credentials object must contain at least one secret");

    } else {

        try {
            switch (getType()) {
            case CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD:
                checkSecrets(secrets, secret -> {
                    checkHashedPassword(secret);
                    secretValidator.accept(getType(), secret);
                });
                break;
            default:
                checkSecrets(secrets, secret -> {});
            }
        } catch (final Exception e) {
            throw new IllegalStateException(e.getMessage());
        }
    }
}
 
Example 6
Source File: KubernetesServiceImporter.java    From vertx-service-discovery with Apache License 2.0 4 votes vote down vote up
static String discoveryType(JsonObject service, Record record) {
  JsonObject spec = service.getJsonObject("spec");
  JsonArray ports = spec.getJsonArray("ports");
  if (ports == null || ports.isEmpty()) {
    return ServiceType.UNKNOWN;
  }

  if (ports.size() > 1) {
    LOGGER.warn("More than one ports has been found for " + record.getName() + " - taking the " +
      "first one to build the record location");
  }

  JsonObject port = ports.getJsonObject(0);
  int p = port.getInteger("port");

  // Http
  if (p == 80 || p == 443 || p >= 8080 && p <= 9000) {
    return HttpEndpoint.TYPE;
  }

  // PostGreSQL
  if (p == 5432 || p == 5433) {
    return JDBCDataSource.TYPE;
  }

  // MySQL
  if (p == 3306 || p == 13306) {
    return JDBCDataSource.TYPE;
  }

  // Redis
  if (p == 6379) {
    return RedisDataSource.TYPE;
  }

  // Mongo
  if (p == 27017 || p == 27018 || p == 27019) {
    return MongoDataSource.TYPE;
  }

  return ServiceType.UNKNOWN;
}
 
Example 7
Source File: CommandTargetMapperImpl.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private Future<JsonObject> determineTargetInstanceJson(final JsonObject adapterInstancesJson, final String deviceId,
        final List<String> viaGateways, final Span span) {
    final JsonArray instancesArray = adapterInstancesJson.getJsonArray(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCES);
    if (instancesArray == null || instancesArray.isEmpty()) {
        return createAndLogInternalServerErrorFuture(span, "Invalid result JSON; field '"
                + DeviceConnectionConstants.FIELD_ADAPTER_INSTANCES + "' is null or empty");
    }

    final JsonObject targetInstanceObject;
    try {
        if (instancesArray.size() == 1) {
            targetInstanceObject = instancesArray.getJsonObject(0);
        } else {
            targetInstanceObject = chooseTargetGatewayAndAdapterInstance(instancesArray);
        }
    } catch (final ClassCastException e) {
        return createAndLogInternalServerErrorFuture(span, "Invalid result JSON: " + e.toString());
    }
    final String targetDevice = targetInstanceObject.getString(DeviceConnectionConstants.FIELD_PAYLOAD_DEVICE_ID);
    final String targetAdapterInstance = targetInstanceObject.getString(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCE_ID);
    if (targetDevice == null || targetAdapterInstance == null) {
        return createAndLogInternalServerErrorFuture(span, "Invalid result JSON, missing target device and/or adapter instance");
    }
    if (!targetDevice.equals(deviceId)) {
        // target device is a gateway
        if (!viaGateways.contains(targetDevice)) {
            return createAndLogInternalServerErrorFuture(span,
                    "Invalid result JSON, target gateway " + targetDevice + " is not in via gateways list");
        }
        span.setTag(MessageHelper.APP_PROPERTY_GATEWAY_ID, targetDevice);
    }

    final String choiceInfo = instancesArray.size() > 1 ? " chosen from " + instancesArray.size() + " entries" : "";
    final String gatewayInfo = !targetDevice.equals(deviceId) ? " gateway '" + targetDevice + "' and" : "";
    final String infoMsg = String.format("command target%s:%s adapter instance '%s'", choiceInfo, gatewayInfo, targetAdapterInstance);
    LOG.debug(infoMsg);
    span.log(infoMsg);

    span.setTag(MessageHelper.APP_PROPERTY_ADAPTER_INSTANCE_ID, targetAdapterInstance);
    return Future.succeededFuture(targetInstanceObject);
}