private JsonObject setDefaults(JsonObject config) {
   config = config.copy();
   // Set the defaults
   if (config.getNumber("session_timeout") == null) {
     config.putNumber("session_timeout", 5l * 1000);
   }
   if (config.getBoolean("insert_JSESSIONID") == null) {
     config.putBoolean("insert_JSESSIONID", true);
   }
   if (config.getNumber("heartbeat_period") == null) {
     config.putNumber("heartbeat_period", 25l * 1000);
   }
   if (config.getNumber("max_bytes_streaming") == null) {
     config.putNumber("max_bytes_streaming", 128 * 1024);
   }
   if (config.getString("prefix") == null) {
     config.putString("prefix", "/");
   }
   if (config.getString("library_url") == null) {
     config.putString("library_url", "http://cdn.sockjs.org/sockjs-0.2.1.min.js");
   }
   if (config.getArray("disabled_transports") == null) {
     config.putArray("disabled_transports", new JsonArray());
   }
   return config;
 }
  @Override
  public void start() throws Exception {
    EventBus eb = vertx.eventBus();
    address = "vertx.memcached";

    JsonObject config = new JsonObject();
    config.putString("address", "vertx.memcached");
    config.putString("address", address);
    config.putString("memcached.servers", "localhost:11211");
    config.putNumber("memcached.timeout.ms", 1000);
    config.putNumber("memcached.tasks.check.ms", 10);
    config.putNumber("memcached.connections", 2);

    container.deployVerticle(
        "net.atarno.vertx.memcached.client.MemClient",
        config,
        1,
        new Handler<String>() {
          @Override
          public void handle(String s) {
            HashMap<String, Object> cacheCall = new HashMap<String, Object>();

            cacheCall.put("shouldReply", true);
            cacheCall.put("command", "set");
            cacheCall.put("key", "CCC");
            cacheCall.put("value", 100);
            /*
            build any other command here
             */
            act(cacheCall);
          }
        });
  }
Exemple #3
0
  public static void logSANodeValue(String nodeID, String nodeName, String nodeValue) {
    JsonObject jsonObj = new JsonObject();
    Long timestamp = System.currentTimeMillis();

    jsonObj.putNumber("time", timestamp);
    jsonObj.putString("type", "SANode");
    jsonObj.putString("nodeID", nodeID);
    jsonObj.putString("nodeName", nodeName);
    jsonObj.putObject("data", new JsonObject(nodeValue));
    jsonObj.putArray("users", AccountManager.getRegisteredUserIDList(nodeID));

    collLog.insert(jsonToDBObject(jsonObj));
  }
 @Test
 public void testWebServer() {
   JsonObject conf = new JsonObject();
   conf.putString("web_root", "src/test/resources")
       .putString("host", "localhost")
       .putNumber("port", 8181);
   container.deployModule(
       System.getProperty("vertx.modulename"),
       conf,
       new Handler<String>() {
         @Override
         public void handle(String deploymentID) {
           assertNotNull("deploymentID should not be null", deploymentID);
           HttpClient client = vertx.createHttpClient();
           client.setHost("localhost").setPort(8181);
           client.getNow(
               "/",
               new Handler<HttpClientResponse>() {
                 @Override
                 public void handle(HttpClientResponse resp) {
                   resp.bodyHandler(
                       new Handler<Buffer>() {
                         @Override
                         public void handle(Buffer body) {
                           assertTrue(body.toString().contains("Armadillos!"));
                           testComplete();
                         }
                       });
                 }
               });
         }
       });
 }
Exemple #5
0
  @Override
  public void get(String sid, final Handler<JsonObject> callback) {
    sid = this.prefix + sid;

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

    eventBus.send(
        redisAddress,
        redis,
        new Handler<Message<JsonObject>>() {
          @Override
          public void handle(Message<JsonObject> reply) {
            if ("ok".equals(reply.body().getString("status"))) {
              String value = reply.body().getString("value");
              if (value == null || "".equals(value)) {
                callback.handle(null);
                return;
              }
              callback.handle(new JsonObject(value));
            } else {
              callback.handle(null);
            }
          }
        });
  }
