Example usage for io.vertx.core.json Json encode

List of usage examples for io.vertx.core.json Json encode

Introduction

In this page you can find the example usage for io.vertx.core.json Json encode.

Prototype

public static String encode(Object obj) throws EncodeException 

Source Link

Document

Encode a POJO to JSON using the underlying Jackson mapper.

Usage

From source file:com.company.vertxstarter.api.PersonResource.java

public void get(RoutingContext e) {
    QueryParam params = new QueryParam(e.request().query());
    if (!params.isValid()) {
        e.fail(params.error());/*from  ww w .j a va2  s  . c om*/
        return;
    }

    Set<SortExpression> sortExp = params.getSortExpressions();
    Set<FilterExpression> filterExp = params.getFilterExpressions();

    List<Person> people = new ArrayList<>();
    people.add(new Person("Thomas", "Peroutka"));
    people.add(new Person("Lisa", "Grtner"));
    people.add(new Person("Felix", "Wagner"));
    people.add(new Person("Kathi", "Schrank"));
    people.add(new Person("Omar", "Arrafeh"));
    people.add(new Person("Tim", "Schwarz"));
    people.add(new Person("Tom", "Schwarz"));
    people.add(new Person("Adriana", "Krug"));
    people.add(new Person("Lisa", "Moller"));
    people.add(new Person("Stefan", "Moller"));
    people.add(new Person("Anna", "Gschaider"));

    HttpServerResponse response = e.response();
    response.end(Json.encode(people));

    /*
    JsonObject postgreSQLClientConfig = new JsonObject();
    postgreSQLClientConfig.put("host", "localhost");
    postgreSQLClientConfig.put("port", 5432);
    postgreSQLClientConfig.put("username", "postgres");
    postgreSQLClientConfig.put("database", "postgres");
    AsyncSQLClient client = PostgreSQLClient.createShared(e.vertx(), postgreSQLClientConfig);
            
    client.getConnection(res -> {
    if (res.succeeded()) {
            
        SQLConnection connection = res.result();
                
        connection.close();
        client.close();
                
        HttpServerResponse response = e.response();
        response.end("{\"message\":\"success\"}");
    } else {
        HttpServerResponse response = e.response();
        response.end("{\"message\":\"failed\"}");
    }
    });
    */

}

From source file:com.github.bpark.companion.SentimentVerticle.java

License:Apache License

