/*
   * TotalDebt = MarginDebt + DfDebt+dfOustandingDebt +accumulatedDepositFee + overdueDepositFee
   */
  public Optional<JsonObject> parse(String json) {
    try {
      final JsonObject body = new JsonObject(json);
      final String type = body.getString(ATDAccountMastKey.MSG_TYPE);
      if (!isATDAccountMastMessage(type)) return Optional.empty();
      System.out.println(body);
      final JsonObject jsonData = body.getJsonObject("data");
      if (jsonData == null) return Optional.empty();
      JsonObject result = new JsonObject();
      result
          .put(ATDAccountMastKey.ACCOUNT, jsonData.getString(ATDAccountMastKey.ACCOUNT))
          .put(
              ATDAccountMastKey.RECEIVING,
              string2Double(jsonData.getString(ATDAccountMastKey.RECEIVING)))
          .put(
              ATDAccountMastKey.BALANCE,
              string2Double(jsonData.getString(ATDAccountMastKey.BALANCE)))
          .put(
              ATDAccountMastKey.TOTALDEBT,
              string2Double(jsonData.getString(ATDAccountMastKey.TOTALDEBT)));
      return Optional.of(result);

    } catch (DecodeException e) {
      LOGGER.error("Cannot decode message to json: ", e);
    }
    return Optional.empty();
  }
示例#2
0
 // Handle failover
 private void checkFailover(String failedNodeID, JsonObject theHAInfo) {
   try {
     JsonArray deployments = theHAInfo.getJsonArray("verticles");
     String group = theHAInfo.getString("group");
     String chosen = chooseHashedNode(group, failedNodeID.hashCode());
     if (chosen != null && chosen.equals(this.nodeID)) {
       if (deployments != null && deployments.size() != 0) {
         log.info(
             "node"
                 + nodeID
                 + " says: Node "
                 + failedNodeID
                 + " has failed. This node will deploy "
                 + deployments.size()
                 + " deploymentIDs from that node.");
         for (Object obj : deployments) {
           JsonObject app = (JsonObject) obj;
           processFailover(app);
         }
       }
       // Failover is complete! We can now remove the failed node from the cluster map
       clusterMap.remove(failedNodeID);
       callFailoverCompleteHandler(failedNodeID, theHAInfo, true);
     }
   } catch (Throwable t) {
     log.error("Failed to handle failover", t);
     callFailoverCompleteHandler(failedNodeID, theHAInfo, false);
   }
 }
 public JsonObject toJson() {
   JsonObject ret = new JsonObject();
   if (value != null) {
     ret.put("value", value);
   }
   return ret;
 }
示例#4
0
 // Check if there is a quorum for our group
 private void checkQuorum() {
   if (quorumSize == 0) {
     this.attainedQuorum = true;
   } else {
     List<String> nodes = clusterManager.getNodes();
     int count = 0;
     for (String node : nodes) {
       String json = clusterMap.get(node);
       if (json != null) {
         JsonObject clusterInfo = new JsonObject(json);
         String group = clusterInfo.getString("group");
         if (group.equals(this.group)) {
           count++;
         }
       }
     }
     boolean attained = count >= quorumSize;
     if (!attainedQuorum && attained) {
       // A quorum has been attained so we can deploy any currently undeployed HA deploymentIDs
       log.info(
           "A quorum has been obtained. Any deploymentIDs waiting on a quorum will now be deployed");
       this.attainedQuorum = true;
     } else if (attainedQuorum && !attained) {
       // We had a quorum but we lost it - we must undeploy any HA deploymentIDs
       log.info(
           "There is no longer a quorum. Any HA deploymentIDs will be undeployed until a quorum is re-attained");
       this.attainedQuorum = false;
     }
   }
 }
  @Override
  public void start(final Future<Void> startFuture) throws Exception {
    LOGGER.info("starting {0}..", identifier());

    // start the HELLO slacker protocol
    final JsonObject helloMessage =
        new JsonObject().put("i", identifier()).put("d", description()).put("v", version());
    vertx
        .eventBus()
        .send(
            "reg.slacker-server",
            helloMessage,
            result -> {
              if (result.succeeded() && JsonObject.class.isInstance(result.result().body())) {
                final JsonObject response = (JsonObject) result.result().body();
                if (response.containsKey("a")) {
                  // everything went smoothly - register the listener and complete the startup
                  registerListener(response.getString("a"));
                  LOGGER.info("successfully registered {0} executor", identifier());
                  startFuture.complete();
                } else {
                  failStart(startFuture, "no address to bind was received");
                }
              } else {
                // something unexpected happened
                failStart(
                    startFuture,
                    Optional.ofNullable(result.cause())
                        .map(Throwable::getMessage)
                        .orElse("invalid response"));
              }
            });
  }