Exemple #6
0
  @SuppressWarnings("unused")
  private void getKeys(final Handler<JsonArray> next) {
    JsonObject redis = new JsonObject();
    redis.putString("command", "keys");
    redis.putArray("args", new JsonArray().add(prefix + "*"));

    eventBus.send(
        redisAddress,
        redis,
        new Handler<Message<JsonObject>>() {
          @Override
          public void handle(Message<JsonObject> message) {
            if (!"ok".equals(message.body().getString("status"))) {
              next.handle(new JsonArray());
            } else {
              JsonArray keys = message.body().getArray("value");

              JsonArray result = new JsonArray();
              int len = prefix.length();

              for (Object o : keys) {
                String key = (String) o;
                result.add(key.substring(len));
              }

              next.handle(result);
            }
          }
        });
  }
 private void deliverMessage(SockJSSocket sock, String address, Message message) {
   JsonObject envelope =
       new JsonObject().putString("address", address).putValue("body", message.body);
   if (message.replyAddress != null) {
     envelope.putString("replyAddress", message.replyAddress);
   }
   sock.writeBuffer(new Buffer(envelope.encode()));
 }
Exemple #8
0
 public void testEchoJson() {
   JsonObject obj = new JsonObject();
   obj.putString("foo", "bar");
   obj.putNumber("num", 12124);
   obj.putBoolean("x", true);
   obj.putBoolean("y", false);
   Handler<Message<JsonObject>> handler = echoHandler(obj);
   eb.send(ECHO_ADDRESS, obj, handler);
 }
  private void processSave(final Message<JsonObject> message) {
    System.out.println(message.body);

    JsonObject replyJson = new JsonObject();
    replyJson.putString("reply", "Saved data");
    replyJson.putNumber("id", System.currentTimeMillis());

    message.reply(replyJson);
  }
Exemple #10
0
  private static void writeHeaderFields(JsonObject result) {
    JsonObject train = findFirstTrain(result);

    if (train == null) {
      return;
    }

    result.putString("StopAreaName", train.getString("StopAreaName"));
    result.putNumber("SiteId", train.getInteger("SiteId"));
  }
Exemple #11
0
  public static void logControllerCommand(
      String request, int statusCode, String respond, String userID) {
    JsonObject jsonObj = new JsonObject();
    Long timestamp = System.currentTimeMillis();

    jsonObj.putNumber("time", timestamp);
    jsonObj.putString("type", "Controller");
    if (userID != null) jsonObj.putString("userID", userID);
    jsonObj.putObject("request", new JsonObject(request));

    JsonObject resJsonObj = new JsonObject();
    resJsonObj.putString("code", "" + statusCode);
    if (respond != null && respond.length() != 0) {
      if (respond.length() > 1024) resJsonObj.putString("data", "deprecated because too long");
      else resJsonObj.putObject("data", new JsonObject(respond));
    }

    jsonObj.putObject("resonse", resJsonObj);
    collLog.insert(jsonToDBObject(jsonObj));
  }
Exemple #12
0
  @Override
  public void all(final Handler<JsonArray> next) {
    JsonObject redis = new JsonObject();
    redis.putString("command", "keys");
    redis.putArray("args", new JsonArray().add(prefix + "*"));

    final JsonArray results = new JsonArray();

    eventBus.send(
        redisAddress,
        redis,
        new Handler<Message<JsonObject>>() {
          @Override
          public void handle(Message<JsonObject> message) {
            if (!"ok".equals(message.body().getString("status"))) {
              next.handle(null);
            } else {
              JsonArray keys = message.body().getArray("value");

              new AsyncIterator<Object>(keys.iterator()) {
                @Override
                public void handle(Object key) {
                  if (hasNext()) {
                    JsonObject redis = new JsonObject();
                    redis.putString("command", "get");
                    redis.putArray("args", new JsonArray().add(key));

                    eventBus.send(
                        redisAddress,
                        redis,
                        new Handler<Message<JsonObject>>() {
                          @Override
                          public void handle(Message<JsonObject> message) {
                            if (!"ok".equals(message.body().getString("status"))) {
                              next.handle(null);
                            } else {
                              String value = message.body().getString("value");
                              if (value != null) {
                                results.add(new JsonObject(value));
                              }
                              next();
                            }
                          }
                        });
                  } else {
                    next.handle(results);
                  }
                }
              };
            }
          }
        });
  }
