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

The following examples show how to use io.vertx.core.json.JsonObject#forEach() . 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: MongoClientImpl.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Override
public Future<@Nullable JsonObject> runCommand(String commandName, JsonObject command) {
  requireNonNull(commandName, "commandName cannot be null");
  requireNonNull(command, "command cannot be null");
  // The command name must be the first entry in the bson, so to ensure this we must recreate and add the command
  // name as first (JsonObject is internally ordered)
  JsonObject json = new JsonObject();
  Object commandVal = command.getValue(commandName);
  if (commandVal == null) {
    throw new IllegalArgumentException("commandBody does not contain key for " + commandName);
  }
  json.put(commandName, commandVal);
  command.forEach(entry -> {
    if (!entry.getKey().equals(commandName)) {
      json.put(entry.getKey(), entry.getValue());
    }
  });

  Promise<JsonObject> promise = vertx.promise();
  holder.db.runCommand(wrap(json), JsonObject.class).subscribe(new SingleResultSubscriber<>(promise));
  return promise.future();
}
 
Example 2
Source File: Service.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
/**
 *
 */
private static void onConfigLoaded(AsyncResult<JsonObject> ar) {
  final JsonObject config = ar.result();
  //Convert empty string values to null
  config.forEach(e -> {
    if (e.getValue() != null && e.getValue().equals("")) {
      config.put(e.getKey(), (String) null);
    }
  });
  configuration = config.mapTo(Config.class);

  initializeLogger(configuration);
  decryptSecrets();

  cacheClient = CacheClient.create();

  spaceConfigClient = SpaceConfigClient.getInstance();
  connectorConfigClient = ConnectorConfigClient.getInstance();

  spaceConfigClient.init(spaceConfigReady -> {
    if (spaceConfigReady.succeeded()) {
      connectorConfigClient.init(connectorConfigReady -> {
        if (connectorConfigReady.succeeded()) {
          if (Service.configuration.INSERT_LOCAL_CONNECTORS) {
            connectorConfigClient.insertLocalConnectors(result -> onLocalConnectorsInserted(result, config));
          }
          else {
            onLocalConnectorsInserted(Future.succeededFuture(), config);
          }
        }
      });
    }
  });
}
 
Example 3
Source File: KubernetesServiceImporter.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
static Record createRecord(JsonObject service) {
  JsonObject metadata = service.getJsonObject("metadata");
  Record record = new Record()
    .setName(metadata.getString("name"));

  JsonObject labels = metadata.getJsonObject("labels");

  if (labels != null) {
    labels.forEach(entry -> record.getMetadata().put(entry.getKey(), entry.getValue().toString()));
  }

  record.getMetadata().put("kubernetes.namespace", metadata.getString("namespace"));
  record.getMetadata().put("kubernetes.name", metadata.getString("name"));
  record.getMetadata().put(KUBERNETES_UUID, metadata.getString("uid"));

  String type = record.getMetadata().getString("service-type");

  // If not set, try to discovery it
  if (type == null) {
    type = discoveryType(service, record);
  }

  switch (type) {
    case HttpEndpoint.TYPE:
      manageHttpService(record, service);
      break;
    // TODO Add JDBC client, redis and mongo
    default:
      manageUnknownService(record, service, type);
      break;
  }

  return record;
}
 
Example 4
Source File: PrometheusMetricResource.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private static Map<String, String> parseMetadata(JsonObject data) {
    HashMap<String, String> metadata = new HashMap<>();
    data.forEach(set -> {
        metadata.put(set.getKey(), set.getValue().toString());
    });
    return metadata;
}
 
Example 5
Source File: VertxMessageExtractAdapter.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
public VertxMessageExtractAdapter(final JsonObject obj) {
    // Convert to single valued map
    this.map = new HashMap<>();

    JsonObject header = obj.getJsonObject("_apmHeader");
    if (header != null) {
        header.forEach(entry -> map.put(entry.getKey(), entry.getValue().toString()));
        // Remove header
        obj.remove("_apmHeader");
    }
}
 
Example 6
Source File: Config.java    From nubes with Apache License 2.0 5 votes vote down vote up
private void createServices() {
  JsonObject services = json.getJsonObject("services", new JsonObject());
  this.serviceRegistry = new ServiceRegistry(vertx, this);
  services.forEach(entry -> {
    String name = entry.getKey();
    String className = (String) entry.getValue();
    try {
      Class<?> clazz = Class.forName(className);
      this.serviceRegistry.registerService(name, clazz.newInstance());
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
      throw new VertxException(e);
    }
  });
}
 
