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

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

Introduction

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

Prototype

public JsonObject getJsonObject(String key) 

Source Link

Document

Get the JsonObject value with the specified key

Usage

From source file:examples.VertxAmqpBridgeExamples.java

License:Apache License

@SuppressWarnings("unused")
public void example4(JsonObject amqpMsgPayload) {
    // Check the application properties section was present before use, it may not be
    JsonObject appProps = amqpMsgPayload.getJsonObject("application_properties");
    if (appProps != null) {
        Object propValue = appProps.getValue("propertyName");
    }/*from   w  w  w .ja  v  a  2  s  . co  m*/
}

From source file:fr.pjthin.vertx.client.UserDaoVertxProxyHandler.java

License:Apache License

public void handle(Message<JsonObject> msg) {
    try {//from  w w w  .  j  a v  a 2  s.  c o m
        JsonObject json = msg.body();
        String action = msg.headers().get("action");
        if (action == null) {
            throw new IllegalStateException("action not specified");
        }
        accessed();
        switch (action) {

        case "save": {
            service.save(
                    json.getJsonObject("newUser") == null ? null
                            : new fr.pjthin.vertx.client.data.User(json.getJsonObject("newUser")),
                    createHandler(msg));
            break;
        }
        case "findAll": {
            service.findAll(res -> {
                if (res.failed()) {
                    msg.fail(-1, res.cause().getMessage());
                } else {
                    msg.reply(new JsonArray(
                            res.result().stream().map(User::toJson).collect(Collectors.toList())));
                }
            });
            break;
        }
        case "findUserByLogin": {
            service.findUserByLogin((java.lang.String) json.getValue("login"), res -> {
                if (res.failed()) {
                    msg.fail(-1, res.cause().getMessage());
                } else {
                    msg.reply(res.result() == null ? null : res.result().toJson());
                }
            });
            break;
        }
        case "deleteByLogin": {
            service.deleteByLogin((java.lang.String) json.getValue("login"), createHandler(msg));
            break;
        }
        case "close": {
            service.close();
            close();
            break;
        }
        default: {
            throw new IllegalStateException("Invalid action: " + action);
        }
        }
    } catch (Throwable t) {
        msg.fail(-1, t.getMessage());
        throw t;
    }
}

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

License:Open Source License

/**
 * Post a new document to other people's rack folder.
 * @param request Client request containing a list of user ids belonging to the receivers and the file.
 *///from  ww  w. j a va 2s. co  m