示例#6
0
  @Override
  public void handle(SockJSSocket sockJSSocket) {
    final String sessionId = sockJSSocket.webSession().id();
    final MessageConsumer<String> sessionConsumer = consumers.get(sessionId);

    if (sessionConsumer == null) {
      final MessageConsumer<String> consumer =
          eventStore.consumer(
              UpdateOrdrEvent.class,
              message -> {
                final String id = sockJSSocket.webSession().get("id").toString();
                JsonObject dashboardJson = new JsonObject(message.body());
                if (dashboardJson.getString("id").equals(id)) {
                  sockJSSocket.write(Buffer.buffer(message.body()));
                }
              });
      log.info("bound WS handler to sessionId {}", sessionId);
      consumers.put(sessionId, consumer);
      log.info("registered consumers {}", consumers.size());
    }

    sockJSSocket.endHandler(
        aVoid -> {
          final MessageConsumer<String> consumer = consumers.get(sessionId);
          consumer.unregister();
          consumers.remove(sessionId);
          log.info("unregistered consumer for sessionId {}", sessionId);
        });
  }
 @Override
 protected BsonType getBsonType(Object value) {
   BsonType type = super.getBsonType(value);
   if (type == BsonType.DOCUMENT) {
     JsonObject obj = (JsonObject) value;
     if (obj.containsKey(DATE_FIELD)) {
       return BsonType.DATE_TIME;
     }
     // not supported yet
     /*else if (obj.containsKey("$binary")) {
       return BsonType.BINARY;
     } else if (obj.containsKey("$maxKey")) {
       return BsonType.MAX_KEY;
     } else if (obj.containsKey("$minKey")) {
       return BsonType.MIN_KEY;
     } else if (obj.containsKey("$oid")) {
       return BsonType.OBJECT_ID;
     } else if (obj.containsKey("$regex")) {
       return BsonType.REGULAR_EXPRESSION;
     } else if (obj.containsKey("$symbol")) {
       return BsonType.SYMBOL;
     } else if (obj.containsKey("$timestamp")) {
       return BsonType.TIMESTAMP;
     } else if (obj.containsKey("$undefined")) {
       return BsonType.UNDEFINED;
     } else if (obj.containsKey("$numberLong")) {
       return BsonType.INT64;
     } else if (obj.containsKey("$code")) {
       return JAVASCRIPT or JAVASCRIPT_WITH_SCOPE;
     } */
   }
   return type;
 }
示例#8
0
 @CodeTranslate
 public void putBooleanFromIdentifier() throws Exception {
   JsonObject obj = new JsonObject();
   obj.put("_true", true);
   obj.put("_false", false);
   JsonTest.o = JsonConverter.toJsonObject(obj);
 }
示例#9
0
  default <T extends Throwable> void error(
      RoutingContext context, HttpResponseStatus code, String message, T object) {
    HttpServerResponse response = context.response().setStatusCode(code.code());
    response.putHeader("X-API-Gateway-Error", "true");

    if (message == null) {
      response.setStatusMessage(code.reasonPhrase());
    } else {
      response.setStatusMessage(message);
    }

    if (object != null) {
      JsonObject errorResponse =
          new JsonObject()
              .put("errorType", object.getClass().getSimpleName())
              .put("message", object.getMessage());

      response
          .setChunked(true)
          .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
          .end(errorResponse.toString(), "UTF-8");
    } else {
      response.end();
    }
  }