Exemple #13
0
  private static void setUniqueKeysOn(JsonArray trains) {
    if (trains == null) {
      return;
    }

    stream(trains.spliterator(), false)
        .forEach(
            o -> {
              JsonObject train = (JsonObject) o;
              Integer siteId = train.getInteger("SiteId");
              if (siteId != null) {
                train.putString(
                    "Key",
                    Keys.key(
                        siteId,
                        "" + train.getString("TimeTabledDateTime"),
                        train.getInteger("JourneyDirection")));
              } else {
                train.putString(
                    "Key",
                    Keys.key(
                        "" + train.getString("TimeTabledDateTime"),
                        train.getInteger("JourneyDirection")));
              }
            });

    List<String> keyList =
        stream(trains.spliterator(), false)
            .map(o -> ((JsonObject) o).getString("Key"))
            .collect(toList());

    Set<String> keySet =
        stream(trains.spliterator(), false)
            .map(o -> ((JsonObject) o).getString("Key"))
            .collect(toSet());

    if (keyList.size() != keySet.size()) {
      throw new IllegalStateException("duplicate keys in " + keyList);
    }
  }
Exemple #14
0
 public void azzert(boolean result, String message) {
   JsonObject jsonObject =
       new JsonObject()
           .putString(EventFields.TYPE_FIELD, EventFields.ASSERT_EVENT)
           .putString(
               EventFields.ASSERT_RESULT_FIELD,
               result
                   ? EventFields.ASSERT_RESULT_VALUE_PASS
                   : EventFields.ASSERT_RESULT_VALUE_FAIL);
   if (message != null) {
     jsonObject.putString(EventFields.ASSERT_MESSAGE_FIELD, message);
   }
   if (!result) {
     jsonObject.putString(EventFields.ASSERT_STACKTRACE_FIELD, getStackTrace(new Exception()));
   }
   sendMessage(jsonObject);
   if (!result) {
     // We throw a RTE not an AssertFailedError since Rhino cannot catch errors in
     // test_utils.js
     throw new RuntimeException("Assertion failed: " + message);
   }
 }
  public void act(HashMap<String, Object> cmd) {
    if (cmd == null) return;

    JsonObject notif = new JsonObject();

    for (String key : cmd.keySet()) {
      Object value = cmd.get(key);

      if (value != null) {
        if (value instanceof byte[]) notif.putBinary(key, (byte[]) value);
        else if (value instanceof Boolean) notif.putBoolean(key, (Boolean) value);
        else if (value instanceof Number) notif.putNumber(key, (Number) value);
        else if (value instanceof String) notif.putString(key, (String) value);
        else if (value instanceof JsonArray) notif.putArray(key, (JsonArray) value);
      }
    }
    System.out.println("sent: \n" + notif.encode());
    push(notif);
  }
Exemple #16
0
  @Override
  public void length(final Handler<Integer> next) {
    JsonObject redis = new JsonObject();
    redis.putString("command", "keys");
    redis.putArray("args", new JsonArray().add(prefix + "*"));

    eventBus.send(
        redisAddress,
        redis,
        new Handler<Message<JsonObject>>() {
          @Override
          public void handle(Message<JsonObject> message) {
            if (!"ok".equals(message.body().getString("status"))) {
              next.handle(0);
            } else {
              JsonArray keys = message.body().getArray("value");
              next.handle(keys.size());
            }
          }
        });
  }
Exemple #17
0
  @Override
  public void destroy(String sid, final Handler<Object> callback) {
    sid = this.prefix + sid;

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

    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"));
            }
          }
        });
  }
Exemple #18
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"));
            }
          }
        });
  }
