Example usage for io.vertx.core.json JsonObject copy

List of usage examples for io.vertx.core.json JsonObject copy

Introduction

In this page you can find the example usage for io.vertx.core.json JsonObject copy.

Prototype

@Override
public JsonObject copy() 

Source Link

Document

Copy the JSON object

Usage

From source file:com.dangchienhsgs.redis.client.RedisOption.java

License:Open Source License

public RedisOption(JsonObject json) {
    this.json = json.copy();

    // process the binary support
    if (getEncoding().equalsIgnoreCase("iso-8859-1")) {
        setBinary(true);//from  w w  w.  ja  v a 2 s .c om
        return;
    }

    if (isBinary()) {
        setEncoding("iso-8859-1");
    }
}

From source file:de.elsibay.EbbTicketShowcase.java

License:Open Source License

@Override
public void start(Future<Void> startFuture) throws Exception {

    SessionStore sessionStore = LocalSessionStore.create(vertx);
    Router backendRouter = Router.router(vertx);
    backendRouter.route().handler(LoggerHandler.create(LoggerHandler.DEFAULT_FORMAT));
    CookieHandler cookieHandler = CookieHandler.create();
    SessionHandler sessionHandler = SessionHandler.create(sessionStore);
    // the CORS OPTION request must not set cookies
    backendRouter.get().handler(cookieHandler);
    backendRouter.get().handler(sessionHandler);
    backendRouter.post().handler(cookieHandler);
    backendRouter.post().handler(sessionHandler);

    // setup CORS
    CorsHandler corsHandler = CorsHandler.create("http(s)?://" + WEBSERVER_HOST + ":" + WEBSERVER_PORT)
            .allowCredentials(true).allowedHeader(HttpHeaders.ACCEPT.toString())
            .allowedHeader(HttpHeaders.ORIGIN.toString()).allowedHeader(HttpHeaders.AUTHORIZATION.toString())
            .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()).allowedHeader(HttpHeaders.COOKIE.toString())
            .exposedHeader(HttpHeaders.SET_COOKIE.toString()).allowedMethod(HttpMethod.POST)
            .allowedMethod(HttpMethod.PUT).allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.DELETE);

    // setup event bus bridge
    TicketEventbusBridge sebb = new TicketEventbusBridge(sessionStore);
    backendRouter.mountSubRouter("/eventbus", sebb.route(vertx));

    // dummy eventbus services
    vertx.eventBus().consumer("ping", (Message<JsonObject> msg) -> {
        msg.reply(new JsonObject().put("answer", "pong " + msg.body().getString("text", "")));
    });/*from ww  w  .j  a  va  2s .c om*/

    vertx.setPeriodic(5000, id -> {
        vertx.eventBus().send("topic", new JsonObject().put("timestamp", new Date().getTime()));
    });

    // session manager for login
    backendRouter.route("/api/*").handler(corsHandler);
    backendRouter.route("/api/*").method(HttpMethod.POST).method(HttpMethod.PUT).handler(BodyHandler.create());

    backendRouter.route("/api/session").handler((RoutingContext rc) -> {
        JsonObject user = rc.getBodyAsJson();
        String sessionId = rc.session().id();
        rc.session().put("user", user);
        rc.response().end(user.copy().put("sessionId", sessionId).encodePrettily());
    });

    // dummy ping REST service
    backendRouter.route("/api/ping").handler((RoutingContext rc) -> {
        JsonObject replyMsg = new JsonObject();
        replyMsg.put("timestamp", new Date().getTime());
        Cookie sessionCookie = rc.getCookie(SessionHandler.DEFAULT_SESSION_COOKIE_NAME);
        if (sessionCookie != null) {
            replyMsg.put("sessionId", sessionCookie.getValue());
        }
        rc.response().end(replyMsg.encode());
    });

    // start backend on one port
    vertx.createHttpServer().requestHandler(backendRouter::accept).listen(BACKENDSERVER_PORT,
            BACKENDSERVER_HOST, (AsyncResult<HttpServer> async) -> {
                System.out
                        .println(async.succeeded() ? "Backend Server started" : "Backend Server start FAILED");
            });

    // static files on other port
    Router staticFilesRouter = Router.router(vertx);
    staticFilesRouter.route("/*").handler(StaticHandler.create("src/main/www").setCachingEnabled(false));
    vertx.createHttpServer().requestHandler(staticFilesRouter::accept).listen(WEBSERVER_PORT, WEBSERVER_HOST,
            (AsyncResult<HttpServer> async) -> {
                System.out.println(async.succeeded()
                        ? "Web Server started\ngoto http://" + WEBSERVER_HOST + ":" + WEBSERVER_PORT + "/"
                        : "Web Server start FAILED");
            });
}