示例#10
0
 public <T extends PersistableEvent<? extends SourcedEvent>> Observable<T> insert(final T event) {
   final JsonObject document = new JsonObject();
   document.put("_id", event.getId());
   document.put("dateCreated", new Date().getTime());
   document.put("clazz", event.getClazz().getCanonicalName());
   document.put("payload", new JsonObject(event.getPayload()));
   return mongoClient.insertObservable("events", document).flatMap(s -> Observable.just(event));
 }
 @Override
 protected JsonObject createAuthServiceConfig() {
   JsonObject js = new JsonObject();
   js.put(
       MongoAuth.PROPERTY_COLLECTION_NAME,
       createCollectionName(MongoAuth.DEFAULT_COLLECTION_NAME));
   js.put(MongoAuth.PROPERTY_SALT_STYLE, HashSaltStyle.EXTERNAL);
   return js;
 }
 @Override
 protected Object readDateTime(BsonReader reader, DecoderContext ctx) {
   final JsonObject result = new JsonObject();
   result.put(
       DATE_FIELD,
       OffsetDateTime.ofInstant(Instant.ofEpochMilli(reader.readDateTime()), ZoneOffset.UTC)
           .format(ISO_OFFSET_DATE_TIME));
   return result;
 }
 private static void linkConstructor(StringBuilder allLinks, List<JsonObject> jsonObjects) {
   for (JsonObject joo : jsonObjects) {
     allLinks
         .append("<a href = \"http://localhost:8989/")
         .append(joo.getString("id"))
         .append("\">")
         .append(joo.getString("id"))
         .append("<br>");
   }
 }
 private static JsonObject makeExoJson(String line) {
   JsonObject jsonObject = new JsonObject();
   Path path = Paths.get(line);
   if (Files.exists(path)) {
     jsonObject.put("full", line);
     String id = path.getFileName().toString();
     id = id.substring(0, id.indexOf('.'));
     jsonObject.put("id", id);
   }
   return jsonObject;
 }
示例#15
0
  private PersistableEvent<? extends SourcedEvent> makePersistableEventFromJson(
      final JsonObject event) {
    Class<? extends SourcedEvent> clazz = null;
    try {
      //noinspection unchecked
      clazz = (Class<? extends SourcedEvent>) Class.forName(event.getString("clazz"));
    } catch (final ClassNotFoundException e) {
      log.warn(e.getMessage());
    }

    return new PersistableEvent<>(clazz, event.getJsonObject("payload").encode());
  }
示例#16
0
 @Test
 public void testPublishJsonObject() {
   JsonObject obj = new JsonObject();
   obj.put(TestUtils.randomUnicodeString(100), TestUtils.randomUnicodeString(100))
       .put(TestUtils.randomUnicodeString(100), TestUtils.randomInt());
   testPublish(
       obj,
       (received) -> {
         assertEquals(obj, received);
         assertFalse(obj == received); // Make sure it's copied
       });
 }
示例#17
0
 // Add some information on a deployment in the cluster so other nodes know about it
 private void addToHA(
     String deploymentID, String verticleName, DeploymentOptions deploymentOptions) {
   String encoded;
   synchronized (haInfo) {
     JsonObject verticleConf = new JsonObject().put("dep_id", deploymentID);
     verticleConf.put("verticle_name", verticleName);
     verticleConf.put("options", deploymentOptions.toJson());
     JsonArray haMods = haInfo.getJsonArray("verticles");
     haMods.add(verticleConf);
     encoded = haInfo.encode();
     clusterMap.put(nodeID, encoded);
   }
 }
示例#18
0
  private JsonObject buildLangTextJson(Map<String, String> langMap) {

    JsonObject jsonObj = new JsonObject();

    if (langMap != null) {

      langMap.forEach(
          (key, value) -> {
            jsonObj.put(key, value);
          });
    }

    return jsonObj;
  }
 @Override
 public JsonObject transform(JsonObject json) {
   if (json == null) {
     return null;
   }
   converters.forEach(
       (k, v) -> {
         Object value = json.getValue(k);
         if (value != null) {
           json.put(k, v.apply(value));
         }
       });
   return json;
 }
 @Test
 public void testMasters() {
   redisSentinel.masters(
       reply -> {
         assertTrue(reply.succeeded());
         assertEquals(1, reply.result().size());
         JsonObject result = JsonUtils.convertToJsonObject(reply.result().getJsonArray(0));
         assertEquals(MASTER_NAME, result.getString("name"));
         assertEquals(host, result.getString("ip"));
         assertEquals(String.valueOf(DEFAULT_PORT), result.getString("port"));
         testComplete();
       });
   await();
 }
