List of usage examples for io.vertx.core.json JsonObject getJsonObject
public JsonObject getJsonObject(String key)
From source file:com.github.ithildir.airbot.model.MeasurementConverter.java
License:Apache License
public static void fromJson(JsonObject json, Measurement obj) { if (json.getValue("aqi") instanceof Number) { obj.setAqi(((Number) json.getValue("aqi")).intValue()); }// w w w . java 2 s . co m if (json.getValue("city") instanceof String) { obj.setCity((String) json.getValue("city")); } if (json.getValue("comments") instanceof String) { obj.setComments((String) json.getValue("comments")); } if (json.getValue("mainPollutant") instanceof String) { obj.setMainPollutant((String) json.getValue("mainPollutant")); } if (json.getValue("time") instanceof Number) { obj.setTime(((Number) json.getValue("time")).longValue()); } if (json.getValue("values") instanceof JsonObject) { java.util.Map<String, java.lang.Double> map = new java.util.LinkedHashMap<>(); json.getJsonObject("values").forEach(entry -> { if (entry.getValue() instanceof Number) map.put(entry.getKey(), ((Number) entry.getValue()).doubleValue()); }); obj.setValues(map); } }
From source file:com.github.ithildir.airbot.service.impl.MapQuestGeoServiceImpl.java
License:Open Source License
private Location _getLocation(JsonObject jsonObject) { JsonArray resultsJsonArray = jsonObject.getJsonArray("results"); JsonObject resultJsonObject = resultsJsonArray.getJsonObject(0); JsonArray locationsJsonArray = resultJsonObject.getJsonArray("locations"); JsonObject locationJsonObject = locationsJsonArray.getJsonObject(0); JsonObject latLngJsonObject = locationJsonObject.getJsonObject("latLng"); double latitude = latLngJsonObject.getDouble("lat"); double longitude = latLngJsonObject.getDouble("lng"); String country = locationJsonObject.getString("adminArea1"); return new Location(latitude, longitude, country); }
From source file:com.github.ithildir.airbot.service.impl.WaqiMeasurementServiceImpl.java
License:Open Source License
private Measurement _getMeasurement(JsonObject jsonObject) { String status = jsonObject.getString("status"); if (!"ok".equals(status)) { _logger.warn("Unable to use response {0}", jsonObject); return null; }//from ww w. j av a2s.co m JsonObject dataJsonObject = jsonObject.getJsonObject("data"); JsonObject cityJsonObject = dataJsonObject.getJsonObject("city"); String city = cityJsonObject.getString("name"); JsonObject timeJsonObject = dataJsonObject.getJsonObject("time"); String dateTime = timeJsonObject.getString("s"); String dateTimeOffset = timeJsonObject.getString("tz"); String date = dateTime.substring(0, 10); String time = dateTime.substring(11); TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_OFFSET_DATE_TIME .parse(date + "T" + time + dateTimeOffset); Instant instant = Instant.from(temporalAccessor); int aqi = dataJsonObject.getInteger("aqi"); String mainPollutant = dataJsonObject.getString("dominentpol"); Map<String, Double> values = new HashMap<>(); JsonObject valuesJsonObject = dataJsonObject.getJsonObject("iaqi"); for (String pollutant : valuesJsonObject.fieldNames()) { JsonObject pollutantJsonObject = valuesJsonObject.getJsonObject(pollutant); double value = pollutantJsonObject.getDouble("v"); values.put(pollutant, value); } return new Measurement(city, instant.toEpochMilli(), aqi, mainPollutant, values, null); }
From source file:com.github.ithildir.numbers.game.NumbersGameVerticle.java
License:Open Source License
private void _handleText(JsonObject requestJSON, JsonObject inputJSON, HttpServerResponse httpServerResponse) { JsonArray rawInputsJSON = inputJSON.getJsonArray("raw_inputs"); JsonObject rawInputJSON = rawInputsJSON.getJsonObject(0); String query = rawInputJSON.getString("query"); JsonObject conversationJSON = requestJSON.getJsonObject("conversation"); int correctAnswer = Integer.parseInt(conversationJSON.getString("conversation_token")); int answer;/*from www. j a v a2 s. c o m*/ try { answer = Integer.parseInt(query); } catch (NumberFormatException nfe) { ConversationUtil.ask(httpServerResponse, String.valueOf(correctAnswer), "That's not a number, say it again!", _NO_INPUT_PROMPTS); return; } String textToSpeech = "You're right, it is " + correctAnswer + "!"; if (answer != correctAnswer) { textToSpeech = "You're wrong, it was " + correctAnswer + "!"; } ConversationUtil.tell(httpServerResponse, textToSpeech); }
From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java
License:Apache License
private void prepareEnsureUnique(String id, JsonObject instance, RBatch redissonBatch, ArrayList<String> pList, String parent) throws RepositoryException { try {/*from w w w.j av a 2s. com*/ BeanMap pMap = new BeanMap(cls.newInstance()); pMap.keySet().forEach(e -> { if ("class".equals(e) || instance.getValue(e.toString()) == null) { return; } Class type = pMap.getType(e.toString()); String fieldName = (parent == null ? "" : parent.concat(".")).concat(e.toString()); if (isRedisEntity(type)) { try { RedisRepositoryImpl innerRepo = (RedisRepositoryImpl) factory.instance(type); innerRepo.prepareEnsureUnique(id, instance.getJsonObject(e.toString()), redissonBatch, pList, fieldName); } catch (RepositoryException ex) { throw new RuntimeException(ex); } } else { try { if (cls.getDeclaredField(e.toString()).isAnnotationPresent(RedissonUnique.class)) { redissonBatch.getMap(getUniqueKey(e.toString())) .putIfAbsentAsync(instance.getValue(e.toString()), id); pList.add(fieldName); } } catch (NoSuchFieldException | SecurityException ex) { throw new RuntimeException(ex); } } }); } catch (InstantiationException | IllegalAccessException | RuntimeException ex) { throw new RepositoryException(ex); } }
From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java
License:Apache License
private void prepareUndoUnique(String id, JsonObject instance, RBatch redissonBatch, ArrayList<String> pList, String parent) throws RepositoryException { try {/*from ww w . j a va2 s.c o m*/ BeanMap pMap = new BeanMap(cls.newInstance()); pMap.keySet().forEach(e -> { if ("class".equals(e) || instance.getValue(e.toString()) == null) { return; } Class type = pMap.getType(e.toString()); String fieldName = (parent == null ? "" : parent.concat(".")).concat(e.toString()); if (isRedisEntity(type)) { try { RedisRepositoryImpl innerRepo = (RedisRepositoryImpl) factory.instance(type); innerRepo.prepareUndoUnique(id, instance.getJsonObject(e.toString()), redissonBatch, pList, fieldName); } catch (RepositoryException ex) { throw new RuntimeException(ex); } } else { try { if (cls.getDeclaredField(e.toString()).isAnnotationPresent(RedissonUnique.class) && pList.contains(fieldName)) { redissonBatch.getMap(getUniqueKey(e.toString())) .removeAsync(instance.getValue(e.toString()), id); } } catch (NoSuchFieldException | SecurityException ex) { throw new RuntimeException(ex); } } }); } catch (InstantiationException | IllegalAccessException | RuntimeException ex) { throw new RepositoryException(ex); } }
From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java
License:Apache License
private void prepareEnsuerIndex(String id, T r, JsonObject instance, Boolean isNew, RBatch redissonBatch, ArrayList<String> pList, String parent) throws RepositoryException { try {//ww w . j ava2 s .co m BeanMap pMap = new BeanMap(r == null ? cls.newInstance() : r); pMap.keySet().forEach(e -> { if ("class".equals(e) || instance.getValue(e.toString()) == null) { return; } Class type = pMap.getType(e.toString()); String fieldName = (parent == null ? "" : parent.concat(".")).concat(e.toString()); if (isRedisEntity(type)) { try { RedisRepositoryImpl innerRepo = (RedisRepositoryImpl) factory.instance(type); innerRepo.prepareEnsuerIndex(id, pMap.get(e), instance.getJsonObject(e.toString()), isNew, redissonBatch, pList, fieldName); } catch (RepositoryException ex) { throw new RuntimeException(ex); } } else { try { if (cls.getDeclaredField(e.toString()).isAnnotationPresent(RedissonIndex.class)) { RedissonIndex index = cls.getDeclaredField(e.toString()) .getAnnotation(RedissonIndex.class); if (index.indexOnSave()) { prepareEnsuerIndex(id, r, instance, redissonBatch, index, e.toString(), pMap.get(e)); } } else if (cls.getDeclaredField(e.toString()) .isAnnotationPresent(RedissonIndex.List.class)) { RedissonIndex.List indexList = cls.getDeclaredField(e.toString()) .getAnnotation(RedissonIndex.List.class); Arrays.stream(indexList.value()).filter(f -> f.indexOnSave()) .forEach(index -> prepareEnsuerIndex(id, r, instance, redissonBatch, index, e.toString(), pMap.get(e))); } if (cls.getDeclaredField(e.toString()).isAnnotationPresent(RedissonCounter.class)) { RedissonCounter counter = cls.getDeclaredField(e.toString()) .getAnnotation(RedissonCounter.class); prepareEnsuerCounter(id, r, instance, isNew, redissonBatch, counter, e.toString(), pMap.get(e)); } else if (cls.getDeclaredField(e.toString()) .isAnnotationPresent(RedissonCounter.List.class)) { RedissonCounter.List counterList = cls.getDeclaredField(e.toString()) .getAnnotation(RedissonCounter.List.class); Arrays.stream(counterList.value()).forEach(index -> prepareEnsuerCounter(id, r, instance, isNew, redissonBatch, index, e.toString(), pMap.get(e))); } } catch (NoSuchFieldException ex) { throw new RuntimeException(ex); } } }); } catch (InstantiationException | IllegalAccessException | RuntimeException ex) { throw new RepositoryException(ex); } }
From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java
License:Apache License
private void persistBlocking(String id, JsonObject data, RBatch redissonBatch, Handler<AsyncResult<Boolean>> resultHandler) { RBatch batch = redissonBatch == null ? redissonWrite.createBatch() : redissonBatch; AtomicBoolean failed = new AtomicBoolean(false); try {//from w w w . ja va 2s .c o m BeanMap pMap = new BeanMap(cls.newInstance()); //remove the indexes; if (isRedisEntity()) { AtomicBoolean finished = new AtomicBoolean(false); AtomicBoolean hasNested = new AtomicBoolean(false); AtomicLong stack = new AtomicLong(); pMap.forEach((k, v) -> { if ("class".equals(k)) { return; } Class<?> type = pMap.getType((String) k); if (!isRedisEntity(type)) { //recreate the indexes; if ("id".equals(k)) { batch.getMap(getStorageKey(), StringCodec.INSTANCE).fastPutAsync(id, id); } else { batch.getMap(getStorageKey((String) k)).fastPutAsync(id, data.getValue((String) k)); } } else { hasNested.set(true); stack.incrementAndGet(); RedisRepositoryImpl<?> innerRepo; try { innerRepo = (RedisRepositoryImpl) factory.instance(type); } catch (RepositoryException e) { throw new RuntimeException(e); } JsonObject value = data.getJsonObject((String) k); final boolean newOne = !value.containsKey("id") || value.getString("id") == null || "null".equals(value.getString("id")); final String ID = newOne ? id : value.getString("id"); innerRepo.persist(ID, value, batch, c -> {//making the nested entity shares the same id as the parent when its 1:1 relation. This makes fetch a lot faster since it doesn't not need to resolve the reference when fetching 1:1 nested objects. if (c.succeeded()) { long s = stack.decrementAndGet(); if (newOne) { batch.getMap(getStorageKey((String) k)).fastPutAsync(id, ID);//different to the update, create needs to add the reference field to batch } if (s == 0 && finished.get() && !failed.get()) { //finished iterating and no outstanding processes. if (redissonBatch == null) {//if it's not inside a nested process. finishPersist(id, data, batch, resultHandler); } else {//if it is inside a nested process. resultHandler.handle(Future.succeededFuture(true)); } } //else wait for others to complete } else { boolean firstToFail = failed.compareAndSet(false, true); if (firstToFail) { resultHandler.handle(Future.failedFuture(c.cause())); } } }); } }); batch.getAtomicLongAsync(getCounterKey()).incrementAndGetAsync(); finished.set(true); if (!hasNested.get()) {//does not have nested RedissonEntity within if (redissonBatch == null) {//if it's not inside a nested process. finishPersist(id, data, batch, resultHandler); } else {//if it is inside a nested process. resultHandler.handle(Future.succeededFuture(true)); } } } else {//not a RedissonEntity class, persist as json string. //recreate the indexes; batch.<String, String>getMap(getStorageKey(), StringCodec.INSTANCE).fastPutAsync(id, Json.encode(data)); batch.getAtomicLongAsync(getCounterKey()).incrementAndGetAsync(); if (redissonBatch == null) {//if it's not inside a nested process. finishPersist(id, data, batch, resultHandler); } else {//if it is inside a nested process. resultHandler.handle(Future.succeededFuture(true)); } } } catch (InstantiationException | IllegalAccessException | RuntimeException ex) { failed.set(true); resultHandler.handle(Future.failedFuture(ex)); } }
From source file:com.glencoesoftware.omero.ms.thumbnail.ThumbnailMicroserviceVerticle.java
License:Open Source License
/** * Deploys our verticles and performs general setup that depends on * configuration.//from www . j av a2s . c o m * @param config Current configuration */ public void deploy(JsonObject config, Future<Void> future) { log.info("Deploying verticle"); // Deploy our dependency verticles JsonObject omero = config.getJsonObject("omero"); if (omero == null) { throw new IllegalArgumentException("'omero' block missing from configuration"); } vertx.deployVerticle(new ThumbnailVerticle(omero.getString("host"), omero.getInteger("port")), new DeploymentOptions().setWorker(true).setMultiThreaded(true).setConfig(config)); HttpServer server = vertx.createHttpServer(); Router router = Router.router(vertx); // Cookie handler so we can pick up the OMERO.web session router.route().handler(CookieHandler.create()); // OMERO session handler which picks up the session key from the // OMERO.web session and joins it. JsonObject redis = config.getJsonObject("redis"); if (redis == null) { throw new IllegalArgumentException("'redis' block missing from configuration"); } sessionStore = new OmeroWebRedisSessionStore(redis.getString("uri")); router.route().handler(new OmeroWebSessionRequestHandler(config, sessionStore)); // Thumbnail request handlers router.get("/webclient/render_thumbnail/size/:longestSide/:imageId*").handler(this::renderThumbnail); router.get("/webclient/render_thumbnail/:imageId*").handler(this::renderThumbnail); router.get("/webgateway/render_thumbnail/:imageId/:longestSide*").handler(this::renderThumbnail); router.get("/webgateway/render_thumbnail/:imageId*").handler(this::renderThumbnail); router.get("/webclient/render_birds_eye_view/:imageId/:longestSide*").handler(this::renderThumbnail); router.get("/webclient/render_birds_eye_view/:imageId*").handler(this::renderThumbnail); router.get("/webgateway/render_birds_eye_view/:imageId/:longestSide*").handler(this::renderThumbnail); router.get("/webgateway/render_birds_eye_view/:imageId*").handler(this::renderThumbnail); router.get("/webgateway/get_thumbnails/:longestSide*").handler(this::getThumbnails); router.get("/webgateway/get_thumbnails*").handler(this::getThumbnails); router.get("/webclient/get_thumbnails/:longestSide*").handler(this::getThumbnails); router.get("/webclient/get_thumbnails*").handler(this::getThumbnails); int port = config.getInteger("port"); log.info("Starting HTTP server *:{}", port); server.requestHandler(router::accept).listen(port, result -> { if (result.succeeded()) { future.complete(); } else { future.fail(result.cause()); } }); }
From source file:com.groupon.vertx.memcache.codec.RetrieveCommandResponseCodec.java
License:Apache License
@Override public RetrieveCommandResponse decodeFromWire(int i, Buffer buffer) { JsonObject json = CodecManager.JSON_OBJECT_MESSAGE_CODEC.decodeFromWire(i, buffer); JsendStatus status = JsendStatus.valueOf(json.getString("status")); String message = json.getString("message"); JsonObject jsonData = json.getJsonObject("data"); Map<String, String> data = null; if (jsonData != null) { data = new HashMap<>(); for (Map.Entry<String, Object> entry : jsonData.getMap().entrySet()) { data.put(entry.getKey(), entry.getValue() != null ? entry.getValue().toString() : null); }//from w w w . j a v a2 s .co m } return new RetrieveCommandResponse.Builder().setStatus(status).setMessage(message).setData(data).build(); }