Example #1
0
File: Util.java Project: P-ful/PICO
 public static <T> JsonArray makeArrayToJsonArrayObject(final T[] array) {
   final JsonArray jsonArray = new JsonArray();
   for (final T v : array) {
     jsonArray.add(v);
   }
   return jsonArray;
 }
Example #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);
   }
 }
Example #3
0
  @RouteMapping(method = RouteMethod.GET)
  public Handler<RoutingContext> getAll() {
    return ctx -> {
      JDBCClient client = AppUtil.getJdbcClient(Vertx.vertx());

      client.getConnection(
          conn -> {
            if (conn.failed()) {
              LOGGER.error(conn.cause().getMessage(), conn.cause());
              ctx.fail(400);
            }

            SQLUtil.query(
                conn.result(),
                "select * from patient",
                rs -> {
                  JsonArray patients = new JsonArray();
                  for (JsonObject row : rs.getRows()) {
                    patients.add(row);
                  }

                  SQLUtil.close(conn.result());
                  ctx.response().end(patients.encode());
                });
          });
    };
  }
 @Override
 protected void add(JsonArray array, Object value) {
   if (value != null) {
     array.add(value);
   } else {
     array.addNull();
   }
 }
  public List<String> getFields() {
    List<String> fields = new LinkedList<>();

    JsonArray jsonFields = this.body.getJsonArray(FIELD_FIELDS);
    for (int i = 0; i < jsonFields.size(); i++) {
      fields.add(jsonFields.getString(i));
    }

    return fields;
  }
Example #6
0
  @Override
  public ValidationResult validate(JsonArray json) {

    for (int i = 0; i < json.size(); i++) {
      boolean equals = json.getValue(i).equals(jsonArray.getValue(i));
      if (!equals) {
        return invalidate(json);
      }
    }

    return null;
  }
Example #7
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);
   }
 }
Example #8
0
 @Test
 public void testPublishJsonArray() {
   JsonArray arr = new JsonArray();
   arr.add(TestUtils.randomUnicodeString(100))
       .add(TestUtils.randomInt())
       .add(TestUtils.randomBoolean());
   testPublish(
       arr,
       (received) -> {
         assertEquals(arr, received);
         assertFalse(arr == received); // Make sure it's copied
       });
 }
 private Handler<AsyncResult<Set<Character>>> createSetCharHandler(Message msg) {
   return res -> {
     if (res.failed()) {
       msg.fail(-1, res.cause().getMessage());
     } else {
       JsonArray arr = new JsonArray();
       for (Character chr : res.result()) {
         arr.add((int) chr);
       }
       msg.reply(arr);
     }
   };
 }
 private Handler<AsyncResult<List<Character>>> createListCharHandler(Message msg) {
   return res -> {
     if (res.failed()) {
       if (res.cause() instanceof ServiceException) {
         msg.reply(res.cause());
       } else {
         msg.reply(new ServiceException(-1, res.cause().getMessage()));
       }
     } else {
       JsonArray arr = new JsonArray();
       for (Character chr : res.result()) {
         arr.add((int) chr);
       }
       msg.reply(arr);
     }
   };
 }