@Post("")
@SecuredAction(send)
public void postRack(final HttpServerRequest request) {
    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override
        public void handle(final UserInfos userInfos) {

            if (userInfos == null) {
                badRequest(request);
                return;
            }

            request.setExpectMultipart(true);
            final Buffer fileBuffer = Buffer.buffer();
            final JsonObject metadata = new JsonObject();

            /* Upload file */
            request.uploadHandler(getUploadHandler(fileBuffer, metadata, request));

            /* After upload */
            request.endHandler(new Handler<Void>() {
                @Override
                public void handle(Void v) {
                    String users = request.formAttributes().get("users");
                    if (users == null) {
                        badRequest(request);
                        return;
                    }

                    String[] userIds = users.split(",");

                    final AtomicInteger countdown = new AtomicInteger(userIds.length);
                    final AtomicInteger success = new AtomicInteger(0);
                    final AtomicInteger failure = new AtomicInteger(0);

                    /* Final handler - called after each attempt */
                    final Handler<Boolean> finalHandler = new Handler<Boolean>() {
                        @Override
                        public void handle(Boolean event) {
                            if (event == null || !event)
                                failure.addAndGet(1);
                            else
                                success.addAndGet(1);
                            if (countdown.decrementAndGet() == 0) {
                                JsonObject result = new JsonObject();
                                result.put("success", success.get());
                                result.put("failure", failure.get());
                                renderJson(request, result);
                            }
                        }
                    };

                    for (final String to : userIds) {
                        /* Query user and check existence */
                        String query = "MATCH (n:User) " + "WHERE n.id = {id} "
                                + "RETURN count(n) as nb, n.displayName as username";
                        Map<String, Object> params = new HashMap<>();
                        params.put("id", to);

                        Handler<Message<JsonObject>> existenceHandler = new Handler<Message<JsonObject>>() {
                            @Override
                            public void handle(Message<JsonObject> res) {
                                JsonArray result = res.body().getJsonArray("result");

                                if (!"ok".equals(res.body().getString("status")) || 1 != result.size()
                                        || 1 != result.getJsonObject(0).getInteger("nb")) {
                                    finalHandler.handle(false);
                                    return;
                                }

                                /* Pre write rack document fields */
                                final JsonObject doc = new JsonObject();
                                doc.put("to", to);
                                doc.put("toName", result.getJsonObject(0).getString("username"));
                                doc.put("from", userInfos.getUserId());
                                doc.put("fromName", userInfos.getUsername());
                                String now = dateFormat.format(new Date());
                                doc.put("sent", now);

                                /* Rack collection saving */
                                final Handler<JsonObject> rackSaveHandler = new Handler<JsonObject>() {
                                    @Override
                                    public void handle(JsonObject uploaded) {
                                        if (uploaded == null || !"ok".equals(uploaded.getString("status"))) {
                                            finalHandler.handle(false);
                                        } else {
                                            addAfterUpload(uploaded.put("metadata", metadata), doc,
                                                    request.params().get("name"),
                                                    request.params().get("application"),
                                                    request.params().getAll("thumbnail"),
                                                    new Handler<Message<JsonObject>>() {
                                                        @Override
                                                        public void handle(Message<JsonObject> res) {
                                                            if ("ok".equals(res.body().getString("status"))) {
                                                                JsonObject params = new JsonObject()
                                                                        .put("uri",
                                                                                "/userbook/annuaire#"
                                                                                        + doc.getString("from"))
                                                                        .put("resourceUri", pathPrefix)
                                                                        .put("username",
                                                                                doc.getString("fromName"))
                                                                        .put("documentName",
                                                                                doc.getString("name"));
                                                                List<String> receivers = new ArrayList<>();
                                                                receivers.add(doc.getString("to"));

                                                                JsonObject pushNotif = new JsonObject()
                                                                        .put("title",
                                                                                "rack.push.notif.rack-post")
                                                                        .put("body",
                                                                                I18n.getInstance().translate(
                                                                                        "rack.push.notif.rack-post.body",
                                                                                        getHost(request),
                                                                                        I18n.acceptLanguage(
                                                                                                request),
                                                                                        doc.getString(
                                                                                                "fromName"),
                                                                                        doc.getString("name")));
                                                                params.put("pushNotif", pushNotif);

                                                                timelineHelper.notifyTimeline(request,
                                                                        "rack.rack-post", userInfos, receivers,
                                                                        userInfos.getUserId()
                                                                                + System.currentTimeMillis()
                                                                                + "postrack",
                                                                        null, params, true);
                                                                finalHandler.handle(true);
                                                            } else {
                                                                finalHandler.handle(false);
                                                            }
                                                        }
                                                    });
                                        }
                                    }
                                };

                                /* Get user quota & check */
                                getUserQuota(to, new Handler<JsonObject>() {
                                    @Override
                                    public void handle(JsonObject j) {
                                        if (j == null || "error".equals(j.getString("status"))) {
                                            finalHandler.handle(false);
                                            return;
                                        }

                                        long emptySize = 0l;
                                        long quota = j.getLong("quota", 0l);
                                        long storage = j.getLong("storage", 0l);
                                        emptySize = quota - storage;
                                        if (emptySize < metadata.getLong("size", 0l)) {
                                            finalHandler.handle(false);
                                            return;
                                        }
                                        //Save file
                                        RackController.this.storage.writeBuffer(fileBuffer,
                                                metadata.getString("content-type"), metadata.getString("name"),
                                                rackSaveHandler);
                                    }
                                });

                            }
                        };
                        Neo4j.getInstance().execute(query, params, existenceHandler);
                    }
                }
            });
        }
    });
}

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

License:Open Source License

