kuujo / vertigo

Flow-based programming for the Vert.x application platform.
Apache License 2.0
155 stars 24 forks source link

Json schemas #20

Closed kuujo closed 11 years ago

kuujo commented 11 years ago

This adds schema validation for component inputs with the following changes:

Example:

MathVerticle.java

vertigo.createBasicWorker().start(new Handler<AsyncResult<BasicWorker>>() {
  public void handle(AsyncResult<BasicWorker> result) {
    if (result.failed()) {
      return;
    }

    final BasicWorker worker = result.result();

    // Create a schema that requires a message structure like:
    // {
    //   "operator": "+",
    //   "values": [1, 2, 3]
    "" }
    ObjectSchema schema = new ObjectSchema();
    schema.addField("operator", String.class);
    schema.addField("values", new ArraySchema().setType(Integer.class));

    // Add the schema to the worker.
    worker.declareSchema(schema);

    // Register a message handler that calculates a value.
    worker.messageHandler(new Handler<JsonMessage>() {
      public void handle(JsonMessage message) {
        // We can be confident that the "operator" field exists and is a String.
        String operator = message.body().getString("operator");
        switch (operator) {
          case "+":
            int sum = 0;
            // We can be confident that each of these values are integers.
            for (Object num : message.body().getArray("values")) {
              sum += Integer.valueOf(num);
            }
            worker.emit(new JsonObject().putString("sum", sum), message);
            break;
          case "*":
            int product = 0;
            // Again, we're still confident these are integers.
            for (Object num : message.body().getArray("values")) {
              product *= Integer.valueOf(num);
            }
            worker.emit(new JsonObject().putString("product", product), message);
            break;
          default:
            worker.fail(message);
            break;
        }
      }
    });
  }
});
kuujo commented 11 years ago

13

ramukima commented 10 years ago

You Rock !!

And MANY congratulations for getting this finally into the vert.x module repo.