Exemple #19
0
 public void addAttachment() {
   JsonArray functionalAttachment = struct.getArray("functionalAttachment");
   if (functionalAttachment != null
       && functionalAttachment.size() > 0
       && !externalId.equals(functionalAttachment.get(0))) {
     JsonObject params = new JsonObject().putString("externalId", externalId);
     String query;
     if (functionalAttachment.size() == 1) {
       query =
           "MATCH (s:Structure { externalId : {externalId}}), "
               + "(ps:Structure { externalId : {functionalAttachment}}) "
               + "CREATE UNIQUE s-[:HAS_ATTACHMENT]->ps";
       params.putString("functionalAttachment", (String) functionalAttachment.get(0));
     } else {
       query =
           "MATCH (s:Structure { externalId : {externalId}}), (ps:Structure) "
               + "WHERE ps.externalId IN {functionalAttachment} "
               + "CREATE UNIQUE s-[:HAS_ATTACHMENT]->ps";
       params.putArray("functionalAttachment", functionalAttachment);
     }
     getTransaction().add(query, params);
   }
 }
 @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");
   }
 }
Exemple #21
0
 public ErrorMessage(String error) {
   body.putString("status", "error").putString("message", error);
 }
  /**
   * Notify SXA Plugin-CC that a new CPE has been discovered.
   *
   * @param cpe
   */
  public static void sendCpeDiscoveryToPluginCc(final Cpe cpe) {
    /** Build request payload */
    JsonObject payload = new JsonObject();
    payload.putString("id", cpe.getCpeKey());
    payload.putString("ip", cpe.deviceId.ipAddress == null ? "" : cpe.deviceId.ipAddress);
    payload.putString("mac", cpe.deviceId.macAddress == null ? "" : cpe.deviceId.macAddress);
    payload.putString("ser-no", cpe.deviceId.sn);
    payload.putString("model", cpe.deviceId.modelName == null ? "" : cpe.deviceId.modelName);
    payload.putString("mfr", cpe.deviceId.manufacturer);
    payload.putString("sw-ver", cpe.deviceId.swVersion == null ? "" : cpe.deviceId.swVersion);
    payload.putString(
        "reg-id", cpe.deviceId.registrationId == null ? "" : cpe.deviceId.registrationId);
    payload.putString(
        "prod-class", cpe.deviceId.productClass == null ? "" : cpe.deviceId.productClass);
    payload.putString(
        "prov-code", cpe.getParamValue("InternetGatewayDevice.DeviceInfo.ProvisioningCode"));
    payload.putString(
        "persistent-data", cpe.getParamValue("InternetGatewayDevice.DeviceConfig.PersistentData"));
    payload.putNumber("last-comm-time", cpe.informTime / 1000);

    // Send it
    sendRequest(
        CWMP_PLUGIN_CC_MODULE_NAME,
        HttpMethod.POST,
        CPE_DISCOVERY_URL_PATH,
        cpe.deviceId.orgId, // use "orgId" as username
        PASSWORD,
        payload.encode(),
        new Handler<HttpClientResponse>() {
          @Override
          public void handle(HttpClientResponse response) {
            /** Simply log the response */
            if (response.statusCode() == HttpResponseStatus.OK.code()
                || response.statusCode() == HttpResponseStatus.NO_CONTENT.code()) {
              log.info(
                  cpe.getCpeKey()
                      + ": Successfully sent CPE discovery notification to SXA Plugin-CC.");
            } else {
              log.error(
                  cpe.getCpeKey()
                      + ": Failed to send CPE discovery notification to SXA Plugin-CC!"
                      + " HTTP Status "
                      + response.statusCode()
                      + " "
                      + response.statusMessage());
            }
          }
        },
        new Handler<Throwable>() {
          @Override
          public void handle(Throwable exception) {
            log.error(
                cpe.getCpeKey()
                    + ": Failed to send CPE discovery notification to SXA Plugin-CC due to"
                    + " exception "
                    + exception.getMessage()
                    + "!");
          }
        });
  }