Example 7
Source File: OpenAPI3Utils.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
protected static Map<String, JsonObject> resolveAllOfArrays(List<JsonObject> allOfSchemas) {
  Map<String, JsonObject> properties = new HashMap<>();
  for (JsonObject schema : allOfSchemas) {
    if ("object".equals(schema.getString("type")))
      throw RouterFactoryException.createUnsupportedSpecFeature("allOf allows only inner object types in parameters. Schema: " + schema.encode());
    schema.forEach(e -> properties.put(e.getKey(), (JsonObject) e.getValue()));
  }
  return properties;
}
 
Example 8
Source File: GroovyStaticExtension.java    From vertx-codetrans with Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> fromJsonObject(JsonConverter converter, JsonObject obj) {
  Map<String, Object> m = new HashMap<>();
  obj.forEach(entry -> {
    if (entry.getValue() instanceof JsonObject) {
      m.put(entry.getKey(), fromJsonObject(converter, (JsonObject) entry.getValue()));
    } else if (entry.getValue() instanceof JsonArray) {
      m.put(entry.getKey(), fromJsonArray(converter, (JsonArray) entry.getValue()));
    } else {
      m.put(entry.getKey(), entry.getValue());
    }
  });
  return m;
}
 
Example 9
Source File: VertxEngineConfig.java    From apiman with Apache License 2.0 5 votes vote down vote up
protected void substituteLeafVars(JsonObject node) {
    node.forEach(elem -> {
       Object value = elem.getValue();
       if (value instanceof JsonObject) {
           substituteLeafVars((JsonObject) value);
       } else if (value instanceof String) {
           node.put(elem.getKey(), SUBSTITUTOR.replace((String) value));
       }
    });
}
 
Example 10
Source File: HttpBasedMessageMapping.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private void mapMessageRequest(
        final MqttContext ctx,
        final ResourceIdentifier targetAddress,
        final JsonObject registrationInfo,
        final MapperEndpoint mapperEndpoint,
        final Handler<AsyncResult<MappedMessage>> resultHandler) {

    final MultiMap headers = MultiMap.caseInsensitiveMultiMap();
    registrationInfo.forEach(property -> {
        final Object value = property.getValue();
        if (value instanceof String) {
            // prevent strings from being enclosed in quotes
            headers.add(property.getKey(), (String) value);
        } else {
            headers.add(property.getKey(), Json.encode(value));
        }
    });

    final Promise<MappedMessage> result = Promise.promise();

    webClient.post(mapperEndpoint.getPort(), mapperEndpoint.getHost(), mapperEndpoint.getUri())
        .putHeaders(headers)
        .ssl(mapperEndpoint.isTlsEnabled())
        .expect(ResponsePredicate.SC_OK)
        .sendBuffer(ctx.message().payload(), httpResponseAsyncResult -> {
            if (httpResponseAsyncResult.succeeded()) {
                final HttpResponse<Buffer> httpResponse = httpResponseAsyncResult.result();

                final Map<String, String> additionalProperties = new HashMap<>();
                httpResponse.headers().forEach(entry -> additionalProperties.put(entry.getKey(), entry.getValue()));

                final String mappedDeviceId = Optional.ofNullable(additionalProperties.remove(MessageHelper.APP_PROPERTY_DEVICE_ID))
                        .map(id -> {
                            LOG.debug("original {} has been mapped to [device-id: {}]", ctx.authenticatedDevice(), id);
                            return id;
                        })
                        .orElse(targetAddress.getResourceId());

                result.complete(new MappedMessage(
                        ResourceIdentifier.from(targetAddress.getEndpoint(), targetAddress.getTenantId(), mappedDeviceId),
                        httpResponse.bodyAsBuffer(),
                        additionalProperties));
            } else {
                LOG.debug("mapping of message published by {} failed", ctx.authenticatedDevice(), httpResponseAsyncResult.cause());
                result.complete(new MappedMessage(targetAddress, ctx.message().payload()));
            }
            resultHandler.handle(result.future());
        });
}
 
