private void start(final JsonObject config) {
    final RxVertx rx = new RxVertx(vertx);

    new FakeDataGenerator(config, rx);
    new MetricsUpdatesRebroadcaster(config, rx);
    new HttpServer(config, rx);
    final String host = config.getObject("http").getString("host");
    final Integer port = config.getObject("http").getInteger("port");

    container.logger().info(String.format("Vert.x/Rx/React demo running on %s:%d", host, port));
  }
Example #2
0
 private static String getLatestUpdate(JsonObject json) {
   JsonObject responseData = json.getObject("ResponseData");
   if (responseData != null) {
     return responseData.getString("LatestUpdate");
   }
   return "ResponseData missing";
 }
 private JsonObject getMandatoryObject(JsonObject json, String field) {
   JsonObject value = json.getObject(field);
   if (value == null) {
     throw new IllegalStateException(field + " must be specified for message");
   }
   return value;
 }
Example #4
0
 /** Redeploys a deployment. */
 private void doRedeploy(final JsonObject deploymentInfo) {
   if (deploymentInfo.getString("type").equals("module")) {
     log.info(
         String.format(
             "%s - redeploying module %s",
             DefaultGroupManager.this, deploymentInfo.getString("module")));
     final CountDownLatch latch = new CountDownLatch(1);
     platform.deployModule(
         deploymentInfo.getString("module"),
         deploymentInfo.getObject("config", new JsonObject()),
         deploymentInfo.getInteger("instances", 1),
         createRedeployHandler(deploymentInfo, latch));
     try {
       latch.await(10, TimeUnit.SECONDS);
     } catch (InterruptedException e) {
     }
   } else if (deploymentInfo.getString("type").equals("verticle")) {
     log.info(
         String.format(
             "%s - redeploying verticle %s",
             DefaultGroupManager.this, deploymentInfo.getString("main")));
     final CountDownLatch latch = new CountDownLatch(1);
     if (deploymentInfo.getBoolean("worker", false)) {
       platform.deployWorkerVerticle(
           deploymentInfo.getString("main"),
           deploymentInfo.getObject("config", new JsonObject()),
           deploymentInfo.getInteger("instances", 1),
           deploymentInfo.getBoolean("multi-threaded"),
           createRedeployHandler(deploymentInfo, latch));
     } else {
       platform.deployVerticle(
           deploymentInfo.getString("main"),
           deploymentInfo.getObject("config", new JsonObject()),
           deploymentInfo.getInteger("instances", 1),
           createRedeployHandler(deploymentInfo, latch));
     }
     try {
       latch.await(10, TimeUnit.SECONDS);
     } catch (InterruptedException e) {
     }
   }
 }
  /*
  Empty inboundPermitted means reject everything - this is the default.
  If at least one match is supplied and all the fields of any match match then the message inboundPermitted,
  this means that specifying one match with a JSON empty object means everything is accepted
   */
  private Match checkMatches(boolean inbound, String address, Object body) {

    if (inbound && acceptedReplyAddresses.remove(address)) {
      // This is an inbound reply, so we accept it
      return new Match(true, false);
    }

    List<JsonObject> matches = inbound ? inboundPermitted : outboundPermitted;

    for (JsonObject matchHolder : matches) {
      String matchAddress = matchHolder.getString("address");
      String matchRegex;
      if (matchAddress == null) {
        matchRegex = matchHolder.getString("address_re");
      } else {
        matchRegex = null;
      }

      boolean addressOK;
      if (matchAddress == null) {
        if (matchRegex == null) {
          addressOK = true;
        } else {
          addressOK = regexMatches(matchRegex, address);
        }
      } else {
        addressOK = matchAddress.equals(address);
      }

      if (addressOK) {
        boolean matched = true;
        // Can send message other than JSON too - in which case we can't do deep matching on
        // structure of message
        if (body instanceof JsonObject) {
          JsonObject match = matchHolder.getObject("match");
          if (match != null) {
            for (String fieldName : match.getFieldNames()) {
              if (!match.getField(fieldName).equals(((JsonObject) body).getField(fieldName))) {
                matched = false;
                break;
              }
            }
          }
        }
        if (matched) {
          Boolean b = matchHolder.getBoolean("requires_auth");
          return new Match(true, b != null && b);
        }
      }
    }
    return new Match(false, false);
  }
    @Override
    public void handle(Message<JsonObject> reply) {
      final JsonObject body = reply.body();

      if ("ok".equals(body.getString("status"))) {
        this.worlds.add(body.getObject("result"));
        if (this.worlds.size() == this.queries) {
          // All queries have completed; send the response.
          final String result = Json.encode(worlds);
          final int contentLength = result.getBytes(StandardCharsets.UTF_8).length;
          this.req.response().putHeader("Content-Type", "application/json; charset=UTF-8");
          this.req.response().putHeader("Content-Length", String.valueOf(contentLength));
          this.req.response().end(result);
        }
      } else {
        System.err.println("Failed to execute query");
      }
    }
  private void parseConfigAndStart(final Buffer buffer) {
    final JsonObject config = new JsonObject(buffer.toString());

    container.deployModule(
        METRICS_MODULE,
        config.getObject("metrics"),
        ar -> {
          if (ar.succeeded()) {
            container
                .logger()
                .fatal("Deployed: " + METRICS_MODULE + " with id: " + ar.result(), ar.cause());

            start(config);
          } else {
            container.logger().fatal("Failed to deploy: " + METRICS_MODULE, ar.cause());
          }
        });
  }
 @Override
 public void handle(Message<JsonObject> event) {
   Integer id = event.body.getInteger("id");
   JsonObject params = event.body.getObject("op");
   JsonObject state = event.body.getObject("state");
   JsonObject meta = state.getObject("meta");
   if (meta == null) {
     meta = new JsonObject();
   }
   StringBuilder key = new StringBuilder();
   key.append(HandlerUtils.determineKs(params, state, null));
   key.append(' ');
   key.append(HandlerUtils.determineCf(params, state, null));
   key.append(' ');
   key.append(params.getString("type"));
   meta.putObject(key.toString(), new JsonObject().putString("clazz", params.getString("clazz")));
   state.putObject("meta", meta);
   event.reply(new JsonObject().putString(id.toString(), "OK").putObject("state", state));
 }