Example #11
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());
   }
 }
 private void queryBudget(RoutingContext context, SQLConnection connection) {
   connection.query(
       "SELECT budget FROM preferences WHERE username = '******'",
       res2 -> {
         if (res2.succeeded()) {
           // System.out.println("Able to get budget query");
           ResultSet resultSet = res2.result();
           for (JsonArray line : res2.result().getResults()) {
             Budget = line.encode();
             Budget = Budget.replaceAll("[^a-zA-Z,' ']", "");
             // System.out.println("Budget: "+Budget);
           }
           queryHotels(context, connection);
         } else {
           log.error("Could not select budget from pref table table");
         }
       });
 }
 private void queryHotels(RoutingContext context, SQLConnection connection) {
   // Retrieve Hotels
   connection.query(
       "SELECT name FROM hotel ",
       res2 -> {
         if (res2.succeeded()) {
           // System.out.println("Able to get hotel query");
           for (JsonArray line : res2.result().getResults()) {
             Hotel[Hotelcounter] = line.encode();
             Hotel[Hotelcounter] = Hotel[Hotelcounter].replaceAll("[^a-zA-Z' ']", "");
             Hotelcounter++;
           }
           Hotelcounter = 0;
           queryHotelPricing(context, connection);
         } else {
           log.error("Could not select from the user table");
         }
       });
 }
 /*
  * (non-Javadoc)
  *
  * @see de.braintags.io.vertx.pojomapper.json.typehandler.handler.ArrayTypeHandler#intoStore(java.lang.Object,
  * de.braintags.io.vertx.pojomapper.mapping.IField, io.vertx.core.Handler)
  */
 @Override
 public void intoStore(
     Object javaValues, IField field, Handler<AsyncResult<ITypeHandlerResult>> handler) {
   super.intoStore(
       javaValues,
       field,
       result -> {
         if (result.failed()) {
           handler.handle(result);
           return;
         }
         JsonArray resultArray = (JsonArray) result.result().getResult();
         try {
           String arrayString = resultArray.encode();
           success(arrayString, handler);
         } catch (Exception e) {
           fail(e, handler);
         }
       });
 }
  @Test
  public void testDataJsonConsumption() throws Exception {
    JsonArray ginzburg = createJson("ginzburg", 1, 10);
    assertEquals(ginzburg.size(), 1);

    BasicSampleExtractor extractor = new BasicSampleExtractor();
    JsonObject jsonObject = ginzburg.getJsonObject(0);

    Optional<SampleData> sampleData = extractor.extractSample(jsonObject);
    assertTrue(sampleData.isPresent());
    assertEquals(sampleData.get().getPublishId(), "ginzburg");
    assertFalse(sampleData.get().getTime().isEmpty());

    double[] readings = extractor.extractReadings(jsonObject.getString(READINGS));
    assertEquals(readings.length, 10);

    DescriptiveStatistics stats = new DescriptiveStatistics(readings);
    double median = stats.getPercentile(50);
    assertEquals(sampleData.get().getMedian(), median);
  }
  @Test
  public void testWithJsonArray() {
    AtomicReference<JsonArray> result = new AtomicReference<>();
    Service service = Service.createProxy(consumerNode.get(), "my.service");
    TestDataObject data = new TestDataObject().setBool(true).setNumber(25).setString("vert.x");
    JsonArray array = new JsonArray();
    array.add("vert.x").add(data.toJson());

    service.methodWithJsonArray(
        array,
        ar -> {
          result.set(ar.result());
        });

    Awaitility.await().atMost(10, TimeUnit.SECONDS).until(() -> result.get() != null);
    TestDataObject out = new TestDataObject(result.get().getJsonObject(1));
    assertThat(array.getString(0)).isEqualToIgnoringCase("vert.x");
    assertThat(out.getNumber()).isEqualTo(25);
    assertThat(out.isBool()).isTrue();
    assertThat(out.getString()).isEqualTo("vert.x");
  }
  private void queryLocation(RoutingContext context, AsyncResult<SQLConnection> connectionRes) {
    // Get and set locations of user for future queries
    SQLConnection connection = connectionRes.result();
    // System.out.println("SELECT Location FROM preferences WHERE username = '******'");
    connection.query(
        "SELECT Location FROM preferences WHERE username = '******'",
        res2 -> {
          if (res2.succeeded()) {
            // System.out.println("Able to get query location");
            ResultSet resultSet = res2.result();
            for (JsonArray line : res2.result().getResults()) {
              Location = line.encode();
              Location = Location.replaceAll("[^a-zA-Z,' ']", "");
              // System.out.println("userLocation:"+Location);
            }
            context.session().put("location", Location);
            queryBudget(context, connection);

          } else {
            log.error("Could not select from the user table");
          }
        });
  }
  private void queryActivites(RoutingContext context, SQLConnection connection) {
    // Retrieve Activies
    connection.query(
        "SELECT name FROM activities",
        res5 -> {
          if (res5.succeeded()) {
            // System.out.println("Able to get activities query");
            for (JsonArray line3 : res5.result().getResults()) {
              // System.out.println("Activities: "+line3.encode());
              String ActTemp = line3.encode();
              ActTemp = ActTemp.replaceAll("[^a-zA-Z,' '0-9]", "");
              Act[Actcounter] = ActTemp;
              Actcounter++;
            }
            Actcounter = 0;
            context.session().put("activities", Act);

            context.next();
          } else {
            log.error("could not select form the activites table");
          }
        });
  }
  private void queryResturants(final RoutingContext context, final SQLConnection connection) {
    // Retrieve Resturants
    connection.query(
        "SELECT name FROM resturant",
        res4 -> {
          if (res4.succeeded()) {
            // System.out.println("Able to get resturant query");
            for (JsonArray line2 : res4.result().getResults()) {
              // System.out.println("resturant: "+line2.encode());
              String Resttemp = line2.encode();
              Resttemp = Resttemp.replaceAll("[^a-zA-Z,' '0-9]", "");
              Rest[Restcounter] = Resttemp;
              Restcounter++;
            }
            Restcounter = 0;
            context.session().put("resturants", Rest);

            queryActivites(context, connection);
          } else {
            log.error("could not select form resturant table");
          }
        });
  }
 private void queryHotelPricing(RoutingContext context, SQLConnection connection) {
   // Retrieve Hotel Pricing
   connection.query(
       "SELECT price FROM hotel",
       res3 -> {
         if (res3.succeeded()) {
           // System.out.println("Able to get hotel pricing");
           Hotelcounter = 0;
           for (JsonArray line1 : res3.result().getResults()) {
             String temp = Hotel[Hotelcounter];
             temp = temp.concat("   ($" + line1.encode() + ")");
             temp = temp.replaceAll("[^a-zA-Z,' '0-9$()]", "");
             Hotel[Hotelcounter] = temp;
             // System.out.println("hotel with price: " + Hotel[Hotelcounter]);
             Hotelcounter++;
           }
           context.session().put("hotels", Hotel);
           queryResturants(context, connection);
           Hotelcounter = 0;
         } else {
           log.error("could not select from user table above");
         }
       });
 }
  /** Iterate and deploy verticles */
  private void deployVerticle(final Message<JsonObject> event) {

    // iterate over all candidates to be deployed
    Set<String> candidates = this.workingCopy.fieldNames();

    // detach from underlying json
    Map<String, JsonObject> initiants = new HashMap<>();
    candidates.forEach(
        id -> {
          JsonObject info = this.workingCopy.getJsonObject(id);
          JsonArray dependsOn = info.getJsonArray("dependsOn");
          if (dependsOn != null && deployed.getList().containsAll(dependsOn.getList())
              || dependsOn == null
              || dependsOn.isEmpty()) {
            initiants.put(id, info);
          }
        });

    // remove the initiants
    initiants.keySet().forEach(id -> this.workingCopy.remove(id));

    // setup latch for the reply
    CountDownLatch latch = new CountDownLatch(initiants.size());
    if (initiants.isEmpty()) {
      event.reply(Boolean.TRUE);
      return;
    }

    // run over all dependencies
    initiants.forEach(
        (id, info) -> {

          // get the name of the verticle
          String name = info.getString("name");
          final JsonObject localConfig = new JsonObject();
          localConfig.mergeIn(globalConfig);
          localConfig.mergeIn(info.getJsonObject("config", new JsonObject()));

          Handler<AsyncResult<String>> handler =
              innerEvent -> {
                if (innerEvent.succeeded()) {
                  // add service to deployed-list
                  deployed.add(id);

                  // re-emit
                  vertx
                      .eventBus()
                      .send(
                          LOOPBACK,
                          workingCopy,
                          (AsyncResult<Message<Boolean>> recursiveReply) -> {
                            // always decrease latch
                            latch.countDown();

                            if (recursiveReply.succeeded() && recursiveReply.result().body()) {
                              if (latch.getCount() == 0) {
                                event.reply(recursiveReply.result().body() & Boolean.TRUE);
                              }
                            } else {
                              event.fail(500, this.getFailure(id, recursiveReply));
                            }
                          });

                } else {
                  event.fail(500, id + " >> " + innerEvent.cause().getMessage());
                }
              };

          LOG.log(Level.INFO, "Deploying: ''{0}''", new Object[] {id});
          DeploymentOptions deploymentOptions = new DeploymentOptions(info);
          vertx.deployVerticle(name, deploymentOptions.setConfig(localConfig), handler);
        });
  }