示例#21
0
  @Override
  public void execute(HttpServerRequest request) {
    init(request);

    wrapDAO.getSession(this, params.getString("token"));

    if (params.isEmpty() || !checkValidation(params)) {

      JsonObject rs = new JsonObject();
      rs.put("result_code", -1);
      rs.put("result_msg", "params error");
      request.response().end(rs.toString());
    }
  }
  /**
   * Convert to JSON
   *
   * @return the JSON
   */
  public JsonObject toJson() {
    JsonObject mongoClientUpdateResultJson = new JsonObject();

    if (docMatched != DEFAULT_DOCMATCHED) {
      mongoClientUpdateResultJson.put(DOC_MATCHED, docMatched);
    }
    if (docUpsertedId != null) {
      mongoClientUpdateResultJson.put(UPSERTED_ID, docUpsertedId);
    }
    if (docModified != DEFAULT_DOCMODIFIED) {
      mongoClientUpdateResultJson.put(DOC_MODIFIED, docModified);
    }

    return mongoClientUpdateResultJson;
  }
 @Override
 protected void forEach(JsonObject object, BiConsumer<String, Object> objectConsumer) {
   object.forEach(
       entry -> {
         objectConsumer.accept(entry.getKey(), entry.getValue());
       });
 }
  private ExecutionResult<MessageResponse> validateAndInitialize() {
    if (message == null || !(message.body() instanceof JsonObject)) {
      LOGGER.error("Invalid message received, either null or body of message is not JsonObject ");
      return new ExecutionResult<>(
          MessageResponseFactory.createInvalidRequestResponse(),
          ExecutionResult.ExecutionStatus.FAILED);
    }

    userId = ((JsonObject) message.body()).getString(MessageConstants.MSG_USER_ID);
    if (!validateUser(userId)) {
      LOGGER.error("Invalid user id passed. Not authorized.");
      return new ExecutionResult<>(
          MessageResponseFactory.createForbiddenResponse(), ExecutionResult.ExecutionStatus.FAILED);
    }

    prefs = ((JsonObject) message.body()).getJsonObject(MessageConstants.MSG_KEY_PREFS);
    request = ((JsonObject) message.body()).getJsonObject(MessageConstants.MSG_HTTP_BODY);

    if (prefs == null || prefs.isEmpty()) {
      LOGGER.error("Invalid preferences obtained, probably not authorized properly");
      return new ExecutionResult<>(
          MessageResponseFactory.createForbiddenResponse(), ExecutionResult.ExecutionStatus.FAILED);
    }

    if (request == null) {
      LOGGER.error("Invalid JSON payload on Message Bus");
      return new ExecutionResult<>(
          MessageResponseFactory.createInvalidRequestResponse(),
          ExecutionResult.ExecutionStatus.FAILED);
    }

    // All is well, continue processing
    return new ExecutionResult<>(null, ExecutionResult.ExecutionStatus.CONTINUE_PROCESSING);
  }
 public JsonObject toJson() {
   JsonObject crit = new JsonObject();
   findBy
       .getStrictRestrictions()
       .forEach(
           (name, value) -> {
             crit.put(name, value);
           });
   findBy
       .getInRestrictions()
       .forEach(
           (name, values) -> {
             crit.put(name, new JsonObject().put("$in", new JsonArray(values)));
           });
   return crit;
 }