Example 11
Source File: IntegrationTestSupport.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * A simple implementation of subtree containment: all entries of the JsonObject that is tested to be contained
 * must be contained in the other JsonObject as well. Nested JsonObjects are treated the same by recursively calling
 * this method to test the containment.
 * JsonArrays are tested for containment as well: all elements in a JsonArray belonging to the contained JsonObject
 * must be present in the corresponding JsonArray of the other JsonObject as well. The sequence of the array elements
 * is not important (suitable for the current tests).
 * @param jsonObject The JsonObject that must fully contain the other JsonObject (but may contain more entries as well).
 * @param jsonObjectToBeContained The JsonObject that needs to be fully contained inside the other JsonObject.
 * @return The result of the containment test.
 */
public static boolean testJsonObjectToBeContained(final JsonObject jsonObject, final JsonObject jsonObjectToBeContained) {
    if (jsonObjectToBeContained == null) {
        return true;
    }
    if (jsonObject == null) {
        return false;
    }
    final AtomicBoolean containResult = new AtomicBoolean(true);

    jsonObjectToBeContained.forEach(entry -> {
        if (!jsonObject.containsKey(entry.getKey())) {
            containResult.set(false);
        } else {
            if (entry.getValue() == null) {
                if (jsonObject.getValue(entry.getKey()) != null) {
                    containResult.set(false);
                }
            } else if (entry.getValue() instanceof JsonObject) {
                if (!(jsonObject.getValue(entry.getKey()) instanceof JsonObject)) {
                    containResult.set(false);
                } else {
                    if (!testJsonObjectToBeContained((JsonObject) entry.getValue(),
                            (JsonObject) jsonObject.getValue(entry.getKey()))) {
                        containResult.set(false);
                    }
                }
            } else if (entry.getValue() instanceof JsonArray) {
                if (!(jsonObject.getValue(entry.getKey()) instanceof JsonArray)) {
                    containResult.set(false);
                } else {
                    // compare two JsonArrays
                    final JsonArray biggerArray = (JsonArray) jsonObject.getValue(entry.getKey());
                    final JsonArray smallerArray = (JsonArray) entry.getValue();

                    if (!testJsonArrayToBeContained(biggerArray, smallerArray)) {
                        containResult.set(false);
                    }
                }
            } else {
                if (!entry.getValue().equals(jsonObject.getValue(entry.getKey()))) {
                    containResult.set(false);
                }
            }
        }
    });
    return containResult.get();
}
 
Example 12
Source File: MessageHelper.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Adds default properties to an AMQP message.
 * <p>
 * This method also sets the message's <em>time-to-live</em> (TTL) property
 * as described in
 *
 * @param message The message to add the properties to.
 * @param target The target address of the message or {@code null} if the message's
 *               <em>to</em> property contains the target address. The target
 *               address is used to determine if the message represents an event or not.
 *               Determining this information from the <em>to</em> property
 *               requires additional parsing which can be prevented by passing in the
 *               target address as a {@code ResourceIdentifier} instead.
 * @param defaults The default properties (device and tenant level) to set or {@code null}
 *                 if no default properties are defined for the device that the message originates from.
 * @param maxTtl The maximum time-to-live (in seconds) that should be used for limiting a default TTL.
 * @return The message with the default properties set.
 * @throws NullPointerException if message is {@code null} or if target is {@code null}
 *                              and the message does not contain an address.
 */