From source file:fr.wseduc.rack.controllers.RackController.java

License:Open Source License

private void copyFiles(final HttpServerRequest request, final JsonArray idsArray, final String folder,
        final UserInfos user, final String destinationCollection) {

    String criteria = "{ \"_id\" : { \"$in\" : " + idsArray.encode() + "}";
    criteria += ", \"to\" : \"" + user.getUserId() + "\" }";

    mongo.find(collection, new JsonObject(criteria), new Handler<Message<JsonObject>>() {

        private void persist(final JsonArray insert, int remains) {
            if (remains == 0) {
                mongo.insert(destinationCollection, insert, new Handler<Message<JsonObject>>() {
                    @Override/*from ww w.  jav  a  2s . c o  m*/
                    public void handle(Message<JsonObject> inserted) {
                        if ("ok".equals(inserted.body().getString("status"))) {
                            /* Increment quota */
                            long totalSize = 0l;
                            for (Object insertion : insert) {
                                JsonObject added = (JsonObject) insertion;
                                totalSize += added.getJsonObject("metadata", new JsonObject()).getLong("size",
                                        0l);
                            }
                            updateUserQuota(user.getUserId(), totalSize);
                            renderJson(request, inserted.body());
                        } else {
                            renderError(request, inserted.body());
                        }
                    }
                });
            }
        }

        @Override
        public void handle(Message<JsonObject> r) {
            JsonObject src = r.body();
            if ("ok".equals(src.getString("status")) && src.getJsonArray("results") != null) {
                final JsonArray origs = src.getJsonArray("results");
                final JsonArray insert = new JsonArray();
                final AtomicInteger number = new AtomicInteger(origs.size());

                emptySize(user, new Handler<Long>() {

                    @Override
                    public void handle(Long emptySize) {
                        long size = 0;

                        /* Get total file size */
                        for (Object o : origs) {
                            if (!(o instanceof JsonObject))
                                continue;
                            JsonObject metadata = ((JsonObject) o).getJsonObject("metadata");
                            if (metadata != null) {
                                size += metadata.getLong("size", 0l);
                            }
                        }
                        /* If total file size is too big (> quota left) */
                        if (size > emptySize) {
                            badRequest(request, "files.too.large");
                            return;
                        }

                        /* Process */
                        for (Object o : origs) {
                            JsonObject orig = (JsonObject) o;
                            final JsonObject dest = orig.copy();
                            String now = MongoDb.formatDate(new Date());
                            dest.remove("_id");
                            dest.remove("protected");
                            dest.remove("comments");
                            dest.put("application", WORKSPACE_NAME);

                            dest.put("owner", user.getUserId());
                            dest.put("ownerName", dest.getString("toName"));
                            dest.remove("to");
                            dest.remove("from");
                            dest.remove("toName");
                            dest.remove("fromName");

                            dest.put("created", now);
                            dest.put("modified", now);
                            if (folder != null && !folder.trim().isEmpty()) {
                                dest.put("folder", folder);
                            } else {
                                dest.remove("folder");
                            }
                            insert.add(dest);
                            final String filePath = orig.getString("file");

                            if (folder != null && !folder.trim().isEmpty()) {

                                //If the document has a new parent folder, replicate sharing rights
                                String parentName, parentFolder;
                                if (folder.lastIndexOf('_') < 0) {
                                    parentName = folder;
                                    parentFolder = folder;
                                } else if (filePath != null) {
                                    String[] splittedPath = folder.split("_");
                                    parentName = splittedPath[splittedPath.length - 1];
                                    parentFolder = folder;
                                } else {
                                    String[] splittedPath = folder.split("_");
                                    parentName = splittedPath[splittedPath.length - 2];
                                    parentFolder = folder.substring(0, folder.lastIndexOf("_"));
                                }

                                QueryBuilder parentFolderQuery = QueryBuilder.start("owner")
                                        .is(user.getUserId()).and("folder").is(parentFolder).and("name")
                                        .is(parentName);

                                mongo.findOne(collection, MongoQueryBuilder.build(parentFolderQuery),
                                        new Handler<Message<JsonObject>>() {
                                            @Override
                                            public void handle(Message<JsonObject> event) {
                                                if ("ok".equals(event.body().getString("status"))) {
                                                    JsonObject parent = event.body().getJsonObject("result");
                                                    if (parent != null && parent.getJsonArray("shared") != null
                                                            && parent.getJsonArray("shared").size() > 0)
                                                        dest.put("shared", parent.getJsonArray("shared"));

                                                    if (filePath != null) {
                                                        storage.copyFile(filePath, new Handler<JsonObject>() {
                                                            @Override
                                                            public void handle(JsonObject event) {
                                                                if (event != null && "ok"
                                                                        .equals(event.getString("status"))) {
                                                                    dest.put("file", event.getString("_id"));
                                                                    persist(insert, number.decrementAndGet());
                                                                }
                                                            }
                                                        });
                                                    } else {
                                                        persist(insert, number.decrementAndGet());
                                                    }
                                                } else {
                                                    renderJson(request, event.body(), 404);
                                                }
                                            }
                                        });

                            } else if (filePath != null) {
                                storage.copyFile(filePath, new Handler<JsonObject>() {

                                    @Override
                                    public void handle(JsonObject event) {
                                        if (event != null && "ok".equals(event.getString("status"))) {
                                            dest.put("file", event.getString("_id"));
                                            persist(insert, number.decrementAndGet());
                                        }
                                    }
                                });
                            } else {
                                persist(insert, number.decrementAndGet());
                            }
                        }
                    }
                });
            } else {
                notFound(request, src.toString());
            }
        }
    });

}