private boolean inlineDocumentResponse(JsonObject doc, String application) {
    JsonObject metadata = doc.getJsonObject("metadata");
    String storeApplication = doc.getString("application");
    return metadata != null && !"WORKSPACE".equals(storeApplication) && ("image/jpeg".equals(
            metadata.getString("content-type")) || "image/gif".equals(metadata.getString("content-type"))
            || "image/png".equals(metadata.getString("content-type"))
            || "image/tiff".equals(metadata.getString("content-type"))
            || "image/vnd.microsoft.icon".equals(metadata.getString("content-type"))
            || "image/svg+xml".equals(metadata.getString("content-type"))
            || ("application/octet-stream".equals(metadata.getString("content-type")) && application != null));
}

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

License:Open Source License

private void deleteFile(final HttpServerRequest request, final String owner) {
    final String id = request.params().get("id");
    rackService.getRack(id, new Handler<Either<String, JsonObject>>() {
        @Override//from   w w w  .  ja  va  2 s  . c  o m
        public void handle(Either<String, JsonObject> event) {
            if (event.isRight()) {
                final JsonObject result = event.right().getValue();

                String file = result.getString("file");
                Set<Entry<String, Object>> thumbnails = new HashSet<Entry<String, Object>>();
                if (result.containsKey("thumbnails")) {
                    thumbnails = result.getJsonObject("thumbnails").getMap().entrySet();
                }

                storage.removeFile(file, new Handler<JsonObject>() {
                    @Override
                    public void handle(JsonObject event) {
                        if (event != null && "ok".equals(event.getString("status"))) {
                            rackService.deleteRack(id, new Handler<Either<String, JsonObject>>() {
                                @Override
                                public void handle(Either<String, JsonObject> deletionEvent) {
                                    if (deletionEvent.isRight()) {
                                        JsonObject deletionResult = deletionEvent.right().getValue();
                                        long size = -1l * result.getJsonObject("metadata", new JsonObject())
                                                .getLong("size", 0l);
                                        updateUserQuota(owner, size);
                                        renderJson(request, deletionResult, 204);
                                    } else {
                                        badRequest(request, deletionEvent.left().getValue());
                                    }
                                }
                            });
                        } else {
                            renderError(request, event);
                        }
                    }
                });

                //Delete thumbnails
                for (final Entry<String, Object> thumbnail : thumbnails) {
                    storage.removeFile(thumbnail.getValue().toString(), new Handler<JsonObject>() {
                        @Override
                        public void handle(JsonObject event) {
                            if (event == null || !"ok".equals(event.getString("status"))) {
                                logger.error("[gridfsRemoveFile] Error while deleting thumbnail " + thumbnail);
                            }
                        }
                    });
                }

            } else {
                JsonObject error = new JsonObject().put("error", event.left().getValue());
                Renders.renderJson(request, error, 400);
            }
        }
    });
}

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

License:Open Source License

private void addAfterUpload(final JsonObject uploaded, final JsonObject doc, String name, String application,
        final List<String> thumbs, final Handler<Message<JsonObject>> handler) {
    //Write additional fields in the document
    doc.put("name", getOrElse(name, uploaded.getJsonObject("metadata").getString("filename"), false));
    doc.put("metadata", uploaded.getJsonObject("metadata"));
    doc.put("file", uploaded.getString("_id"));
    doc.put("application", getOrElse(application, WORKSPACE_NAME));
    //Save document to mongo
    mongo.save(collection, doc, new Handler<Message<JsonObject>>() {
        @Override//from  w w w  . ja v  a  2  s . com
        public void handle(Message<JsonObject> res) {
            if ("ok".equals(res.body().getString("status"))) {
                Long size = doc.getJsonObject("metadata", new JsonObject()).getLong("size", 0l);
                updateUserQuota(doc.getString("to"), size);
                createThumbnailIfNeeded(collection, uploaded, res.body().getString("_id"), null, thumbs);
            }
            if (handler != null) {
                handler.handle(res);
            }
        }
    });
}

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

License:Open Source License

private boolean isImage(JsonObject doc) {
    if (doc == null) {
        return false;
    }// w  ww  . j  a  va  2  s .  c  om
    JsonObject metadata = doc.getJsonObject("metadata");
    return metadata != null && ("image/jpeg".equals(metadata.getString("content-type"))
            || "image/gif".equals(metadata.getString("content-type"))
            || "image/png".equals(metadata.getString("content-type"))
            || "image/tiff".equals(metadata.getString("content-type")));
}