Example #9
0
  public static JsonObject invoke(JsonObject json, String area) {
    JsonObject responseData = json.getObject("ResponseData");

    if (responseData == null) {
      return new JsonObject();
    }

    if (Server.l != null) {
      Server.l.info(getLatestUpdate(json) + " - " + getExecutionTime(json));
    }

    Predicate<String> isJsonArray = name -> responseData.getField(name) instanceof JsonArray;

    Function<String, List<JsonObject>> jsonArrayToList =
        name -> {
          Stream<Object> stream =
              stream(responseData.<JsonArray>getField(name).spliterator(), false);
          Stream<JsonObject> objectStream = stream.filter(getFilterFor(area));
          return objectStream.collect(toList());
        };

    Predicate<Map.Entry<String, List<JsonObject>>> nonEmpty = entry -> !entry.getValue().isEmpty();

    Stream<Map.Entry<String, List<JsonObject>>> entryStream =
        responseData
            .getFieldNames()
            .stream()
            .filter(isJsonArray)
            .collect(toMap(String::toLowerCase, jsonArrayToList))
            .entrySet()
            .stream()
            .filter(nonEmpty);

    JsonObject result = toJsonObject(entryStream);

    setUniqueKeysOn(result.getArray("trains"));
    writeHeaderFields(result);

    return result;
  }