From source file:io.knotx.knot.service.service.ServiceEntry.java

License:Apache License

public ServiceEntry mergeParams(JsonObject defaultParams) {
    if (defaultParams != null) {
        this.params = defaultParams.copy().mergeIn(this.params);
    }//from www  .j  a v  a  2 s. c  om
    return this;
}

From source file:io.knotx.launcher.SystemPropsConfiguration.java

License:Apache License

/**
 * Update given JsonObject with the data provided in system property during Knotx start.<br>
 * In order to provide such overrides you can use two approches:
 * <ul>//from  w  w  w .ja v  a2 s .  c  o m
 * <li>-Dio.knotx.KnotxServer.httpPort=9999,
 * -Dio.knotx.KnotxServer.splitter.address=other-address - this will override one property
 * with the value given after '=' </li>
 * <li>-Dio.knotx.KnotxServer.splitter=file:/aaa/bb/cc.json - this will merge the given cc.json
 * file from the field specified</li>
 * </ul>
 *
 * @param descriptor - JsonObject with module descriptor
 * @return JsonObject - updated descriptor
 */
public JsonObject updateJsonObject(JsonObject descriptor) {
    final JsonObject object = descriptor.copy();
    envConfig.entrySet().forEach(entry -> {
        String[] path = StringUtils.split(entry.getKey(), ".");
        JsonObject element = object;
        for (int idx = 0; idx < path.length; idx++) {
            if (idx < path.length - 1) {
                if (element.containsKey(path[idx])) {
                    element = element.getJsonObject(path[idx]);
                } else {
                    throw new IllegalArgumentException("Wrong config override. There is no matching element "
                            + entry.getKey() + " in the configuration");
                }
            } else { //last
                if (entry.getValue().getObject() instanceof JsonObject) {
                    element.getJsonObject(path[idx]).mergeIn((JsonObject) entry.getValue().getObject());
                } else {
                    element.put(path[idx], entry.getValue().getObject());
                }
            }
        }
    });
    return object;
}

From source file:io.knotx.util.JsonObjectUtil.java

License:Apache License

public static JsonObject deepMerge(JsonObject source, JsonObject other) {
    JsonObject result = source.copy();
    other.forEach(entry -> {/*from  www .  j  a va 2s  . c o  m*/
        if (result.containsKey(entry.getKey())) {
            if (isKeyAJsonObject(result, entry.getKey()) && entry.getValue() instanceof JsonObject) {

                result.put(entry.getKey(),
                        deepMerge(source.getJsonObject(entry.getKey()), (JsonObject) entry.getValue()));
            } else { //Override whole key, if value is not jsonObject
                result.put(entry.getKey(), entry.getValue());
            }
        } else {
            result.put(entry.getKey(), entry.getValue());
        }
    });

    return result;
}

From source file:microservicerx.example.impl.MicroServiceRxImpl.java

@Override
public void cold(JsonObject document, Handler<AsyncResult<JsonObject>> resultHandler) {
    System.out.println("Processing...");
    Observable<JsonObject> observable;

    JsonObject result = document.copy();
    if (!document.containsKey("name")) {
        observable = Observable.error(new ServiceException(NO_NAME_ERROR, "No name in the document"));
    } else if (document.getString("name").isEmpty() || document.getString("name").equalsIgnoreCase("bad")) {
        observable = Observable.error(new ServiceException(BAD_NAME_ERROR, "Bad name in the document"));
    } else {/*from w ww . j ava 2s .co m*/
        result.put("approved", true);
        observable = Observable.just(result.copy().put("id", 0), result.copy().put("id", 1));
    }
    DistributedObservable dist = DistributedObservable.toDistributable(observable.map(j -> (Object) j), vertx);
    resultHandler.handle(Future.succeededFuture(dist.toJsonObject()));
}