private Observable<Void> saveMessage(String id, SentimentAnalysis sentimentAnalysis) {
    return vertx.sharedData().<String, String>rxGetClusterWideMap(id)
            .flatMap(map -> map.rxPut(SENTIMENT_KEY, Json.encode(sentimentAnalysis))).toObservable();
}

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();/*from w w w  . j a v a2  s.  co m*/
    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);
        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 ensureUniqueAndIndexingBlocking(String id, JsonObject data, Boolean isNew,
        AsyncResultHandler<String> resultHandler) {
    Async.waterfall().<String>task(t -> {
        RBatch batch = redissonOther.createBatch();
        ArrayList<String> pList = new ArrayList();
        try {/*from  ww w .  j  a  v  a 2  s.c om*/
            prepareEnsureUnique(id, data, batch, pList, null);
        } catch (RepositoryException ex) {
            t.handle(Future.failedFuture(ex));
            return;
        }
        if (pList.isEmpty()) {
            t.handle(Future.succeededFuture());
            return;
        }
        batch.executeAsync().addListener(future -> {
            if (future.isSuccess() && future.get() != null) {
                List<String> result = (List<String>) future.get();
                Stream<String> filter = pList.stream().filter(
                        p -> result.get(pList.indexOf(p)) != null && !result.get(pList.indexOf(p)).equals(id));//uniques are ensured by using putIfAbsent and all results should be null or itself to indicate no violation.
                Object[] filterArray = filter.toArray();
                if (filterArray.length != 0) {
                    t.handle(Future.succeededFuture(
                            new JsonObject().put("uniqueViolation", Json.encode(filterArray)).encode()));
                    //now undo these things.
                    ArrayList<String> undoList = pList.stream()
                            .filter(p -> result.get(pList.indexOf(p)) == null
                                    || result.get(pList.indexOf(p)).equals(id))
                            .collect(Collectors.toCollection(ArrayList::new));
                    Async.<Void>waterfall().<Void>task(task -> {
                        RBatch b = redissonOther.createBatch();
                        try {
                            prepareUndoUnique(id, data, b, undoList, null);
                        } catch (RepositoryException ex) {
                            task.handle(Future.failedFuture(ex));
                        }
                        b.executeAsync().addListener(fu -> {
                            task.handle(fu.isSuccess() ? Future.succeededFuture((Void) fu.get())
                                    : Future.failedFuture(fu.cause()));
                        });
                    }).run(run -> {
                        logger.debug("Parallel undo indexing [id: " + id + "] "
                                + (run.succeeded() ? "successed." : "failed."));
                    });
                } else {
                    t.handle(Future.succeededFuture());
                }
            } else {
                t.handle(Future.failedFuture(!future.isSuccess() ? future.cause().fillInStackTrace()
                        : new RepositoryException("No unique check result returned")));
            }
        });
    }).<String>task((violations, t) -> {
        if (violations != null) {
            t.handle(Future.failedFuture(violations));
            return;
        } else {
            t.handle(Future.succeededFuture());
        }
        //parallel indexing
        Async.<Void>waterfall().<T>task(task -> {
            if (!isNew) {
                fetch(id, Boolean.TRUE, task);
            } else {
                task.handle(Future.succeededFuture(null));
            }
        }).<Void>task((r, task) -> {
            reIndex(id, r, data, isNew, ri -> {
                task.handle(
                        ri.succeeded() ? Future.succeededFuture(ri.result()) : Future.failedFuture(ri.cause()));
            });
        }).run(run -> {
            logger.debug("Parallel Indexing [id: " + id + "] " + (run.succeeded() ? "successed." : "failed."),
                    run.cause());
        });
    }).run(resultHandler);

}

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 {//  w  w w  . ja  va 2s.co 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.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

License:Apache License

private void finishPersist(String id, JsonObject data, RBatch batch,
        Handler<AsyncResult<Boolean>> resultHandler) {
    vertx.executeBlocking(f -> {// w w w.  j  ava 2  s .  c  om
        batch.executeAsync().addListener(future -> {
            if (future.isSuccess()) {
                if (future.get() != null && !f.isComplete()) {
                    f.complete((Boolean) ((List) future.get()).get(0));
                    logger.debug(
                            "[" + getStorageKey() + "] Persist Success : " + id + " - " + Json.encode(data));
                } else if (!f.isComplete()) {
                    f.fail(new RepositoryException("No save result returned"));
                    logger.debug(
                            "[" + getStorageKey() + "] Persist Failure : " + id + " - " + Json.encode(data),
                            future.cause());
                }
            } else if (!f.isComplete()) {
                f.fail(new RepositoryException(future.cause()));
                logger.debug("[" + getStorageKey() + "] Persist Failure : " + id + " - " + Json.encode(data),
                        future.cause());
            }
        });
    }, resultHandler);

}

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 {//ww w  . j  a  v a2 s  . co  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.jackygurui.vertxredissonrepository.repository.index.DefaultValueResolver.java

License:Apache License

@Override
public String resolve(T value, JsonObject root, String id, String fieldName, RedissonIndex index) {
    return Json.encode(value);
}

From source file:com.glencoesoftware.omero.ms.thumbnail.ThumbnailMicroserviceVerticle.java

License:Open Source License

/**
 * Render thumbnail event handler. Responds with a <code>image/jpeg</code>
 * body on success based on the <code>longestSide</code> and
 * <code>imageId</code> encoded in the URL or HTTP 404 if the {@link Image}
 * does not exist or the user does not have permissions to access it.
 * @param event Current routing context.
 *//*from   w w w  .  j av  a 2  s . co m*/
private void renderThumbnail(RoutingContext event) {
    final HttpServerRequest request = event.request();
    final HttpServerResponse response = event.response();
    final Map<String, Object> data = new HashMap<String, Object>();
    data.put("longestSide",
            Optional.ofNullable(request.getParam("longestSide")).map(Integer::parseInt).orElse(96));
    data.put("imageId", Long.parseLong(request.getParam("imageId")));
    data.put("omeroSessionKey", event.get("omero.session_key"));
    data.put("renderingDefId",
            Optional.ofNullable(request.getParam("rdefId")).map(Long::parseLong).orElse(null));

    vertx.eventBus().<byte[]>send(ThumbnailVerticle.RENDER_THUMBNAIL_EVENT, Json.encode(data), result -> {
        try {
            if (result.failed()) {
                Throwable t = result.cause();
                int statusCode = 404;
                if (t instanceof ReplyException) {
                    statusCode = ((ReplyException) t).failureCode();
                }
                response.setStatusCode(statusCode);
                return;
            }
            byte[] thumbnail = result.result().body();
            response.headers().set("Content-Type", "image/jpeg");
            response.headers().set("Content-Length", String.valueOf(thumbnail.length));
            response.write(Buffer.buffer(thumbnail));
        } finally {
            response.end();
            log.debug("Response ended");
        }
    });
}

From source file:com.glencoesoftware.omero.ms.thumbnail.ThumbnailMicroserviceVerticle.java

License:Open Source License

/**
 * Get thumbnails event handler. Responds with a JSON dictionary of Base64
 * encoded <code>image/jpeg</code> thumbnails keyed by {@link Image}
 * identifier. Each dictionary value is prefixed with
 * <code>data:image/jpeg;base64,</code> so that it can be used with
 * <a href="http://caniuse.com/#feat=datauri">data URIs</a>.
 * @param event Current routing context.
 *//* www .  j  a v  a  2s.c  om*/
private void getThumbnails(RoutingContext event) {
    final HttpServerRequest request = event.request();
    final HttpServerResponse response = event.response();
    final Map<String, Object> data = new HashMap<String, Object>();
    final String callback = request.getParam("callback");
    data.put("longestSide",
            Optional.ofNullable(request.getParam("longestSide")).map(Integer::parseInt).orElse(96));
    data.put("imageIds",
            request.params().getAll("id").stream().map(Long::parseLong).collect(Collectors.toList()).toArray());
    data.put("omeroSessionKey", event.get("omero.session_key"));

    vertx.eventBus().<String>send(ThumbnailVerticle.GET_THUMBNAILS_EVENT, Json.encode(data), result -> {
        try {
            if (result.failed()) {
                Throwable t = result.cause();
                int statusCode = 404;
                if (t instanceof ReplyException) {
                    statusCode = ((ReplyException) t).failureCode();
                }
                response.setStatusCode(statusCode);
                return;
            }
            String json = result.result().body();
            String contentType = "application/json";
            if (callback != null) {
                json = String.format("%s(%s);", callback, json);
                contentType = "application/javascript";
            }
            response.headers().set("Content-Type", contentType);
            response.headers().set("Content-Length", String.valueOf(json.length()));
            response.write(json);
        } finally {
            response.end();
            log.debug("Response ended");
        }
    });
}