private String chooseHashedNode(String group, int hashCode) { List<String> nodes = clusterManager.getNodes(); ArrayList<String> matchingMembers = new ArrayList<>(); for (String node: nodes) { String sclusterInfo = clusterMap.get(node); if (sclusterInfo != null) { JsonObject clusterInfo = new JsonObject(sclusterInfo); String memberGroup = clusterInfo.getString("group"); if (group == null || group.equals(memberGroup)) { matchingMembers.add(node); } } } if (!matchingMembers.isEmpty()) { // Hashcodes can be -ve so make it positive long absHash = (long)hashCode + Integer.MAX_VALUE; long lpos = absHash % matchingMembers.size(); return matchingMembers.get((int)lpos); } else { return null; } } }
@Override public void process(JsonObject document, Handler<AsyncResult<JsonObject>> resultHandler) { System.out.println("Processing..."); JsonObject result = document.copy(); if (!document.containsKey("name")) { resultHandler.handle(ServiceException.fail(NO_NAME_ERROR, "No name in the document")); } else if (document.getString("name").isEmpty() || document.getString("name").equalsIgnoreCase("bad")) { resultHandler.handle(ServiceException.fail(BAD_NAME_ERROR, "Bad name in the document: " + document.getString("name"), new JsonObject().put("name", document.getString("name")))); } else { result.put("approved", true); resultHandler.handle(Future.succeededFuture(result)); } }
/** * Create options from JSON * * @param json the JSON */ public RequestOptions(JsonObject json) { setHost(json.getString("host", DEFAULT_HOST)); setPort(json.getInteger("port", DEFAULT_PORT)); setSsl(json.getBoolean("ssl", DEFAULT_SSL)); setURI(json.getString("uri", DEFAULT_URI)); }
@Test public void testCreateFromMapNestedJsonObject() { Map<String, Object> map = new HashMap<>(); JsonObject nestedObj = new JsonObject().put("foo", "bar"); map.put("nested", nestedObj); JsonObject obj = new JsonObject(map); JsonObject nestedRetrieved = obj.getJsonObject("nested"); assertEquals("bar", nestedRetrieved.getString("foo")); }
@Test public void testStartingApplicationInRedeployModeWithFileConf2() throws IOException { cli.dispatch(new Launcher(), new String[]{"run", HttpTestVerticle.class.getName(), "--redeploy=**" + File.separator + "*.txt", "--launcher-class=" + Launcher.class.getName(), "--conf=" + new File("src/test/resources/conf.json").getAbsolutePath() }); assertWaitUntil(() -> { try { return RunCommandTest.getHttpCode() == 200; } catch (IOException e) { return false; } }); JsonObject conf = RunCommandTest.getContent().getJsonObject("conf"); assertThat(conf).isNotNull().isNotEmpty(); assertThat(conf.getString("name")).isEqualTo("vertx"); }
@Test public void testPutCharSequence() { assertSame(jsonObject, jsonObject.put("foo", new StringBuilder("bar"))); assertEquals("bar", jsonObject.getString("foo")); assertEquals("bar", jsonObject.getString("foo", "def")); jsonObject.put("quux",new StringBuilder("wibble")); assertEquals("wibble", jsonObject.getString("quux")); assertEquals("bar", jsonObject.getString("foo")); jsonObject.put("foo", new StringBuilder("blah")); assertEquals("blah", jsonObject.getString("foo")); jsonObject.put("foo", (CharSequence) null); assertTrue(jsonObject.containsKey("foo")); try { jsonObject.put(null, (CharSequence)"blah"); fail(); } catch (NullPointerException e) { // OK } }
@Test public void testStartListStopWithJVMOptions() throws InterruptedException, IOException { record(); cli.dispatch(new String[]{"start", "run", HttpTestVerticle.class.getName(), "--launcher-class", Launcher.class.getName(), "--java-opts=-Dfoo=bar -Dbaz=bar", "--redirect-output"}); waitForStartup(); assertThat(output.toString()).contains("Starting vert.x application"); JsonObject content = RunCommandTest.getContent(); assertThat(content.getString("foo")).isEqualToIgnoringCase("bar"); assertThat(content.getString("baz")).isEqualToIgnoringCase("bar"); output.reset(); cli.dispatch(new String[]{"list"}); assertThat(output.toString()).hasLineCount(2); // Extract id. String[] lines = output.toString().split(System.lineSeparator()); String id = lines[1].trim().substring(0, lines[1].trim().indexOf("\t")); output.reset(); // pass --redeploy to not call system.exit cli.dispatch(new String[]{"stop", id, "--redeploy"}); assertThat(output.toString()) .contains("Stopping vert.x application '" + id + "'") .contains("Application '" + id + "' terminated with status 0"); waitForShutdown(); assertWaitUntil(() -> { output.reset(); cli.dispatch(new String[]{"list"}); return !output.toString().contains(id); }); assertThat(output.toString()).hasLineCount(2).contains("No vert.x application found"); }
protected SQLClient createDbClient(JsonObject config) { return JDBCClient.createNonShared(vertx, new JsonObject() .put("url", config.getString("db_url", "jdbc:hsqldb:file:db/wiki")) .put("driver_class", config.getString("db_driver", "org.hsqldb.jdbcDriver")) .put("max_pool_size", config.getInteger("db_max_pool_size", 30))); }
/** * Initialise the fields of this instance from the specified JSON * * @param json the JSON */ public void fromJson(JsonObject json) { this.config = json.getJsonObject("config"); this.worker = json.getBoolean("worker", DEFAULT_WORKER); this.isolationGroup = json.getString("isolationGroup", DEFAULT_ISOLATION_GROUP); this.ha = json.getBoolean("ha", DEFAULT_HA); JsonArray arr = json.getJsonArray("extraClasspath", null); if (arr != null) { this.extraClasspath = arr.getList(); } this.instances = json.getInteger("instances", DEFAULT_INSTANCES); JsonArray arrIsolated = json.getJsonArray("isolatedClasses", null); if (arrIsolated != null) { this.isolatedClasses = arrIsolated.getList(); } }
@Override public CustomMessage decodeFromWire(int position, Buffer buffer) { // My custom message starting from this *position* of buffer int _pos = position; // Length of JSON int length = buffer.getInt(_pos); // Get JSON string by it`s length // Jump 4 because getInt() == 4 bytes String jsonStr = buffer.getString(_pos+=4, _pos+=length); JsonObject contentJson = new JsonObject(jsonStr); // Get fields int statusCode = contentJson.getInteger("statusCode"); String resultCode = contentJson.getString("resultCode"); String summary = contentJson.getString("summary"); // We can finally create custom message object return new CustomMessage(statusCode, resultCode, summary); }
/** * Create a delivery options from JSON * * @param json the JSON */ public DeliveryOptions(JsonObject json) { this.timeout = json.getLong("timeout", DEFAULT_TIMEOUT); this.codecName = json.getString("codecName", null); JsonObject hdrs = json.getJsonObject("headers", null); if (hdrs != null) { headers = new CaseInsensitiveHeaders(); for (Map.Entry<String, Object> entry: hdrs) { if (!(entry.getValue() instanceof String)) { throw new IllegalStateException("Invalid type for message header value " + entry.getValue().getClass()); } headers.set(entry.getKey(), (String)entry.getValue()); } } this.localOnly = json.getBoolean("localOnly", DEFAULT_LOCAL_ONLY); }
@Override public void start() throws Exception { // A simple backend vertx.eventBus().<JsonObject>consumer("backend", msg -> { JsonObject json = msg.body(); switch (json.getString("op", "")) { case "get": { String productID = json.getString("id"); msg.reply(products.get(productID)); break; } case "add": { String productID = json.getString("id"); JsonObject product = json.getJsonObject("product"); product.put("id", productID); msg.reply(addProduct(product)); break; } case "list": { JsonArray arr = new JsonArray(); products.forEach((k, v) -> arr.add(v)); msg.reply(arr); break; } default: { msg.fail(0, "operation not permitted"); } } }); }
@Test public void testCreateFromMapNestedMap() { Map<String, Object> map = new HashMap<>(); Map<String, Object> nestedMap = new HashMap<>(); nestedMap.put("foo", "bar"); map.put("nested", nestedMap); JsonObject obj = new JsonObject(map); JsonObject nestedRetrieved = obj.getJsonObject("nested"); assertEquals("bar", nestedRetrieved.getString("foo")); }
@Test public void testStartingApplicationInRedeployModeWithFileConf() throws IOException { cli.dispatch(new Launcher(), new String[]{"run", HttpTestVerticle.class.getName(), "--redeploy=**" + File.separator + "*.txt", "--launcher-class=" + Launcher.class.getName(), "--conf", new File("src/test/resources/conf.json").getAbsolutePath() }); assertWaitUntil(() -> { try { return RunCommandTest.getHttpCode() == 200; } catch (IOException e) { return false; } }); JsonObject conf = RunCommandTest.getContent().getJsonObject("conf"); assertThat(conf).isNotNull().isNotEmpty(); assertThat(conf.getString("name")).isEqualTo("vertx"); }
@Test public void testPutString() { assertSame(jsonObject, jsonObject.put("foo", "bar")); assertEquals("bar", jsonObject.getString("foo")); jsonObject.put("quux", "wibble"); assertEquals("wibble", jsonObject.getString("quux")); assertEquals("bar", jsonObject.getString("foo")); jsonObject.put("foo", "blah"); assertEquals("blah", jsonObject.getString("foo")); jsonObject.put("foo", (String) null); assertTrue(jsonObject.containsKey("foo")); try { jsonObject.put(null, "blah"); fail(); } catch (NullPointerException e) { // OK } }
@Test public void testDecode() { byte[] bytes = TestUtils.randomByteArray(10); String strBytes = Base64.getEncoder().encodeToString(bytes); Instant now = Instant.now(); String strInstant = ISO_INSTANT.format(now); String json = "[\"foo\",123,1234,1.23,2.34,true,\"" + strBytes + "\",\"" + strInstant + "\",null,{\"foo\":\"bar\"},[\"foo\",123]]"; JsonArray arr = new JsonArray(json); assertEquals("foo", arr.getString(0)); assertEquals(Integer.valueOf(123), arr.getInteger(1)); assertEquals(Long.valueOf(1234l), arr.getLong(2)); assertEquals(Float.valueOf(1.23f), arr.getFloat(3)); assertEquals(Double.valueOf(2.34d), arr.getDouble(4)); assertEquals(true, arr.getBoolean(5)); assertArrayEquals(bytes, arr.getBinary(6)); assertEquals(Base64.getEncoder().encodeToString(bytes), arr.getValue(6)); assertEquals(now, arr.getInstant(7)); assertEquals(now.toString(), arr.getValue(7)); assertTrue(arr.hasNull(8)); JsonObject obj = arr.getJsonObject(9); assertEquals("bar", obj.getString("foo")); JsonArray arr2 = arr.getJsonArray(10); assertEquals("foo", arr2.getString(0)); assertEquals(Integer.valueOf(123), arr2.getInteger(1)); }
String uri = config.getString("mongo_uri"); if (uri == null) { uri = "mongodb://localhost:27017"; String db = config.getString("mongo_db"); if (db == null) { db = "test"; JsonObject mongoconfig = new JsonObject() .put("connection_string", uri) .put("db_name", db); JsonObject product1 = new JsonObject().put("itemId", "12345").put("name", "Cooler").put("price", "100.0"); mongoClient.find("products", new JsonObject().put("itemId", "12345"), res -> { System.out.println("Name is " + res.result().get(0).getString("name")); mongoClient.remove("products", new JsonObject().put("itemId", "12345"), rs -> {
protected SQLClient createDbClient(JsonObject config) { return JDBCClient.createNonShared(vertx, new JsonObject() .put("url", config.getString("db_url", "jdbc:hsqldb:file:db/wiki")) .put("driver_class", config.getString("db_driver", "org.hsqldb.jdbcDriver")) .put("max_pool_size", config.getInteger("db_max_pool_size", 30))); }
/** * Initialise the fields of this instance from the specified JSON * * @param json the JSON */ public void fromJson(JsonObject json) { this.config = json.getJsonObject("config"); this.worker = json.getBoolean("worker", DEFAULT_WORKER); this.multiThreaded = json.getBoolean("multiThreaded", DEFAULT_MULTI_THREADED); this.isolationGroup = json.getString("isolationGroup", DEFAULT_ISOLATION_GROUP); this.ha = json.getBoolean("ha", DEFAULT_HA); JsonArray arr = json.getJsonArray("extraClasspath", null); if (arr != null) { this.extraClasspath = arr.getList(); } this.instances = json.getInteger("instances", DEFAULT_INSTANCES); JsonArray arrIsolated = json.getJsonArray("isolatedClasses", null); if (arrIsolated != null) { this.isolatedClasses = arrIsolated.getList(); } }
private void handleAddProduct(RoutingContext routingContext) { HttpServerResponse response = routingContext.response(); SQLConnection conn = routingContext.get("conn"); JsonObject product = routingContext.getBodyAsJson(); conn.updateWithParams("INSERT INTO products (name, price, weight) VALUES (?, ?, ?)", new JsonArray().add(product.getString("name")).add(product.getFloat("price")).add(product.getInteger("weight")), query -> { if (query.failed()) { sendError(500, response); } else { response.end(); } }); }