示例#26
0
 // Process the failover of a deployment
 private void processFailover(JsonObject failedVerticle) {
   if (failDuringFailover) {
     throw new VertxException("Oops!");
   }
   // This method must block until the failover is complete - i.e. the verticle is successfully
   // redeployed
   final String verticleName = failedVerticle.getString("verticle_name");
   final CountDownLatch latch = new CountDownLatch(1);
   final AtomicReference<Throwable> err = new AtomicReference<>();
   // Now deploy this verticle on this node
   ContextImpl ctx = vertx.getContext();
   if (ctx != null) {
     // We could be on main thread in which case we don't want to overwrite tccl
     ContextImpl.setContext(null);
   }
   JsonObject options = failedVerticle.getJsonObject("options");
   try {
     doDeployVerticle(
         verticleName,
         new DeploymentOptions(options),
         result -> {
           if (result.succeeded()) {
             log.info("Successfully redeployed verticle " + verticleName + " after failover");
           } else {
             log.error("Failed to redeploy verticle after failover", result.cause());
             err.set(result.cause());
           }
           latch.countDown();
           Throwable t = err.get();
           if (t != null) {
             throw new VertxException(t);
           }
         });
   } finally {
     if (ctx != null) {
       ContextImpl.setContext(ctx);
     }
   }
   try {
     if (!latch.await(120, TimeUnit.SECONDS)) {
       throw new VertxException("Timed out waiting for redeploy on failover");
     }
   } catch (InterruptedException e) {
     throw new IllegalStateException(e);
   }
 }
 public void handle(Message<JsonObject> msg) {
   try {
     JsonObject json = msg.body();
     String action = msg.headers().get("action");
     if (action == null) {
       throw new IllegalStateException("action not specified");
     }
     accessed();
     switch (action) {
       case "checkin":
         {
           service.checkin(
               (java.lang.String) json.getValue("name"),
               json.getValue("lat") == null ? null : (json.getDouble("lat").doubleValue()),
               json.getValue("lon") == null ? null : (json.getDouble("lon").doubleValue()),
               createHandler(msg));
           break;
         }
       case "getCheckins":
         {
           service.getCheckins(
               res -> {
                 if (res.failed()) {
                   msg.fail(-1, res.cause().getMessage());
                 } else {
                   msg.reply(
                       new JsonArray(
                           res.result()
                               .stream()
                               .map(Checkin::toJson)
                               .collect(Collectors.toList())));
                 }
               });
           break;
         }
       default:
         {
           throw new IllegalStateException("Invalid action: " + action);
         }
     }
   } catch (Throwable t) {
     msg.fail(-1, t.getMessage());
     throw t;
   }
 }
示例#28
0
 public static void toJson(Place obj, JsonObject json) {
   if (obj.getAddress() != null) {
     json.put("address", obj.getAddress());
   }
   if (obj.getCategory() != null) {
     json.put("category", obj.getCategory());
   }
   if (obj.getDescription() != null) {
     json.put("description", obj.getDescription());
   }
   json.put("latitude", obj.getLatitude());
   json.put("longitude", obj.getLongitude());
   if (obj.getName() != null) {
     json.put("name", obj.getName());
   }
   if (obj.getTags() != null) {
     json.put(
         "tags",
         new JsonArray(
             obj.getTags()
                 .stream()
                 .map(item -> item)
                 .collect(java.util.stream.Collectors.toList())));
   }
 }
  public void start(Future<Void> startFuture) {

    logger.info("[PacketDividerController-start()] START! > " + this.name);

    EventBus eb = vertx.eventBus();
    PacketAnalyzer pa = new PacketAnalyzer();

    eb.consumer(
        "PD_Trap" + remoteAddr,
        message -> {
          JsonObject jo = (JsonObject) message.body();
          String recvMsg = jo.getString("recvPacket");

          logger.debug(name_log + "PD_Trap, RECV[" + recvMsg.length() + "]> \n" + recvMsg);

          JsonObject paJo = new JsonObject();
          paJo = pa.reqAnalyzePacket(recvMsg);

          logger.debug("paJo.size(): " + paJo.size());

          // RESPONSE, to Target
          if (!paJo.isEmpty()) {
            logger.debug("nextCmd: " + paJo.getString("nextCmd"));

            String sendPacket = paJo.getString("sendPacket");
            logger.debug("[sendData()] sendPacket: " + sendPacket);
            logger.debug(name_log + "PD_Trap, SEND> " + sendPacket);
            eb.send(remoteAddr + "Trap_ACK", sendPacket);
          } else {
            logger.debug(name_log + "PD_Trap, SEND> " + "NACK");
            String sendPacket = "NACK";
            eb.send(remoteAddr + "Trap_NACK", sendPacket);
          }
        });
  }
示例#30
0
 // Remove the information on the deployment from the cluster - this is called when an HA module is
 // undeployed
 public void removeFromHA(String depID) {
   Deployment dep = deploymentManager.getDeployment(depID);
   if (dep == null || !dep.deploymentOptions().isHa()) {
     return;
   }
   synchronized (haInfo) {
     JsonArray haMods = haInfo.getJsonArray("verticles");
     Iterator<Object> iter = haMods.iterator();
     while (iter.hasNext()) {
       Object obj = iter.next();
       JsonObject mod = (JsonObject) obj;
       if (mod.getString("dep_id").equals(depID)) {
         iter.remove();
       }
     }
     clusterMap.put(nodeID, haInfo.encode());
   }
 }