JsonObject data = new JsonObject() .put("title", "Seasons of the year"); JsonArray seasons = new JsonArray(); seasons.add(new JsonObject().put("name", "Spring")); seasons.add(new JsonObject().put("name", "Summer")); seasons.add(new JsonObject().put("name", "Autumn")); seasons.add(new JsonObject().put("name", "Winter")); data.put("seasons", seasons); if (res.succeeded()) { ctx.response().end(res.result()); } else { ctx.fail(res.cause()); vertx.createHttpServer().requestHandler(router).listen(8080);
@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)); } }
@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"); } } }); }
public StreamPriority(JsonObject json) { this.weight = json.getInteger("weight", (int)DEFAULT_WEIGHT).shortValue(); this.dependency = json.getInteger("dependency", DEFAULT_DEPENDENCY); this.exclusive = json.getBoolean("exclusive", DEFAULT_EXCLUSIVE); }
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); } }
@Override public void start(Future<Void> startFuture) throws Exception { JsonObject options = new JsonObject().put("httpOptions", new JsonObject(). put("host", "localhost"). put("port", 8080). put("authOptions", new JsonObject().put("provider", "shiro").put("config", new JsonObject().put("properties_path", "auth.properties"))) ); vertx.deployVerticle("service:io.vertx.ext.shell", new DeploymentOptions().setConfig(options), ar -> { if (ar.succeeded()) { startFuture.succeeded(); } else { startFuture.fail(ar.cause()); } }); } }
setClusterViewChangedHandler(haManager); clusterManager.<String, ClusterNodeInfo>getAsyncMultiMap(SUBS_MAP_NAME, ar1 -> { if (ar1.succeeded()) { subs = ar1.result(); server = vertx.createNetServer(getServerOptions()); if (asyncResult.succeeded()) { int serverPort = getClusterPublicPort(options, server.actualPort()); String serverHost = getClusterPublicHost(options); nodeInfo = new ClusterNodeInfo(clusterManager.getNodeID(), serverID); vertx.executeBlocking(fut -> { haManager.addDataToAHAInfo(SERVER_ID_HA_KEY, new JsonObject().put("host", serverID.host).put("port", serverID.port)); fut.complete(); }, false, ar2 -> { if (ar2.succeeded()) { started = true; resultHandler.handle(Future.succeededFuture()); } else { resultHandler.handle(Future.failedFuture(ar2.cause())); resultHandler.handle(Future.failedFuture(asyncResult.cause()));
index++; for (int j = 0; j < numToDeploy; j++) { JsonObject config = new JsonObject(); config.put("foo", TestUtils.randomAlphaString(100)); DeploymentOptions options = new DeploymentOptions().setHa(true).setConfig(config); String verticleName = "java:io.vertx.test.verticles.HAVerticle" + (random.nextInt(3) + 1); v.deployVerticle(verticleName, options, ar -> { assertTrue(ar.succeeded()); deployCount.incrementAndGet(); });
@GET @Path("/products") @Produces({MediaType.APPLICATION_JSON}) public void list( // Suspend the request @Suspended final AsyncResponse asyncResponse, // Inject the Vertx instance @Context Vertx vertx) { // Send a list message to the backend vertx.eventBus().<JsonArray>send("backend", new JsonObject().put("op", "list"), msg -> { // When we get the response we resume the Jax-RS async response if (msg.succeeded()) { JsonArray json = msg.result().body(); if (json != null) { asyncResponse.resume(json.encode()); } else { asyncResponse.resume(Response.status(Response.Status.NOT_FOUND).build()); } } else { asyncResponse.resume(Response.status(Response.Status.INTERNAL_SERVER_ERROR).build()); } }); } }
final JsonObject authInfo = new JsonObject(); String[] tokens = SPLITTER.split(parseAuthorization.result()); authInfo.put(m.group(1), m.group(2)); final String nonce = authInfo.getString("nonce"); handler.handle(Future.failedFuture(UNAUTHORIZED)); return; if (authInfo.containsKey("qop")) { int nc = Integer.parseInt(authInfo.getString("nc")); final Nonce n = nonces.get(nonce); if (nc <= n.count) { handler.handle(Future.failedFuture(UNAUTHORIZED)); return; final Session session = context.session(); if (session != null) { String opaque = (String) session.data().get("opaque"); if (opaque != null && !opaque.equals(authInfo.getString("opaque"))) { handler.handle(Future.failedFuture(UNAUTHORIZED)); return; authInfo.put("method", context.request().method().name()); handler.handle(Future.succeededFuture(authInfo));
@Override public void start(Future<Void> startFuture) throws Exception { HttpServerOptions options = new HttpServerOptions().setPort(config().getInteger("port")); vertx.createHttpServer(options).requestHandler(request -> { String name = request.getParam("name"); if (name == null) { request.response().setStatusCode(400).end("Missing name"); } else { vertx.eventBus().<String>send("hello", name, ar -> { if (ar.succeeded()) { request.response().end(ar.result().body()); } else { request.response().setStatusCode(500).end(ar.cause().getMessage()); } }); } }).listen(ar -> { if (ar.succeeded()) { startFuture.complete(); } else { startFuture.fail(ar.cause()); } }); } }
@Override public void parseCredentials(RoutingContext context, Handler<AsyncResult<JsonObject>> handler) { if (skip != null && context.normalisedPath().startsWith(skip)) { context.next(); return; } parseAuthorization(context, false, parseAuthorization -> { if (parseAuthorization.failed()) { handler.handle(Future.failedFuture(parseAuthorization.cause())); return; } handler.handle(Future.succeededFuture(new JsonObject().put("jwt", parseAuthorization.result()).put("options", options))); }); }
@Override public void parseCredentials(RoutingContext context, Handler<AsyncResult<JsonObject>> handler) { parseAuthorization(context, false, parseAuthorization -> { if (parseAuthorization.failed()) { handler.handle(Future.failedFuture(parseAuthorization.cause())); return; } final String suser; final String spass; try { // decode the payload String decoded = new String(Base64.getDecoder().decode(parseAuthorization.result())); int colonIdx = decoded.indexOf(":"); if (colonIdx != -1) { suser = decoded.substring(0, colonIdx); spass = decoded.substring(colonIdx + 1); } else { suser = decoded; spass = null; } } catch (RuntimeException e) { // IllegalArgumentException includes PatternSyntaxException context.fail(e); return; } handler.handle(Future.succeededFuture(new JsonObject().put("username", suser).put("password", spass))); }); }
@Override public SomeDatabaseService getDataById(int id, Handler<AsyncResult<JsonObject>> resultHandler) { if (id > 0) { resultHandler.handle(Future.succeededFuture(new JsonObject() .put("id", id) .put("name", "vertx"))); } else { resultHandler.handle(Future.failedFuture("Invalid id")); } return this; } }
@Test public void testToJsonObject() { Map<String, Object> map = new HashMap<>(); map.put("string", "the_string"); map.put("integer", 4); map.put("boolean", true); map.put("charsequence", new AsciiString("the_charsequence")); map.put("biginteger", new BigInteger("1234567")); map.put("binary", Buffer.buffer("hello")); map.put("object", Collections.singletonMap("nested", 4)); map.put("array", Arrays.asList(1, 2, 3)); JsonObject json = (JsonObject) ConversionHelper.toObject(map); assertEquals(8, json.size()); assertEquals("the_string", json.getString("string")); assertEquals(4, (int)json.getInteger("integer")); assertEquals(true, json.getBoolean("boolean")); assertEquals("the_charsequence", json.getString("charsequence")); assertEquals(1234567, (int)json.getInteger("biginteger")); assertEquals("hello", new String(json.getBinary("binary"))); assertEquals(new JsonObject().put("nested", 4), json.getJsonObject("object")); assertEquals(new JsonArray().add(1).add(2).add(3), json.getJsonArray("array")); }
private void sendMessage() { JsonObject jsonMessage = new JsonObject().put("message_from_sender_verticle", "hello consumer"); eventBus.send("Consumer", jsonMessage, messageAsyncResult -> { if(messageAsyncResult.succeeded()) { JsonObject jsonReply = (JsonObject) messageAsyncResult.result().body(); System.out.println("received reply: " + jsonReply.getValue("reply")); } }); } }
client = JDBCClient.createShared(vertx, new JsonObject() .put("url", "jdbc:hsqldb:mem:test?shutdown=true") .put("driver_class", "org.hsqldb.jdbcDriver")); if (res.failed()) { routingContext.fail(res.cause()); } else { SQLConnection conn = res.result(); routingContext.put("conn", conn); routingContext.addHeadersEndHandler(done -> conn.close(v -> { })); routingContext.next(); router.get("/products").handler(that::handleListProducts); vertx.createHttpServer().requestHandler(router).listen(8080); });
mongo = MongoClient.createShared(vertx, new JsonObject().put("db_name", "demo")); vertx.eventBus().consumer("vtoons.listAlbums", this::listAlbums); vertx.eventBus().consumer("vtoons.placeOrder", this::placeOrder); AuthProvider authProvider = ShiroAuth.create(vertx, ShiroAuthRealmType.PROPERTIES, new JsonObject()); JsonObject credentials = ctx.getBodyAsJson(); if (credentials == null) { ctx.fail(400); return; if (login.failed()) { ctx.fail(403); return; ctx.setUser(login.result()); ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json").end("{}"); }); vertx.createHttpServer().requestHandler(router).listen(8080);
vertx.registerVerticleFactory(fact); TestVerticleFactory factResolve = new TestVerticleFactory("resolve", "actual:myverticle", "othergroup"); vertx.registerVerticleFactory(factResolve); JsonObject config = new JsonObject().put("foo", "bar"); DeploymentOptions original = new DeploymentOptions().setWorker(false).setConfig(config).setIsolationGroup("somegroup"); DeploymentOptions options = new DeploymentOptions(original); vertx.deployVerticle("resolve:someid", options, res -> { assertTrue(res.succeeded()); assertEquals("resolve:someid", factResolve.identifierToResolve); assertEquals(options, factResolve.deploymentOptionsToResolve); assertTrue(verticle.startCalled); assertEquals(1, vertx.deploymentIDs().size()); Deployment dep = ((VertxInternal)vertx).getDeployment(res.result()); assertNotNull(dep); assertFalse(original.equals(dep.deploymentOptions())); assertFalse(dep.deploymentOptions().getConfig().containsKey("foo")); assertEquals("quux", dep.deploymentOptions().getConfig().getString("wibble")); assertTrue(dep.deploymentOptions().isWorker()); assertEquals("othergroup", dep.deploymentOptions().getIsolationGroup());