List of usage examples for io.vertx.core.json JsonObject put
public JsonObject put(String key, Object value)
From source file:fr.wseduc.rack.controllers.RackController.java
License:Open Source License
private void updateUserQuota(final String userId, long size) { JsonObject message = new JsonObject(); message.put("action", "updateUserQuota"); message.put("userId", userId); message.put("size", size); message.put("threshold", threshold); eb.send(QUOTA_BUS_ADDRESS, message, new Handler<AsyncResult<Message<JsonObject>>>() { @Override/*from w w w . j ava 2 s . c o m*/ public void handle(AsyncResult<Message<JsonObject>> reply) { JsonObject obj = reply.result().body(); UserUtils.addSessionAttribute(eb, userId, "storage", obj.getLong("storage"), null); if (obj.getBoolean("notify", false)) { notifyEmptySpaceIsSmall(userId); } } }); }
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 w w w . j a va 2s .c om*/ 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: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.j av a2s .c om 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 void createThumbnails(List<String> thumbs, JsonObject srcFile, final String collection, final String documentId) { Pattern size = Pattern.compile("([0-9]+)x([0-9]+)"); JsonArray outputs = new JsonArray(); for (String thumb : thumbs) { Matcher m = size.matcher(thumb); if (m.matches()) { try { int width = Integer.parseInt(m.group(1)); int height = Integer.parseInt(m.group(2)); if (width == 0 && height == 0) continue; JsonObject j = new JsonObject().put("dest", storage.getProtocol() + "://" + storage.getBucket()); if (width != 0) { j.put("width", width); }//ww w.jav a2 s . c o m if (height != 0) { j.put("height", height); } outputs.add(j); } catch (NumberFormatException e) { log.error("Invalid thumbnail size.", e); } } } if (outputs.size() > 0) { JsonObject json = new JsonObject().put("action", "resizeMultiple") .put("src", storage.getProtocol() + "://" + storage.getBucket() + ":" + srcFile.getString("_id")) .put("destinations", outputs); eb.send(imageResizerAddress, json, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> event) { if (event.succeeded()) { JsonObject thumbnails = event.result().body().getJsonObject("outputs"); if ("ok".equals(event.result().body().getString("status")) && thumbnails != null) { mongo.update(collection, new JsonObject().put("_id", documentId), new JsonObject().put("$set", new JsonObject().put("thumbnails", thumbnails))); } } else { log.error("Error when resize image.", event.cause()); } } }); } }
From source file:fr.wseduc.rack.services.RackServiceMongoImpl.java
License:Open Source License
public void trashRack(String id, Handler<Either<String, JsonObject>> handler) { JsonObject modifider = new JsonObject(); modifider.put("folder", "Trash"); super.update(id, modifider, handler); }
From source file:hu.elte.ik.robotika.futar.vertx.backend.verticle.HTTPVerticle.java
private boolean calculateThreeCircleIntersection(double x0, double y0, double r0, double x1, double y1, double r1, double x2, double y2, double r2, String robotid) { double a, dx, dy, d, h, rx, ry; double point2_x, point2_y; /* dx and dy are the vertical and horizontal distances between * the circle centers.//from w ww . j a v a 2 s .c om */ dx = x1 - x0; dy = y1 - y0; /* Determine the straight-line distance between the centers. */ d = Math.sqrt((dy * dy) + (dx * dx)); /* Check for solvability. */ if (d > (r0 + r1)) { log.info("no solution. circles do not intersect."); /* no solution. circles do not intersect. */ return false; } if (d < Math.abs(r0 - r1)) { log.info("no solution. one circle is contained in the other"); /* no solution. one circle is contained in the other */ return false; } /* 'point 2' is the point where the line through the circle * intersection points crosses the line between the circle * centers. */ /* Determine the distance from point 0 to point 2. */ a = ((r0 * r0) - (r1 * r1) + (d * d)) / (2.0 * d); /* Determine the coordinates of point 2. */ point2_x = x0 + (dx * a / d); point2_y = y0 + (dy * a / d); /* Determine the distance from point 2 to either of the * intersection points. */ h = Math.sqrt((r0 * r0) - (a * a)); /* Now determine the offsets of the intersection points from * point 2. */ rx = -dy * (h / d); ry = dx * (h / d); /* Determine the absolute intersection points. */ double intersectionPoint1_x = point2_x + rx; double intersectionPoint2_x = point2_x - rx; double intersectionPoint1_y = point2_y + ry; double intersectionPoint2_y = point2_y - ry; double finalPosX = (intersectionPoint1_x + intersectionPoint2_x) / 2; double finalPosY = (intersectionPoint1_y + intersectionPoint2_y) / 2; log.info("INTERSECTION Circle1 AND Circle2:" + "(" + intersectionPoint1_x + "," + intersectionPoint1_y + ")" + " AND (" + intersectionPoint2_x + "," + intersectionPoint2_y + ")"); /* Lets determine if circle 3 intersects at either of the above intersection points. */ dx = intersectionPoint1_x - x2; dy = intersectionPoint1_y - y2; double d1 = Math.sqrt((dy * dy) + (dx * dx)); dx = intersectionPoint2_x - x2; dy = intersectionPoint2_y - y2; double d2 = Math.sqrt((dy * dy) + (dx * dx)); if (Math.abs(d1 - r2) < EPSILON) { log.info("INTERSECTION Circle1 AND Circle2 AND Circle3:" + "(" + intersectionPoint1_x + "," + intersectionPoint1_y + ")"); finalPosX = intersectionPoint1_x; finalPosY = intersectionPoint1_y; } else if (Math.abs(d2 - r2) < EPSILON) { log.info("INTERSECTION Circle1 AND Circle2 AND Circle3:" + "(" + intersectionPoint2_x + "," + intersectionPoint2_y + ")"); //here was an error } else { log.info("INTERSECTION Circle1 AND Circle2 AND Circle3:" + "NONE"); } positionedRobots.remove(robotid); JsonObject response = new JsonObject(); response.put("robotId", robotid); response.put("x", finalPosX); response.put("y", finalPosY); positionedRobots.put(robotid, response); vertx.eventBus().publish("robot.position", Json.encode(response)); return true; }
From source file:hu.elte.ik.robotika.futar.vertx.backend.verticle.HTTPVerticle.java
private SockJSHandler eventBusHandler() { BridgeOptions options = new BridgeOptions() .addOutboundPermitted(new PermittedOptions().setAddressRegex("new.robot")); options.addOutboundPermitted(new PermittedOptions().setAddressRegex("logout.robot")); options.addOutboundPermitted(new PermittedOptions().setAddressRegex("new.bt.device")); options.addOutboundPermitted(new PermittedOptions().setAddressRegex("placed.bt.device")); options.addOutboundPermitted(new PermittedOptions().setAddressRegex("robot.position")); options.addInboundPermitted(new PermittedOptions().setAddressRegex("login.robot")); options.addInboundPermitted(new PermittedOptions().setAddressRegex("login.client")); options.addInboundPermitted(new PermittedOptions().setAddressRegex("robot.\\.[0-9]+")); options.addInboundPermitted(new PermittedOptions().setAddressRegex("place.bt.device")); // use this to send message to the clients: // routingContext.vertx().eventBus().publish("muhaha", routingContext.getBodyAsString()); return SockJSHandler.create(vertx).bridge(options, event -> { if (event.type() == BridgeEventType.SOCKET_CREATED) { log.info("A socket was created"); }/*w w w . j a v a2s .co m*/ if (event.type() == BridgeEventType.SOCKET_CLOSED) { log.info("A socket was closed"); if (activeRobots.contains(event.socket().writeHandlerID())) { log.info("Robot logged out"); activeRobots.remove(event.socket().writeHandlerID()); JsonObject response = new JsonObject(); response.put("robotId", event.socket().writeHandlerID()); vertx.eventBus().publish("logout.robot", Json.encode(response)); } } if (event.type() == BridgeEventType.REGISTER) { log.info("A handler was registered"); log.info(event.rawMessage()); } if (event.type() == BridgeEventType.SEND) { log.info("Client sent a message: " + event.rawMessage()); if (event.rawMessage().getString("address").equals("login.robot") && !activeRobots.contains(event.socket().writeHandlerID())) { log.info("Robot logged in"); activeRobots.add(event.socket().writeHandlerID()); JsonObject response = new JsonObject(); response.put("robotId", event.socket().writeHandlerID()); vertx.eventBus().publish("new.robot", Json.encode(response)); } else if (event.rawMessage().getString("address").equals("login.robot")) { log.info("Robot already logged in"); } if (event.rawMessage().getString("address").equals("login.client")) { for (String key : sockets.keySet()) { log.info("Send active robots"); JsonObject response = new JsonObject(); response.put("robotId", key); vertx.eventBus().publish("new.robot", Json.encode(response)); } for (JsonObject value : placedBTDevices.values()) { vertx.eventBus().publish("placed.bt.device", Json.encode(value)); } for (JsonObject value : newBTDevices.values()) { vertx.eventBus().publish("new.bt.device", Json.encode(value)); } for (JsonObject value : positionedRobots.values()) { vertx.eventBus().publish("robot.position", Json.encode(value)); } } if (event.rawMessage().getString("address").equals("place.bt.device")) { JsonObject data = event.rawMessage().getJsonObject("body"); log.info("Place bt device: " + data.getString("address")); placedBTDevices.remove(data.getString("address")); placedBTDevices.put(data.getString("address"), data); newBTDevices.remove(data.getString("address")); vertx.eventBus().publish("placed.bt.device", Json.encode(data)); } } event.complete(true); }); }
From source file:hu.elte.ik.robotika.futar.vertx.backend.verticle.HTTPVerticle.java
/** * Preload data/* w w w.j a v a 2 s . c om*/ * * @param routingContext */ private void getInfo(RoutingContext routingContext) { JsonObject resp = new JsonObject(); resp.put("preload", "data"); routingContext.response().putHeader("content-type", "application/json; charset=utf-8") .end(Json.encodePrettily(resp)); }
From source file:hu.elte.ik.robotika.futar.vertx.backend.verticle.HTTPVerticle.java
@Override public void start() { init();// ww w .jav a2s . c o 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. j a v a2 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); } } }