List of usage examples for io.vertx.core.json JsonObject getString
public String getString(String key)
From source file:com.github.ithildir.airbot.WaqiMeasurementServiceVerticle.java
License:Open Source License
@Override protected MeasurementService getServiceImpl(JsonObject configJsonObject) { String key = configJsonObject.getString(ConfigKeys.WAQI_KEY); return new WaqiMeasurementServiceImpl(vertx, key); }
From source file:com.github.ithildir.numbers.game.NumbersGameVerticle.java
License:Open Source License
private void _handle(RoutingContext routingContext) { JsonObject requestJSON = routingContext.getBodyAsJson(); JsonArray inputsJSON = requestJSON.getJsonArray("inputs"); JsonObject inputJSON = inputsJSON.getJsonObject(0); String intent = inputJSON.getString("intent"); if (intent.equals(ConversationUtil.INTENT_MAIN)) { _handleMain(routingContext.response()); } else {/*from w w w .java 2s .c om*/ _handleText(requestJSON, inputJSON, routingContext.response()); } }
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 w w w .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.handler.Impl.CallInMessageHandlerImpl.java
License:Apache License
@Override public void handle(Message<JsonObject> m) { JsonObject jBody = m.body(); String from = jBody.getString("from"); String to = jBody.getString("to"); Long requestTime = jBody.getLong("requestTime"); String userData = jBody.getString("userData"); AtomicReference<String> cId = new AtomicReference(); AtomicReference<Customer.PersonalDetails> p = new AtomicReference(); Async.waterfall().<String>task(t -> { personalDetailsRepo.searchUniqueIndex("phoneNumber", from, t); }).<Customer.PersonalDetails>task((id, t) -> { cId.set(id);//from w ww . j a v a2 s . c om personalDetailsRepo.get(id, t); }).<Customer.AddressDetails>task((c, t) -> { p.set(c); addressDetailsRepo.get(cId.get(), t); }).run(r -> { CallIn ci; if (r.failed()) { ci = CallIn.builder().callTime(requestTime).callType(numberTypeMap.get(to)).comments(userData) .fullName("??").phoneNumber(from).build(); } else { Customer.PersonalDetails cpd = p.get(); Customer.AddressDetails cad = r.result(); ci = CallIn.builder().address(cad.getFullAddress()).area(cpd.getArea()).birthDay(cpd.getBirthDay()) .callTime(requestTime).callType(numberTypeMap.get(to)).city(cpd.getCity()) .comments(userData).customerId(cId.get()).fullName(cpd.getFullName()) .gender(cpd.getGender()).phoneNumber(from).province(cpd.getProvince()).type(cpd.getType()) .build(); } callInRepo.create(Json.encode(ci), c -> { m.reply(c.result()); ci.setId(c.result()); vertx.eventBus().publish("client.notification.inComingCall", Json.encode(ci)); }); }); }
From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java
License:Apache License
private void update(String id, String data, RBatch redissonBatch, Handler<AsyncResult<Boolean>> resultHandler) { vertx.<JsonObject>executeBlocking(f -> { JsonObject d = new JsonObject(data); if (schema == null && !f.isComplete()) { f.complete(d);//from w ww.ja va 2 s . com return; } try { ProcessingReport validate = VALIDATOR.validate(schema, Json.mapper.readTree(data)); if (id != null && validate.isSuccess() && d.containsKey("id") && id.equals(d.getString("id")) && !f.isComplete()) { f.complete(d); } else if (!f.isComplete()) { f.fail(new RepositoryException("Invalid Data")); } } catch (ProcessingException | IOException ex) { if (!f.isComplete()) { f.fail(ex); } } }, result -> { if (result.succeeded()) { updateWithoutValidate(id, result.result(), redissonBatch, resultHandler); } else { resultHandler.handle(Future.failedFuture(result.cause())); } }); }
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 ww w .j a v a 2 s .c om 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.github.jackygurui.vertxredissonrepository.repository.index.DefaultCompoundValueResolver.java
License:Apache License
@Override public String resolve(Object value, JsonObject root, String id, String fieldName, RedissonIndex index) { AtomicReference<String> s = new AtomicReference<>(); if (StringUtils.isBlank(index.valueField())) { s.set(value instanceof String ? (String) value : Json.encode(value)); } else {/*from ww w . j a v a2s . c o m*/ s.set(root.getString(index.valueField())); } Arrays.stream(index.compoundIndexFields()).forEach( e -> s.set(s.get().concat(RedisRepository.DEFAULT_SEPERATOR).concat(root.getValue(e).toString()))); return s.get().concat(RedisRepository.DEFAULT_SEPERATOR).concat(id); }
From source file:com.github.mcollovati.vertx.vaadin.VaadinVerticle.java
License:Open Source License
@Override public void start(Future<Void> startFuture) throws Exception { log.info("Starting vaadin verticle " + getClass().getName()); VaadinVerticleConfiguration vaadinVerticleConfiguration = getClass() .getAnnotation(VaadinVerticleConfiguration.class); JsonObject vaadinConfig = new JsonObject(); vaadinConfig.put("serviceName", this.deploymentID()); vaadinConfig.put("mountPoint", Optional.ofNullable(vaadinVerticleConfiguration) .map(VaadinVerticleConfiguration::mountPoint).orElse("/")); readUiFromEnclosingClass(vaadinConfig); readConfigurationAnnotation(vaadinConfig); vaadinConfig.mergeIn(config().getJsonObject("vaadin", new JsonObject())); String mountPoint = vaadinConfig.getString("mountPoint"); VertxVaadin vertxVaadin = createVertxVaadin(vaadinConfig); vaadinService = vertxVaadin.vaadinService(); HttpServerOptions serverOptions = new HttpServerOptions().setCompressionSupported(true); httpServer = vertx.createHttpServer(serverOptions); Router router = Router.router(vertx); router.mountSubRouter(mountPoint, vertxVaadin.router()); httpServer.websocketHandler(vertxVaadin.webSocketHandler()); httpServer.requestHandler(router::accept).listen(config().getInteger("httpPort", 8080)); serviceInitialized(vaadinService, router); log.info("Started vaadin verticle " + getClass().getName()); startFuture.complete();//from w w w .j a v a 2 s . c o m }
From source file:com.glencoesoftware.omero.ms.core.RedisCacheVerticle.java
License:Open Source License
@Override public void start() { log.info("Starting verticle"); JsonObject config = config().getJsonObject("redis-cache"); if (config != null) { String uri = config.getString("uri"); client = RedisClient.create(uri); connection = client.connect(new ByteArrayCodec()); }//from w w w . ja v a 2 s . c om vertx.eventBus().<String>consumer(REDIS_CACHE_GET_EVENT, event -> { get(event); }); vertx.eventBus().<JsonObject>consumer(REDIS_CACHE_SET_EVENT, event -> { set(event); }); }
From source file:com.glencoesoftware.omero.ms.core.RedisCacheVerticle.java
License:Open Source License
/** * Set a key in the cache.//from ww w . j av a 2 s . co m */ private void set(Message<JsonObject> message) { if (connection == null) { log.debug("Cache not enabled"); message.reply(null); return; } JsonObject data = message.body(); String key = data.getString("key"); byte[] value = data.getBinary("value"); if (key == null) { message.reply(null); return; } log.debug("Setting cache key: {}", key); RedisAsyncCommands<byte[], byte[]> commands = connection.async(); final StopWatch t0 = new Slf4JStopWatch("set"); // Binary retrieval, get(String) includes a UTF-8 step RedisFuture<String> future = commands.set(key.getBytes(), value); future.whenComplete((v, t) -> { try { if (t != null) { log.error("Exception while setting cache value", t); message.fail(500, t.getMessage()); return; } if (!"OK".equals(v)) { message.fail(500, "Non OK reply: " + v); return; } message.reply(null); } finally { t0.stop(); } }); }