From source file:microservicerx.example.impl.MicroServiceRxImpl.java

@Override
public void hot(JsonObject document, Handler<AsyncResult<JsonObject>> resultHandler) {
    System.out.println("Processing...");
    BehaviorSubject<Object> subject = BehaviorSubject.create();

    JsonObject result = document.copy();
    if (!document.containsKey("name")) {
        subject.onError(new ServiceException(NO_NAME_ERROR, "No name in the document"));
    } else if (document.getString("name").isEmpty() || document.getString("name").equalsIgnoreCase("bad")) {
        subject.onError(new ServiceException(BAD_NAME_ERROR, "Bad name in the document"));
    } else {/*from w  w w. j  a  v a 2 s  .c  o m*/
        Long timerId = vertx.setPeriodic(1000, l -> {
            JsonObject event = result.copy().put("approved", true).put("now", System.currentTimeMillis());
            subject.onNext(event);
        });

        vertx.setTimer(3 * 1000, l -> {
            vertx.cancelTimer(timerId);
            subject.onCompleted();
        });
    }
    DistributedObservable dist = DistributedObservable.toDistributable(subject, vertx);
    resultHandler.handle(Future.succeededFuture(dist.toJsonObject()));
}

From source file:org.eclipse.hono.tests.DeviceRegistryHttpClient.java

License:Open Source License

/**
 * Updates registration information for a device.
 * //  w  w w . j  ava  2  s. co m
 * @param tenantId The tenant that the device belongs to.
 * @param deviceId The identifier of the device.
 * @param data Additional properties to register with the device.
 * @param contentType The content type to set on the request.
 * @param expectedStatus The status code indicating a successful outcome.
 * @return A future indicating the outcome of the operation.
 *         The future will succeed if the response contained the expected status code.
 *         Otherwise the future will fail with a {@link ServiceInvocationException}.
 * @throws NullPointerException if the tenant is {@code null}.
 */
public Future<Void> updateDevice(final String tenantId, final String deviceId, final JsonObject data,
        final String contentType, final int expectedStatus) {

    Objects.requireNonNull(tenantId);
    final String requestUri = String.format(TEMPLATE_URI_REGISTRATION_INSTANCE, tenantId, deviceId);
    final JsonObject requestJson = data.copy();
    requestJson.put(RegistrationConstants.FIELD_PAYLOAD_DEVICE_ID, deviceId);
    return httpClient.update(requestUri, requestJson, contentType, status -> status == expectedStatus);
}

From source file:org.entcore.auth.adapter.UserInfoAdapterV1_0Json.java

License:Open Source License

protected JsonObject getCommonFilteredInfos(JsonObject info, String clientId) {
    JsonObject filteredInfos = info.copy();
    String type = Utils.getOrElse(types.get(info.getString("type", "")), "");
    filteredInfos.put("type", type);
    filteredInfos.remove("cache");
    if (filteredInfos.getString("level") == null) {
        filteredInfos.put("level", "");
    } else if (filteredInfos.getString("level").contains("$")) {
        String[] level = filteredInfos.getString("level").split("\\$");
        filteredInfos.put("level", level[level.length - 1]);
    }//from   www. j av  a  2 s.c  o  m
    if (clientId != null && !clientId.trim().isEmpty()) {
        JsonArray classNames = filteredInfos.getJsonArray("classNames");
        filteredInfos.remove("classNames");
        JsonArray structureNames = filteredInfos.getJsonArray("structureNames");
        filteredInfos.remove("structureNames");
        filteredInfos.remove("federated");
        if (classNames != null && classNames.size() > 0) {
            filteredInfos.put("classId", classNames.getString(0));
        }
        if (structureNames != null && structureNames.size() > 0) {
            filteredInfos.put("schoolName", structureNames.getString(0));
        }
        filteredInfos.remove("functions");
        filteredInfos.remove("groupsIds");
        filteredInfos.remove("structures");
        filteredInfos.remove("classes");
        filteredInfos.remove("apps");
        filteredInfos.remove("authorizedActions");
        filteredInfos.remove("children");
        JsonArray authorizedActions = new fr.wseduc.webutils.collections.JsonArray();
        for (Object o : info.getJsonArray("authorizedActions")) {
            JsonObject j = (JsonObject) o;
            String name = j.getString("name");
            if (name != null && name.startsWith(clientId + "|")) {
                authorizedActions.add(j);
            }
        }
        if (authorizedActions.size() > 0) {
            filteredInfos.put("authorizedActions", authorizedActions);
        }
    }
    return filteredInfos;
}