public static Message addDefaults(
        final Message message,
        final ResourceIdentifier target,
        final JsonObject defaults,
        final long maxTtl) {

    Objects.requireNonNull(message);

    if (defaults == null) {
        return message;
    }

    final ResourceIdentifier ri = Optional.ofNullable(target)
            .orElseGet(() -> ResourceIdentifier.fromString(message.getAddress()));

    defaults.forEach(prop -> {

        switch (prop.getKey()) {
        case MessageHelper.SYS_HEADER_PROPERTY_TTL:
            if (ri.hasEventEndpoint() && message.getTtl() == 0 && Number.class.isInstance(prop.getValue())) {
                final long defaultTtl = ((Number) prop.getValue()).longValue();
                if (maxTtl != TenantConstants.UNLIMITED_TTL && defaultTtl > maxTtl) {
                    MessageHelper.setTimeToLive(message, Duration.ofSeconds(maxTtl));
                } else {
                    MessageHelper.setTimeToLive(message, Duration.ofSeconds(defaultTtl));
                }
            }
            break;
        case SYS_PROPERTY_CONTENT_TYPE:
            if (Strings.isNullOrEmpty(message.getContentType()) && String.class.isInstance(prop.getValue())) {
                // set to default type registered for device or fall back to default content type
                message.setContentType((String) prop.getValue());
            }
            break;
        case SYS_PROPERTY_CONTENT_ENCODING:
            if (Strings.isNullOrEmpty(message.getContentEncoding()) && String.class.isInstance(prop.getValue())) {
                message.setContentEncoding((String) prop.getValue());
            }
            break;
        case SYS_HEADER_PROPERTY_DELIVERY_COUNT:
        case SYS_HEADER_PROPERTY_DURABLE:
        case SYS_HEADER_PROPERTY_FIRST_ACQUIRER:
        case SYS_HEADER_PROPERTY_PRIORITY:
        case SYS_PROPERTY_ABSOLUTE_EXPIRY_TIME:
        case SYS_PROPERTY_CORRELATION_ID:
        case SYS_PROPERTY_CREATION_TIME:
        case SYS_PROPERTY_GROUP_ID:
        case SYS_PROPERTY_GROUP_SEQUENCE:
        case SYS_PROPERTY_MESSAGE_ID:
        case SYS_PROPERTY_REPLY_TO:
        case SYS_PROPERTY_REPLY_TO_GROUP_ID:
        case SYS_PROPERTY_SUBJECT:
        case SYS_PROPERTY_TO:
        case SYS_PROPERTY_USER_ID:
            // these standard properties cannot be set using defaults
            LOG.debug("ignoring default property [{}] registered for device", prop.getKey());
            break;
        default:
            // add all other defaults as application properties
            addProperty(message, prop.getKey(), prop.getValue());
        }
    });

    return message;
}
 
Example 13
Source File: JsonObjectCodec.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
@Override
protected void forEach(JsonObject object, BiConsumer<String, Object> objectConsumer) {
  object.forEach(entry -> {
    objectConsumer.accept(entry.getKey(), entry.getValue());
  });
}
 
Example 14
Source File: EventBusBridgeImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
private void checkAndSend(boolean send, String address, Object body,
                          JsonObject headers,
                          SockJSSocket sock,
                          String replyAddress,
                          Message awaitingReply) {
  SockInfo info = sockInfos.get(sock);
  if (replyAddress != null && !checkMaxHandlers(sock, info)) {
    return;
  }
  Handler<AsyncResult<Message<Object>>> replyHandler;
  if (replyAddress != null) {
    replyHandler = result -> {
      if (result.succeeded()) {
        Message message = result.result();
        // Note we don't check outbound matches for replies
        // Replies are always let through if the original message
        // was approved

        // Now - the reply message might itself be waiting for a reply - which would be inbound -so we need
        // to add the message to the messages awaiting reply so it can be let through
        checkAddAccceptedReplyAddress(message);
        deliverMessage(sock, replyAddress, message);
      } else {
        ReplyException cause = (ReplyException) result.cause();
        JsonObject envelope =
          new JsonObject()
            .put("type", "err")
            .put("address", replyAddress)
            .put("failureCode", cause.failureCode())
            .put("failureType", cause.failureType().name())
            .put("message", cause.getMessage());
        sock.write(buffer(envelope.encode()));
      }
      info.handlerCount--;
    };
  } else {
    replyHandler = null;
  }
  if (log.isDebugEnabled()) {
    log.debug("Forwarding message to address " + address + " on event bus");
  }
  MultiMap mHeaders;
  if (headers != null) {
    mHeaders = HttpHeaders.headers();
    headers.forEach(entry -> mHeaders.add(entry.getKey(), entry.getValue().toString()));
  } else {
    mHeaders = null;
  }
  if (send) {
    if (awaitingReply != null) {
      if (replyAddress != null) {
        awaitingReply.replyAndRequest(body, new DeliveryOptions().setSendTimeout(replyTimeout).setHeaders(mHeaders), replyHandler);
      } else {
        awaitingReply.reply(body, new DeliveryOptions().setSendTimeout(replyTimeout).setHeaders(mHeaders));
      }
    } else {
      if (replyAddress != null) {
        eb.request(address, body, new DeliveryOptions().setSendTimeout(replyTimeout).setHeaders(mHeaders), replyHandler);
      } else {
        eb.send(address, body, new DeliveryOptions().setSendTimeout(replyTimeout).setHeaders(mHeaders));
      }
    }
    if (replyAddress != null) {
      info.handlerCount++;
    }
  } else {
    eb.publish(address, body, new DeliveryOptions().setHeaders(mHeaders));
  }
}