From source file:hu.elte.ik.robotika.futar.vertx.backend.verticle.HTTPVerticle.java

@Override
public void start() {

    init();/*  www .  j  a v  a 2  s .co m*/
    HttpServer http = vertx.createHttpServer();
    Router router = Router.router(vertx);

    // Setup websocket connection handling
    router.route("/eventbus/*").handler(eventBusHandler());

    router.route("/ws").handler(this::handleWebSocketConnection);

    // Handle robot position data
    router.route("/api/robotposition/:data").handler(this::handleRobotPositionData);

    // Setup http session auth handling
    router.route().handler(CookieHandler.create());
    router.route().handler(BodyHandler.create());
    router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));

    // Simple auth service which uses a properties file for user/role info
    AuthProvider authProvider = ShiroAuth.create(vertx, ShiroAuthRealmType.PROPERTIES, new JsonObject());

    // We need a user session handler too to make sure the user is stored in
    // the session between requests
    router.route().handler(UserSessionHandler.create(authProvider));

    // Any requests to URI starting '/rest/' require login
    router.route("/rest/*").handler(SimpleAuthHandler.create(authProvider));

    // Serve the static private pages from directory 'rest'
    // user/getAll TEST page
    router.route("/rest/user/getAll").handler(this::getAllUser);

    // Preload
    router.route("/rest/info").handler(this::getInfo);

    router.route("/loginhandler").handler(SimpleLoginHandler.create(authProvider));

    router.route("/logout").handler(context -> {
        context.clearUser();
        // Status OK
        context.response().setStatusCode(HttpStatus.SC_OK).end();
    });

    router.route().handler(StaticHandler.create().setWebRoot(webRoot));
    http.websocketHandler(ws -> {
        String id = java.util.UUID.randomUUID().toString();
        ws.handler(buffer -> {
            try {
                JsonObject response = new JsonObject(buffer.toString());
                if (response.getString("action") != null && response.getString("action").equals("login.robot")
                        && sockets.get(id) == null) {
                    log.info("robot logged in:" + id);
                    sockets.put(id, ws);
                    JsonObject pb = new JsonObject();
                    pb.put("robotId", id);
                    vertx.eventBus().publish("new.robot", Json.encode(pb));
                } else if (response.getString("action") != null
                        && response.getString("action").equals("found.bluetooth")) {
                    log.info("found.bluetooth");
                    JsonObject pb = response.getJsonObject("data");
                    if (placedBTDevices.get(pb.getString("address")) == null
                            && newBTDevices.get(pb.getString("address")) == null) {
                        JsonObject data = new JsonObject(Json.encode(pb));
                        data.remove("rssi");
                        newBTDevices.put(pb.getString("address"), data);
                        log.info("New bt device: " + buffer);
                        vertx.eventBus().publish("new.bt.device", Json.encode(data));
                    }

                    btData.get(id).remove(pb.getString("address"));

                    log.info("Update bt data: " + id + " " + pb.getString("address") + " "
                            + pb.getInteger("rssi"));
                    double x = (pb.getInteger("rssi") - (-40.0)) / ((-10.0) * 2.0);
                    log.info("sub calc res: " + x);
                    double d = Math.pow(10.0, x);
                    //RSSI (dBm) = -10n log10(d) + A
                    log.info("the calculated distance is around: " + d + "m");
                    btData.get(id).put(pb.getString("address"), d * 27);
                } else if (response.getString("action") != null
                        && response.getString("action").equals("start.bluetooth.scan")) {
                    log.info("start.bluetooth.scan");
                    btData.remove(id);
                    btData.put(id, new LinkedHashMap<String, Double>());

                } else if (response.getString("action") != null
                        && response.getString("action").equals("finished.bluetooth.scan")) {
                    log.info("finished.bluetooth.scan");
                    if (btData.get(id).size() >= 3) {
                        double x0 = 0, y0 = 0, r0 = 0, x1 = 0, y1 = 0, r1 = 0, x2 = 0, y2 = 0, r2 = 0;
                        int i = 0;
                        for (Map.Entry<String, Double> entry : btData.get(id).entrySet()) {
                            String key = entry.getKey();
                            JsonObject placedBT = placedBTDevices.get(key);
                            if (placedBT == null) {
                                log.info("placedBT is null, the key was: " + key);
                                continue;
                            }
                            double value = entry.getValue();
                            if (i == 0) {

                                x0 = placedBT.getDouble("x");
                                y0 = placedBT.getDouble("y");
                                r0 = value;
                                log.info("fill first circle x: " + x0 + " y: " + y0 + " r: " + r0);
                            } else if (i == 1) {

                                x1 = placedBT.getDouble("x");
                                y1 = placedBT.getDouble("y");
                                r1 = value;
                                log.info("fill second circle x: " + x1 + " y: " + y1 + " r: " + r1);
                            } else if (i == 2) {

                                x2 = placedBT.getDouble("x");
                                y2 = placedBT.getDouble("y");
                                r2 = value;
                                log.info("fill third circle x: " + x2 + " y: " + y2 + " r: " + r2);
                            } else {
                                break;
                            }
                            i++;
                        }

                        if (i == 3) {
                            log.info("start calculation");
                            if (calculateThreeCircleIntersection(x0, y0, r0, x1, y1, r1, x2, y2, r2, id)) {
                                log.info("solved circle intersection");
                            } else {
                                log.info("cannot solve circle interseciton");
                            }
                        } else {
                            log.info("there was not enough BT device: " + i);
                        }

                    } else {
                        log.info("There is not enough BT data to calculate the location of the robot.");
                    }
                }

                log.info("got the following message from " + id + ": " + Json.encode(response));

            } catch (Exception e) {
                log.info("Cannot process the following buffer: " + buffer);
                log.error(e);
            }
        });
        ws.endHandler(e -> {
            JsonObject response = new JsonObject();
            response.put("robotId", id);
            vertx.eventBus().publish("logout.robot", Json.encode(response));
            sockets.remove(id);
            positionedRobots.remove(id);
            btData.remove(id);
            log.info("The following robot logged out: " + id);
        });
    }).requestHandler(router::accept).listen(Integer.getInteger("http.port"),
            System.getProperty("http.address", "0.0.0.0"));
}

