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

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

Introduction

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

Prototype

public Object remove(String key) 

Source Link

Document

Remove an entry from this object.

Usage

From source file:de.fraunhofer.fokus.redistest.DoInterestingThings.java

License:Creative Commons License

/**
 * transfer hash table from redis into Entry
 * @param json - JsonObject stored in redis, all fields are of type string
 * @return Entry//from  w w w . j  a  v a2 s . com
 */

private JsonObject toEntry(JsonObject json) {
    Entry entry = new Entry().setHandle(json.getString(Constants.KEY_RECORD_ID));
    json.remove(Constants.KEY_RECORD_ID);
    for (String fn : json.fieldNames()) {
        switch (fn) {
        case Constants.KEY_DICE_VALUE:
        case Constants.KEY_FAMILYNAME:
        case Constants.KEY_FIRSTNAME:
        case Constants.KEY_DAY_OF_BIRTH:
        case Constants.KEY_MONTH_OF_BIRTH:
        case Constants.KEY_YEAR_OF_BIRTH:
        case Constants.KEY_PLACE_OF_BIRTH:
        case Constants.KEY_GENDER:
            json.put(fn, Double.parseDouble(json.getString(fn)));
            break;
        }

    }
    return entry.setDiceJson(json);
}

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/* ww w . j  a v 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:hu.elte.ik.robotika.futar.vertx.backend.verticle.HTTPVerticle.java

@Override
public void start() {

    init();/*w w w .  j av a  2s .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.flowly.auth.manager.UserManager.java

License:Open Source License

/**
 * Verify the authenticity of the provided user credentials.
 *
 * @param user JSON object representing the user credentials.
 *             Ex: {// w  w  w.j a  v  a 2  s.com
 *                 "userId": "aragorn",
 *                 "password": "!234aCbbJk_#3"
 *             }
 * @return JSON object representing the authenticated user attributes and effective permissions.
 *         Ex: {
 *             "userId": "aragorn",
 *             "firstName": "First",
 *             "lastName": "Last",
 *             "middleName": "M",
 *             "fullName": "First M Last",
 *             "isInternal": true,
 *             "authenticated": true,
 *             "effectivePermissions": [
 *                 {
 *                     "resourceVertexId": 54113,
 *                     "resourceId": "Studio"
 *                     "rwx": 7
 *                 }
 *             ]
 *         }
 */
public JsonObject authenticate(JsonObject user) {
    user.put(User.AUTHENTICATED, false);
    String password = (String) user.remove(User.PASSWORD);
    String userId = user.getString(User.USER_ID);

    try {
        if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(password)) {

            Traversal<Vertex, Vertex> traversal = graph.traversal().V().has(Schema.V_USER, Schema.V_P_USER_ID,
                    userId);

            if (traversal.hasNext()) {
                Vertex userVertex = traversal.next();
                String hash = getPropertyValue(userVertex, Schema.V_P_PASSWORD).toString();
                boolean authenticated = PasswordHash.validatePassword(password, hash);

                if (authenticated) {
                    user = get(userVertex, true, false, false, true);
                    user.put(User.AUTHENTICATED, true);
                }
            }

            commit();
        }
    } catch (Exception ex) {
        rollback();
        logger.error("Unable to authenticate user.", ex);
    }

    return user;
}

From source file:io.flowly.auth.manager.UserManager.java

License:Open Source License

/**
 * Populate the user attributes, memberships and permissions into a JSON object.
 *
 * @param includeDirectMemberships indicates if the user's direct memberships are to be retrieved.
 * @param includeEffectiveMemberships indicates if all the user's memberships are to be retrieved.
 * @param includeDirectPermissions indicates if the permissions directly granted to the user are to be retrieved.
 * @param includeEffectivePermissions indicates if the effective permissions granted to the user are to be calculated.
 * @return JSON object representing a user and optional memberships and permissions.
 *///from   www. j a v a 2  s.  co  m
private JsonObject get(Vertex userVertex, boolean includeDirectMemberships, boolean includeEffectiveMemberships,
        boolean includeDirectPermissions, boolean includeEffectivePermissions) {
    JsonObject user = makeUserObject(userVertex);

    getMemberships(userVertex, user, includeEffectiveMemberships, includeDirectMemberships,
            includeEffectivePermissions);

    if (includeDirectPermissions || includeEffectivePermissions) {
        getDirectPermissions(userVertex, user);
    }

    if (includeEffectivePermissions) {
        getEffectivePermissions(user);
    }

    // Once effective permissions are calculated, remove
    // other keys if they weren't requested.
    if (!includeDirectMemberships) {
        user.remove(User.DIRECT_MEMBERSHIPS);
    }

    if (!includeDirectPermissions) {
        user.remove(Permission.DIRECT_PERMISSIONS);
    }

    if (!includeEffectiveMemberships) {
        user.remove(User.EFFECTIVE_MEMBERSHIPS);
    }

    return user;
}