Example #22
0
  @Override
  public void onExecute(int what, JsonObject resultJO) {

    if (resultJO.containsKey("result_code") && resultJO.getInteger("result_code") == -1) {
      request.response().end(resultJO.toString());
      return;
    }
    JsonObject rs = new JsonObject();

    switch (what) {
      case Config.getSession:
        if (!resultJO.containsKey("result") || resultJO.getString("result") == null) {
          rs.put("result_code", -1);
          rs.put("result_msg", "로그인이 필요합니다.");
          request.response().end(rs.toString());
          break;
        }
        String user_info[] = resultJO.getString("result").split(",");
        String user_id = user_info[0];

        params.put("user_id", user_id);

        String query =
            String.format(
                "UPDATE app_user_list SET user_nick='%s' WHERE user_id='%s' and app_id='%s'",
                params.getString("user_nick"),
                params.getString("user_id"),
                params.getString("app_id"));
        insertCustomQuery(this, Config.setNickApp, query);

        break;

      case Config.setNickApp:
        String query2 =
            String.format(
                "UPDATE channel_user_list SET user_nick='%s' WHERE user_id='%s' and app_id='%s'",
                params.getString("user_nick"),
                params.getString("user_id"),
                params.getString("app_id"));
        insertCustomQuery(this, 100, query2);

        rs.put("result_code", 0);
        rs.put("result_msg", "닉네임을 변경하였습니다.");
        request.response().end(rs.toString());

        getRedis(this, Config.getRedis, "app:" + params.getString("user_id"));
        break;

      case Config.getRedis:
        JsonArray ja = new JsonArray(resultJO.getString("result"));
        for (int i = 0; i < ja.size(); i++) {
          if (params.getString("app_id").equals(ja.getJsonObject(i).getString("app_id"))) {
            JsonObject jo = ja.getJsonObject(i);
            jo.put("user_nick", params.getString("user_nick"));
            ja.remove(i);
            ja.add(jo);
          }
        }
        JsonObject table = new JsonObject();
        table.put("key", "app:" + Util.getUserId(params.getString("token")));
        table.put("value", ja.toString());
        setRedis(this, Config.setRedis, table);
        break;
    }
  }
 @Override
 protected void forEach(JsonArray array, Consumer<Object> arrayConsumer) {
   array.forEach(arrayConsumer);
 }
Example #24
0
File: Util.java Project: P-ful/PICO
 public static <T> JsonArray makeCollectionToJsonArrayObject(final Collection<T> collection) {
   final JsonArray jsonArray = new JsonArray();
   collection.forEach(e -> jsonArray.add(e));
   return jsonArray;
 }