From source file:io.apiman.gateway.engine.vertx.polling.fetchers.auth.AbstractOAuth2Base.java

License:Apache License

protected static void createOrDescend(JsonObject root, Deque<String> keyPath, String value) {
    // If there are still key-path elements remaining to traverse.
    if (keyPath.size() > 1) {
        // If there's no object already at this key-path create a new JsonObject.
        if (root.getJsonObject(keyPath.peek()) == null) {
            JsonObject newJson = new JsonObject();
            String val = keyPath.pop();
            root.put(val, newJson);
            createOrDescend(newJson, keyPath, value);
        } else { // If there's already an existing object on key-path, grab it and traverse.
            createOrDescend(root.getJsonObject(keyPath.pop()), keyPath, value);
        }//from  www .  ja  v a  2 s  .c  o  m
    } else { // Set the value.
        Boolean boolObj = BooleanUtils.toBooleanObject(value);
        if (boolObj != null) {
            root.put(keyPath.pop(), boolObj);
        } else if (StringUtils.isNumeric(value)) {
            root.put(keyPath.pop(), Long.parseLong(value));
        } else {
            root.put(keyPath.pop(), value);
        }
    }
}

From source file:io.apiman.gateway.platforms.vertx3.common.config.VertxEngineConfig.java

License:Apache License

protected Map<String, String> getConfig(JsonObject obj, String prefix) {
    // First, check whether there's something interesting in System properties.
    Map<String, String> mfp = getConfigMapFromProperties("apiman-gateway." + prefix);

    if (mfp != null && !mfp.isEmpty()) { // TODO
        return mfp;
    }//from   www.j a  v a  2 s .  c  o m
    return toFlatStringMap(obj.getJsonObject(prefix, new JsonObject()).getJsonObject(GATEWAY_CONFIG));
}