From source file:io.flowly.auth.router.UserRouter.java

License:Open Source License

private JsonObject getAuthenticatedUser(JsonObject user) {
    if (!user.getBoolean(User.AUTHENTICATED)) {
        return user;
    }/*from  w ww .  j  av a  2 s .c o  m*/

    JsonObject claims = new JsonObject().put("sub", user.getString(User.USER_ID)).put("permissions",
            user.remove(Permission.EFFECTIVE_PERMISSIONS));

    JsonArray directMemberships = (JsonArray) user.remove(User.DIRECT_MEMBERSHIPS);
    if (directMemberships != null) {
        claims.put(ObjectKeys.GURU, directMemberships.stream().anyMatch(m -> {
            JsonObject group = (JsonObject) m;
            String groupId = group.getString(Group.GROUP_ID);

            return groupId != null && groupId.equals(ObjectKeys.ADMIN_GROUP_ID);
        }));
    }

    return user.put("token", authProvider.generateToken(claims, new JWTOptions()));
}

From source file:org.eclipse.hono.service.EventBusService.java

License:Open Source License

/**
 * Removes a property value of a given type from a JSON object.
 *
 * @param payload The object to get the property from.
 * @param field The name of the property.
 * @param <T> The type of the field.
 * @return The property value or {@code null} if no such property exists or is not of the expected type.
 * @throws NullPointerException if any of the parameters is {@code null}.
 *///  w  w w  . ja  v  a2 s. c o  m
@SuppressWarnings({ "unchecked" })
protected final <T> T removeTypesafeValueForField(final JsonObject payload, final String field) {

    Objects.requireNonNull(payload);
    Objects.requireNonNull(field);

    try {
        return (T) payload.remove(field);
    } catch (ClassCastException e) {
        return null;
    }
}

From source file:org.eclipse.hono.service.registration.RegistrationHttpEndpoint.java

License:Open Source License

private void registerDevice(final RoutingContext ctx, final JsonObject payload) {

    if (payload == null) {
        HttpEndpointUtils.badRequest(ctx.response(), "missing body");
    } else {// w  w w.  java  2s  .com
        Object deviceId = payload.remove(FIELD_DEVICE_ID);
        if (deviceId == null) {
            HttpEndpointUtils.badRequest(ctx.response(),
                    String.format("'%s' param is required", FIELD_DEVICE_ID));
        } else if (!(deviceId instanceof String)) {
            HttpEndpointUtils.badRequest(ctx.response(),
                    String.format("'%s' must be a string", FIELD_DEVICE_ID));
        } else {
            final String tenantId = getTenantParam(ctx);
            logger.debug("registering data for device [tenant: {}, device: {}, payload: {}]", tenantId,
                    deviceId, payload);
            final HttpServerResponse response = ctx.response();
            final JsonObject requestMsg = RegistrationConstants.getServiceRequestAsJson(
                    RegistrationConstants.ACTION_REGISTER, tenantId, (String) deviceId, payload);
            doRegistrationAction(ctx, requestMsg, (status, registrationResult) -> {
                response.setStatusCode(status);
                switch (status) {
                case HttpURLConnection.HTTP_CREATED:
                    response.putHeader(HttpHeaders.LOCATION, String.format("/%s/%s/%s",
                            RegistrationConstants.REGISTRATION_ENDPOINT, tenantId, deviceId));
                default:
                    response.end();
                }
            });
        }
    }
}

From source file:org.eclipse.hono.service.registration.RegistrationHttpEndpoint.java

License:Open Source License

private void updateRegistration(final String deviceId, final JsonObject payload, final RoutingContext ctx) {

    if (payload != null) {
        payload.remove(FIELD_DEVICE_ID);
    }/*w  w w  .  j ava  2 s.  c o  m*/
    final String tenantId = getTenantParam(ctx);
    logger.debug("updating registration data for device [tenant: {}, device: {}, payload: {}]", tenantId,
            deviceId, payload);
    final HttpServerResponse response = ctx.response();
    final JsonObject requestMsg = RegistrationConstants
            .getServiceRequestAsJson(RegistrationConstants.ACTION_UPDATE, tenantId, deviceId, payload);

    doRegistrationAction(ctx, requestMsg, (status, registrationResult) -> {
        response.setStatusCode(status);
        switch (status) {
        case HttpURLConnection.HTTP_OK:
            String msg = registrationResult.getJsonObject("payload").encodePrettily();
            response.putHeader(HttpHeaders.CONTENT_TYPE, HttpEndpointUtils.CONTENT_TYPE_JSON_UFT8)
                    .putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(msg.length())).write(msg);
        default:
            response.end();
        }
    });
}

From source file:org.eclipse.hono.service.tenant.TenantHttpEndpoint.java

License:Open Source License

private static String getTenantParamFromPayload(final JsonObject payload) {
    return (payload != null ? (String) payload.remove(TenantConstants.FIELD_PAYLOAD_TENANT_ID) : null);
}