public static void fromJson(JsonObject json, PgConnectOptions obj) { if (json.getValue("cachePreparedStatements") instanceof Boolean) { obj.setCachePreparedStatements((Boolean)json.getValue("cachePreparedStatements")); } if (json.getValue("database") instanceof String) { obj.setDatabase((String)json.getValue("database")); } if (json.getValue("host") instanceof String) { obj.setHost((String)json.getValue("host")); } if (json.getValue("password") instanceof String) { obj.setPassword((String)json.getValue("password")); } if (json.getValue("pipeliningLimit") instanceof Number) { obj.setPipeliningLimit(((Number)json.getValue("pipeliningLimit")).intValue()); } if (json.getValue("port") instanceof Number) { obj.setPort(((Number)json.getValue("port")).intValue()); } if (json.getValue("username") instanceof String) { obj.setUsername((String)json.getValue("username")); } }
private void getShoppingList(RoutingContext rc) { Single<HttpResponse<Buffer>> list = shopping.get("/shopping").rxSend(); HttpServerResponse serverResponse = rc.response() .setChunked(true); list.subscribe( response -> { JsonObject body = response.bodyAsJsonObject(); Observable.from(body) .flatMap(entry -> retrievePrice(pricer, entry).toObservable()) .subscribe( product -> writeProductLine(serverResponse, product), rc::fail, serverResponse::end ); }, rc::fail); }
private void getShoppingListWithCB(RoutingContext rc) { Single<HttpResponse<Buffer>> list = shopping.get("/shopping").rxSend(); HttpServerResponse serverResponse = rc.response() .setChunked(true); list.subscribe( response -> { JsonObject body = response.bodyAsJsonObject(); Observable.from(body) .flatMap(entry -> circuit.executeWithFallback( future -> retrievePrice(pricer, entry, future), t -> getFallbackPrice(entry) ) .rxSetHandler().toObservable()) .subscribe( product -> writeProductLine(serverResponse, product), rc::fail, serverResponse::end ); }, rc::fail); }
private void indexHandler(RoutingContext context) { DeliveryOptions options = new DeliveryOptions().addHeader("action", "all-pages"); // <2> vertx.eventBus().send(wikiDbQueue, new JsonObject(), options, reply -> { // <1> if (reply.succeeded()) { JsonObject body = (JsonObject) reply.result().body(); // <3> context.put("title", "Wiki home"); context.put("pages", body.getJsonArray("pages").getList()); templateEngine.render(context, "templates", "/index.ftl", ar -> { if (ar.succeeded()) { context.response().putHeader("Content-Type", "text/html"); context.response().end(ar.result()); } else { context.fail(ar.cause()); } }); } else { context.fail(reply.cause()); } }); }
static ServiceDiscovery getServiceDiscovery(io.vertx.core.Vertx vertx) { // Discovery settings ServiceDiscoveryOptions serviceDiscoveryOptions = new ServiceDiscoveryOptions(); // Redis settings with the standard Redis Backend Integer redisPort = Integer.parseInt(Optional.ofNullable(System.getenv("REDIS_PORT")).orElse("6379")); String redisHost = Optional.ofNullable(System.getenv("REDIS_HOST")).orElse("127.0.0.1"); String redisAuth = Optional.ofNullable(System.getenv("REDIS_PASSWORD")).orElse(null); String redisRecordsKey = Optional.ofNullable(System.getenv("REDIS_RECORDS_KEY")).orElse("vert.x.ms"); // the redis hash return ServiceDiscovery.create( vertx, serviceDiscoveryOptions.setBackendConfiguration( new JsonObject() .put("host", redisHost) .put("port", redisPort) .put("auth", redisAuth) .put("key", redisRecordsKey) )); }
private void get(String uri, CacheItem<JsonObject> cache, Future<JsonObject> future, Retryable retryable) { client.get(HTTPS, ENDPOINT, uri).timeout(5000L).as(BodyCodec.jsonObject()).send(ar -> { if (ar.succeeded()) { HttpResponse<JsonObject> res = ar.result(); if (res.statusCode() == OK) { future.complete(cache.set(res.body())); } else if (res.statusCode() == RATE_LIMIT) { retryable.retry( () -> vertx.setTimer(getTimeTillReset(res), timer -> get(uri, cache, future, retryable)), () -> future.fail("Too many retries.")); } else { future.fail("TMDB API returned code: " + res.statusCode() + "; message: " + res.statusMessage()); } } else { retryable.retry( () -> vertx.setTimer(DEFAULT_DELAY, timer -> get(uri, cache, future, retryable)), () -> future.fail("Too many failures.")); } }); }
/** * a插入一条订单记录 */ public void insert(JsonObject order, Handler<Integer> callback) { Integer eid = order.getInteger(EID); if (eid == null) throw new IllegalArgumentException("Eid in Order object cannot be null!!!"); String orderId = order.getString(ORDERID); if (orderId == null || orderId.length() == 0) throw new IllegalArgumentException("OrderId in Order object cannot be null!!!"); String orderCallback = order.getString(CALLBACK); if (orderCallback == null || orderCallback.length() == 0) throw new IllegalArgumentException("Callback in Order object cannot be null!!!"); Integer type = order.getInteger(TYPE); if (type == null) throw new IllegalArgumentException("Type in Order object cannot be null!!!"); String sql = "INSERT INTO awp_order (eid,orderId,callback,type,createTime) VALUES (?,?,?,?,NOW())"; JsonArray params = new JsonArray().add(eid).add(orderId).add(orderCallback).add(type); update(sql, params, callback); }
private ConcurrentMap<String, VertxOptions> visit( final JsonArray vertxData) throws ZeroException { final ConcurrentMap<String, VertxOptions> map = new ConcurrentHashMap<>(); final boolean clustered = this.clusterOptions.isEnabled(); Fn.etJArray(vertxData, JsonObject.class, (item, index) -> { // 1. Extract single final String name = item.getString(YKEY_NAME); // 2. Extract VertxOptions final VertxOptions options = this.transformer.transform(item); // 3. Check the configuration for cluster sync Fn.flingZero(clustered != options.isClustered(), LOGGER, ClusterConflictException.class, getClass(), name, options.toString()); // 4. Put the options into map map.put(name, options); }); return map; }
@Test public void cannotProvideAdditionalPropertiesInLoan() throws InterruptedException, MalformedURLException, TimeoutException, ExecutionException { UUID id = UUID.randomUUID(); JsonObject requestWithAdditionalProperty = new LoanRequestBuilder() .withId(id) .create(); requestWithAdditionalProperty.put("somethingAdditional", "foo"); CompletableFuture<JsonErrorResponse> createCompleted = new CompletableFuture(); client.post(loanStorageUrl(), requestWithAdditionalProperty, StorageTestSuite.TENANT_ID, ResponseHandler.jsonErrors(createCompleted)); JsonErrorResponse response = createCompleted.get(5, TimeUnit.SECONDS); assertThat(response.getStatusCode(), is(UNPROCESSABLE_ENTITY)); assertThat(response.getErrors(), hasSoleMessgeContaining("Unrecognized field")); }
@RequiresPermissions("update") @PUT @Path("pages/{id}") public Single<Response> apiUpdatePage(@PathParam("id") String id, @ApiUpdateValid("markdown") JsonObject page, @Context HttpServerRequest req, @Context Vertx vertx){ JsonArray params = new JsonArray(); params.add(page.getString("markdown")).add(id); return SQLUtil.doInConnection(connection -> connection.rxUpdateWithParams(SQL.SQL_SAVE_PAGE, params)) .map(res -> { JsonObject event = new JsonObject() .put("id", id) .put("client", page.getString("client")); vertx.eventBus().publish("page.saved", event); return Response.ok(new JsonObject().put("success", true)).build(); }); }
private void apiGetPage(RoutingContext context) { int id = Integer.valueOf(context.request().getParam("id")); dbService.rxFetchPageById(id) .subscribe(dbObject -> { if (dbObject.getBoolean("found")) { JsonObject payload = new JsonObject() .put("name", dbObject.getString("name")) .put("id", dbObject.getInteger("id")) .put("markdown", dbObject.getString("content")) .put("html", Processor.process(dbObject.getString("content"))); apiResponse(context, 200, "page", payload); } else { apiFailure(context, 404, "There is no page with ID " + id); } }, t -> apiFailure(context, t)); }
@Override public JsonObject toJSON() { JsonObject json = new JsonObject(); //add header information json.put("event", this.event); json.put("messageID", this.uuid.toString()); //add message body json.put("data", this.data); if (!this.ssid.isEmpty()) { json.put("ssid", this.ssid); } return json; }
public static Completable dumbTradingLogic(String company, int numberOfShares, io.vertx.workshop.portfolio.reactivex.PortfolioService portfolio, JsonObject quote) { if (quote.getString("name").equals(company)) { if (TraderUtils.timeToSell()) { System.out.println("Trying to sell " + numberOfShares + " " + company); return portfolio.rxSell(numberOfShares, quote) .doOnSuccess(p -> System.out.println("Sold " + numberOfShares + " of " + company + "!")) .doOnError(e -> System.out.println("D'oh, failed to sell " + numberOfShares + " of " + company + ": " + e.getMessage())) .toCompletable(); } else { System.out.println("Trying to buy " + numberOfShares + " " + company); return portfolio.rxBuy(numberOfShares, quote) .doOnSuccess(p -> System.out.println("Bought " + numberOfShares + " of " + company + " !")) .doOnError(e -> System.out.println("D'oh, failed to buy " + numberOfShares + " of " + company + " : " + e .getMessage())) .toCompletable(); } } return Completable.complete(); }
@Test public void testInsert() throws SQLException { AtomicInteger counter = new AtomicInteger(0); client.handler((event) -> { if (!"write".equals(event.getString("type"))) { return; } assertEquals(config().getString("schema"), event.getString("schema")); assertEquals("binlog_client_test", event.getString("table")); JsonObject json = event.getJsonObject("row"); Integer id = json.getInteger("id"); String name = json.getString("name"); Map.Entry<Integer, String> expectedRow = rows().get(counter.getAndIncrement()); assertEquals(expectedRow.getKey(), id); assertEquals(expectedRow.getValue(), name); if (id.equals(lastId())) { testComplete(); } }); insert(); await(); }
@RequiresPermissions("update") @PUT @Path("pages/{id}") public Single<Response> apiUpdatePage(@PathParam("id") String id, @ApiUpdateValid("markdown") JsonObject page, @Context HttpServerRequest req, @Context Vertx vertx){ PagesDao dao = (PagesDao) AppGlobals.get().getGlobal("dao"); return dao.updateExecAsync(new Pages().setId(Integer.valueOf(id)).setContent(page.getString("markdown"))) .map(res -> { JsonObject event = new JsonObject() .put("id", id) .put("client", page.getString("client")); vertx.eventBus().publish("page.saved", event); return Response.ok(new JsonObject().put("success", true)).build(); }); }
/** * Gets value as JsonObject. * JsonObjects are converted to JsonObjs. * Parses JsonObject and Map types. */ @SuppressWarnings("unchecked") @Override public JsonObject getJsonObject(String key) { Object value = get(key); if (value == null) { return null; } if (value instanceof JsonObject) { if (value instanceof JsonObj) { return ((JsonObj) value); } return new JsonObj(((JsonObject) value).getMap()); } if (value instanceof Map) { return new JsonObj(((Map<String, Object>) value)); } return null; }
private static Sink buildSink(ObjectMapper mapper, Vertx vertx, String name, JsonNode config) { String type = config.get("type").asText(null); if (type == null) { throw new NullPointerException("Invalid configuration, the config " + name + " has no `type`"); } SinkFactory factory = lookupForSinkFactory(type); if (factory == null) { throw new NullPointerException("Invalid configuration, the sink type " + type + " is unknown"); } try { String json = mapper.writeValueAsString(config); return factory.create(vertx, new JsonObject(json).put("name", name)).blockingGet(); } catch (JsonProcessingException e) { throw new IllegalArgumentException("Invalid configuration for " + name, e); } }
private void updateOne(RoutingContext ctx) { JsonObject item; try { item = ctx.getBodyAsJson(); } catch (RuntimeException e) { error(ctx, 415, "invalid payload"); return; } if (item == null) { error(ctx, 415, "invalid payload"); return; } store.update(ctx.get("fruitId"), item) .subscribe( () -> ctx.response() .putHeader("Content-Type", "application/json") .setStatusCode(200) .end(item.put("id", ctx.<Long>get("fruitId")).encodePrettily()), err -> writeError(ctx, err) ); }
@Override public void handle(RoutingContext routingContext) { Book book = decodeBodyToObject(routingContext, Book.class); int bookId = Integer.valueOf(routingContext.pathParam("id")); bookDatabaseService.rxUpsertBookById(bookId, book) .subscribe( () -> restResponse(routingContext, 200, new JsonObject() .put("id", bookId) .put("title", book.getTitle()) .put("category", book.getCategory()) .put("publicationDate", book.getPublicationDate()) .toString()), throwable -> routingContext.fail(new BadRequestException(throwable)) ); }
static JsonObject append( final JsonObject target, final JsonObject source, final boolean immutable ) { final JsonObject result = immutable ? target.copy() : target; Observable.fromIterable(source.fieldNames()) .filter(key -> !target.containsKey(key)) .subscribe(key -> result.put(key, source.getValue(key))); return result; }
private void doWithConfiguration(Handler<JsonObject> handler) { if (config != null) { handler.handle(config); } else { loadConfiguration(CONFIG_FILE_DEFAULT_PATH, vertx, ar -> { if (ar.succeeded()) { handler.handle(ar.result()); } }); } }
static <R> R init(final String key, final Function<JsonObject, R> executor, final Class<?> clazz) { final Node<JsonObject> node = Instance.instance(ZeroUniform.class); final JsonObject options = node.read(); final Annal logger = Annal.get(clazz); Fn.flingUp(null == options || !options.containsKey(key) , logger, ConfigKeyMissingException.class, clazz, key); final JsonObject config = options.getJsonObject(key); Fn.flingUp(() -> Ruler.verify(key, config), logger); return executor.apply(config); }
private boolean validateJsonPageDocument(RoutingContext context, JsonObject page, String... expectedKeys) { if (!Arrays.stream(expectedKeys).allMatch(page::containsKey)) { LOGGER.error("Bad page creation JSON payload: " + page.encodePrettily() + " from " + context.request().remoteAddress()); context.response().setStatusCode(400); context.response().putHeader("Content-Type", "application/json"); context.response().end(new JsonObject() .put("success", false) .put("error", "Bad request payload").encode()); return false; } return true; }
private Single<JsonArray> findTracks(SQLConnection sqlConnection, Long albumId) { return sqlConnection.rxQueryStreamWithParams(findTracksByAlbum, new JsonArray().add(albumId)) .flatMapObservable(SQLRowStream::toObservable) .map(row -> { return new JsonObject() .put("id", row.getLong(0)) .put("track_number", row.getInteger(1)) .put("title", row.getString(2)) .put("mb_track_id", row.getString(3)) .put("artist", new JsonObject() .put("id", row.getLong(4)) .put("name", row.getString(5))); }).collect(JsonArray::new, JsonArray::add); }
static void scheduling(Vertx vertx) { EventBus eventBus = vertx.eventBus(); // Consumer of the timer events MessageConsumer<JsonObject> consumer = eventBus.consumer("scheduler:timer"); // Listens and prints timer events. When timer completes stops the Vertx consumer.handler ( message -> { JsonObject event = message.body(); if (event.getString("event").equals("complete")) { System.out.println("completed"); vertx.close(); } else { System.out.println(event); } } ); // Create new timer eventBus.send ( "chime", (new JsonObject()).put("operation", "create").put("name", "scheduler:timer") .put("publish", false).put("max count", 3) .put("description", (new JsonObject()).put("type", "interval").put("delay", 1)), ar -> { if (ar.succeeded()) { System.out.println("Scheduling started: " + ar.result().body()); } else { System.out.println("Message failed: " + ar.cause()); vertx.close(); } } ); }
private void apiRoot(RoutingContext context) { dbService.rxFetchAllPagesData() .flatMapObservable(Observable::from) .map(obj -> new JsonObject() .put("id", obj.getInteger("ID")) .put("name", obj.getString("NAME"))) .collect(JsonArray::new, JsonArray::add) .subscribe(pages -> apiResponse(context, 200, "pages", pages), t -> apiFailure(context, t)); }
@Test public void proxyFromSystemProps() throws Exception { System.setProperty("http.proxyHost", "proxy.example.com"); System.setProperty("http.proxyPort", "8080"); System.setProperty("https.proxyHost", "proxy.example.com"); System.setProperty("https.proxyPort", "8443"); System.setProperty("http.nonProxyHosts", "*.example.com|localhost|127.0.0.1"); System.setProperty("socksProxyHost", "proxy.example.com"); System.setProperty("socksProxyPort", "1053"); JsonObject proxyObj = BaseUtil.proxyFromSystemProps(); Assert.assertTrue("Http proxy set", proxyObj.containsKey("httpProxyURL")); Assert.assertTrue("Https proxy set", proxyObj.containsKey("httpsProxyURL")); Assert.assertTrue("Socks proxy set", proxyObj.containsKey("socksProxyURL")); System.clearProperty("http.proxyHost"); System.clearProperty("http.proxyPort"); System.clearProperty("https.proxyHost"); System.clearProperty("https.proxyPort"); System.clearProperty("http.nonProxyHosts"); System.clearProperty("socksProxyHost"); System.clearProperty("socksProxyPort"); proxyObj = BaseUtil.proxyFromSystemProps(); Assert.assertFalse("Http proxy not set", proxyObj.containsKey("httpProxyURL")); Assert.assertFalse("Https proxy not set", proxyObj.containsKey("httpsProxyURL")); Assert.assertFalse("Socks proxy not set", proxyObj.containsKey("socksProxyURL")); }
public static List<JsonObject> toList(JsonArray array) { return array .stream() .map(item -> { if(item instanceof JsonObject) { return (JsonObject)item; } else { return null; } }) .filter(item -> item != null) .collect(Collectors.toList()); }
public void assertGhostView(JsonObject view) { assertThat(view.getInteger("MovieId"), is(315837)); assertThat(view.getString("Title"), is("Ghost in the Shell")); assertThat(view.getString("Start"), is("17 March 2017")); assertThat(view.getString("WasFirst"), is("")); assertThat(view.getString("WasCinema"), is("fa fa-ticket new")); assertThat(view.getString("Image"), is("/si1ZyELNHdPUZw4pXR5KjMIIsBF.jpg")); assertThat(view.getString("Comment"), is("lamp")); assertThat(view.getInteger("Runtime"), is(106)); assertThat(view.getString("DayOfWeek"), is("FRIDAY")); assertThat(view.getString("Time"), is("15:58")); }
private void fetchAllPages(Message<JsonObject> message) { dbClient.query(sqlQueries.get(SqlQuery.ALL_PAGES), res -> { if (res.succeeded()) { List<String> pages = res.result() .getResults() .stream() .map(json -> json.getString(0)) .sorted() .collect(Collectors.toList()); message.reply(new JsonObject().put("pages", new JsonArray(pages))); } else { reportQueryError(message, res.cause()); } }); }
private void deletePage(Message<JsonObject> message) { JsonArray data = new JsonArray().add(message.body().getString("id")); dbClient.updateWithParams(sqlQueries.get(SqlQuery.DELETE_PAGE), data, res -> { if (res.succeeded()) { message.reply("ok"); } else { reportQueryError(message, res.cause()); } }); }
@Override public Future<JsonObject> getTimeDistribution(String username, String jsonParam) { JsonObject json = new JsonObject(jsonParam); json.put("start", formToDBDate(json.getString("start"), false)); json.put("end", formToDBDate(json.getString("end"), true)); StringBuilder sb = new StringBuilder(SQL_GET_TIME_DIST); ifTrue(json.getBoolean("is-first"), () -> sb.append(" AND WasFirst")); ifTrue(json.getBoolean("is-cinema"), () -> sb.append(" AND WasCinema")); return query(sb.append(" GROUP BY Hour").toString(), new JsonArray() .add(username) .add(json.getString("start")) .add(json.getString("end"))); }
private void pageRenderingHandler(RoutingContext context) { String requestedPage = context.request().getParam("page"); dbService.fetchPage(requestedPage, reply -> { if (reply.succeeded()) { JsonObject payLoad = reply.result(); boolean found = payLoad.getBoolean("found"); String rawContent = payLoad.getString("rawContent", EMPTY_PAGE_MARKDOWN); context.put("title", requestedPage); context.put("id", payLoad.getInteger("id", -1)); context.put("newPage", found ? "no" : "yes"); context.put("rawContent", rawContent); context.put("content", Processor.process(rawContent)); context.put("timestamp", new Date().toString()); templateEngine.render(context, "templates", "/page.ftl", ar -> { if (ar.succeeded()) { context.response().putHeader("Content-Type", "text/html"); context.response().end(ar.result()); } else { context.fail(ar.cause()); } }); } else { context.fail(reply.cause()); } }); }
private JsonObject toProject(JsonObject projectRequest) { return new JsonObject() .put("version", projectRequest.getString("version")) .put("language", projectRequest.getString("language")) .put("build", projectRequest.getString("build")) .put("groupId", projectRequest.getString("groupId")) .put("artifactId", projectRequest.getString("artifactId")) .put("dependencies", projectRequest.getJsonArray("dependencies")) .put("format", projectRequest.getString("format")) .put("creationDate", Instant.now()); }
private void apiCreatePage(RoutingContext context) { JsonObject page = context.getBodyAsJson(); if (!validateJsonPageDocument(context, page, "name", "markdown")) { return; } dbService.rxCreatePage(page.getString("name"), page.getString("markdown")).subscribe( v -> apiResponse(context, 201, null, null), t -> apiFailure(context, t)); }
public JsonObject build() { return new JsonObject() .put("baseDir", baseDir) .put("language", language) .put("buildTool", buildTool) .put("version", version) .put("groupId", groupId) .put("artifactId", artifactId) .put("dependencies", new JsonArray(new ArrayList(dependencies))); }
/** * @param wallClses * @param keysRef * @return */ private JsonObject verify(final Set<Class<?>> wallClses, final ConcurrentMap<String, Class<?>> keysRef) { /** Wall duplicated **/ final Set<String> hashs = new HashSet<>(); Observable.fromIterable(wallClses) .filter(Objects::nonNull) .map(item -> { final Annotation annotation = item.getAnnotation(Wall.class); // Add configuration key into keys; keysRef.put(Instance.invoke(annotation, "value"), item); return this.hashPath(annotation); }).subscribe(hashs::add); // Duplicated adding. Fn.flingUp(hashs.size() != wallClses.size(), LOGGER, WallDuplicatedException.class, getClass(), wallClses.stream().map(Class::getName).collect(Collectors.toSet())); /** Shared key does not existing **/ final JsonObject config = NODE.read(); Fn.flingUp(!config.containsKey(KEY), LOGGER, DynamicKeyMissingException.class, getClass(), KEY, config); /** Wall key missing **/ final JsonObject hitted = config.getJsonObject(KEY); for (final String key : keysRef.keySet()) { Fn.flingUp(null == hitted || !hitted.containsKey(key), LOGGER, WallKeyMissingException.class, getClass(), key, keysRef.get(key)); } return hitted; }
public static void fromJson(JsonObject json, BinlogClientOptions obj) { if (json.getValue("connectTimeout") instanceof Number) { obj.setConnectTimeout(((Number)json.getValue("connectTimeout")).longValue()); } if (json.getValue("filename") instanceof String) { obj.setFilename((String)json.getValue("filename")); } if (json.getValue("heartbeatInterval") instanceof Number) { obj.setHeartbeatInterval(((Number)json.getValue("heartbeatInterval")).longValue()); } if (json.getValue("host") instanceof String) { obj.setHost((String)json.getValue("host")); } if (json.getValue("keepAlive") instanceof Boolean) { obj.setKeepAlive((Boolean)json.getValue("keepAlive")); } if (json.getValue("keepAliveInterval") instanceof Number) { obj.setKeepAliveInterval(((Number)json.getValue("keepAliveInterval")).longValue()); } if (json.getValue("password") instanceof String) { obj.setPassword((String)json.getValue("password")); } if (json.getValue("port") instanceof Number) { obj.setPort(((Number)json.getValue("port")).intValue()); } if (json.getValue("position") instanceof Number) { obj.setPosition(((Number)json.getValue("position")).longValue()); } if (json.getValue("username") instanceof String) { obj.setUsername((String)json.getValue("username")); } }