Example #10
0
  @Override
  public void set(String sid, JsonObject sess, final Handler<Object> callback) {
    sid = prefix + sid;

    Integer maxAge = null;

    JsonObject obj = sess.getObject("cookie");
    if (obj != null) {
      maxAge = obj.getInteger("maxAge");
    }

    String session = sess.encode();
    int ttl;

    if (maxAge != null) {
      ttl = maxAge / 1000;
    } else {
      ttl = this.ttl;
    }

    JsonObject redis = new JsonObject();
    redis.putString("command", "setex");
    redis.putArray("args", new JsonArray().add(sid).add(ttl).add(session));

    eventBus.send(
        redisAddress,
        redis,
        new Handler<Message<JsonObject>>() {
          @Override
          public void handle(Message<JsonObject> reply) {
            if ("ok".equals(reply.body().getString("status"))) {
              callback.handle(null);
            } else {
              callback.handle(reply.body().getString("message"));
            }
          }
        });
  }
Example #11
0
 @Override
 public void handleUser(Message<JsonObject> event) {
   Integer id = event.body.getInteger("id");
   JsonObject params = event.body.getObject("op");
   JsonObject state = event.body.getObject("state");
   JsonObject meta = state.getObject("meta");
   JsonObject metaColumn = state.getObject("metaColumn");
   JsonObject metaRanged = state.getObject("metaRanged");
   if (meta == null) {
     meta = new JsonObject();
   }
   if (metaColumn == null) {
     metaColumn = new JsonObject();
   }
   if (metaRanged == null) {
     metaRanged = new JsonObject();
   }
   if (params.getString("type") != null) {
     StringBuilder key = new StringBuilder();
     key.append(HandlerUtils.instance.determineKs(params, state, null));
     key.append(' ');
     key.append(HandlerUtils.instance.determineCf(params, state, null));
     key.append(' ');
     key.append(params.getString("type"));
     meta.putObject(
         key.toString(), new JsonObject().putString("clazz", params.getString("clazz")));
     state.putObject("meta", meta);
     event.reply(new JsonObject().putString(id.toString(), "OK").putObject("state", state));
   } else if (params.getField("name") != null) {
     Object o = params.getField("name");
     ByteBuffer bb = HandlerUtils.instance.byteBufferForObject(o);
     StringBuilder key = new StringBuilder();
     key.append(HandlerUtils.instance.determineKs(params, state, null));
     key.append(' ');
     key.append(HandlerUtils.instance.determineCf(params, state, null));
     key.append(' ');
     key.append(ByteBufferUtil.bytesToHex(bb));
     metaColumn.putObject(
         key.toString(), new JsonObject().putString("clazz", params.getString("clazz")));
     state.putObject("metaColumn", metaColumn);
     event.reply(new JsonObject().putString(id.toString(), "OK").putObject("state", state));
   } else if (params.getField(Operations.RANGE_START) != null) {
     Object start = params.getField(Operations.RANGE_START);
     Object end = params.getField(Operations.RANGE_END);
     ByteBuffer sbuf = HandlerUtils.instance.byteBufferForObject(start);
     ByteBuffer ebuf = HandlerUtils.instance.byteBufferForObject(end);
     StringBuilder key = new StringBuilder();
     key.append(HandlerUtils.instance.determineKs(params, state, null));
     key.append(' ');
     key.append(HandlerUtils.instance.determineCf(params, state, null));
     key.append(' ');
     key.append(ByteBufferUtil.bytesToHex(sbuf));
     JsonObject value = new JsonObject();
     value.putString("clazz", params.getString("clazz"));
     value.putString("end", ByteBufferUtil.bytesToHex(ebuf));
     metaRanged.putObject(key.toString(), value);
     state.putObject("metaRanged", metaRanged);
     event.reply(new JsonObject().putString(id.toString(), "OK").putObject("state", state));
   } else {
     throw new RuntimeException("hit bottom this is bad ok");
   }
 }
Example #12
0
 /**
  * Deserializes a context from JSON.
  *
  * @param context The serialized context.
  * @return The deserialized context.
  */
 public static <T extends Context<T>> T deserialize(JsonObject context) {
   return deserialize(context.getString("uri"), context.getObject("context"));
 }