Example usage for com.mongodb DBObject removeField

List of usage examples for com.mongodb DBObject removeField

Introduction

In this page you can find the example usage for com.mongodb DBObject removeField.

Prototype

Object removeField(String key);

Source Link

Document

Removes a field with a given name from this object.

Usage

From source file:com.restfeel.controller.rest.EntityDataController.java

License:Apache License

@RequestMapping(value = "/api/{projectId}/entities/{name}/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public @ResponseBody String getEntityDataById(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @PathVariable("id") String entityDataId,
        @RequestHeader(value = "authToken", required = false) String authToken) {

    JSONObject authRes = authService.authorize(projectId, authToken, "USER");
    if (!authRes.getBoolean(SUCCESS)) {
        return authRes.toString(4);
    }//from  w  w  w  .  j av a  2  s  .c o m

    DBCollection dbCollection = mongoTemplate.getCollection(projectId + "_" + entityName);

    BasicDBObject queryObject = new BasicDBObject();
    queryObject.append("_id", new ObjectId(entityDataId));

    DBObject resultObject = dbCollection.findOne(queryObject);

    if (resultObject == null) {
        return "Not Found";
    }

    if (entityName.equals("User")) {
        resultObject.removeField(PASSWORD);
    }

    dbRefToRelation(resultObject);
    String json = resultObject.toString();

    // Indentation
    JSONObject jsonObject = new JSONObject(json);
    return jsonObject.toString(4);
}

From source file:com.restfeel.controller.rest.EntityDataController.java

License:Apache License

@RequestMapping(value = "/api/{projectId}/entities/{name}/{uuid}", method = RequestMethod.PUT, headers = "Accept=application/json", consumes = "application/json")
public @ResponseBody String updateEntityData(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @PathVariable("uuid") String uuid,
        @RequestBody Object genericEntityDataDTO,
        @RequestHeader(value = "authToken", required = false) String authToken) {

    DBRef user;//  w  w w .ja va  2  s .co  m
    JSONObject authRes = authService.authorize(projectId, authToken, "USER");
    if (authRes.getBoolean(SUCCESS)) {
        user = (DBRef) authRes.get("user");
    } else {
        return authRes.toString(4);
    }

    DBObject resultObject = new BasicDBObject();
    if (genericEntityDataDTO instanceof Map) {
        Map map = (Map) genericEntityDataDTO;
        if (map.get("id") != null && map.get("id") instanceof String) {
            String entityDataId = (String) map.get("id");
            logger.debug("Updating Entity Data with Id " + entityDataId);
        }
        JSONObject uiJson = new JSONObject(map);
        // ID is stored separately (in a different column).
        DBObject obj = (DBObject) JSON.parse(uiJson.toString());
        obj.removeField("_id");

        DBCollection dbCollection = mongoTemplate.getCollection(projectId + "_" + entityName);
        BasicDBObject queryObject = new BasicDBObject();
        queryObject.append("_id", new ObjectId(uuid));
        resultObject = dbCollection.findOne(queryObject);

        Set<String> keySet = obj.keySet();
        for (String key : keySet) {
            resultObject.put(key, obj.get(key));
        }

        if (entityName.equals("User")) {
            DBObject loggedInUser = dbCollection.findOne(user);
            if (loggedInUser.get(USERNAME).equals(resultObject.get(USERNAME))) {
                return handleUserEntityData(projectId, resultObject, obj.containsField(PASSWORD));
            } else {
                return new JSONObject().put(SUCCESS, false).put("msg", "unauthorized").toString(4);
            }
        }

        relationToDBRef(resultObject, projectId);

        resultObject.put("updatedBy", user);
        resultObject.put("updatedAt", new Date());

        dbCollection.save(resultObject);
    }
    dbRefToRelation(resultObject);
    String json = resultObject.toString();

    // Indentation
    JSONObject jsonObject = new JSONObject(json);
    return jsonObject.toString(4);
}

From source file:com.restfeel.controller.rest.EntityDataController.java

License:Apache License

private String handleUserEntityData(String projectId, DBObject user, boolean encryptPassword) {
    JSONObject response = new JSONObject();

    if (!user.containsField(USERNAME)) {
        response.put("msg", "username is mandotary");
        return response.toString(4);
    }/*from  w  ww.  j  a  v  a  2 s  . c om*/

    if (((String) user.get(USERNAME)).length() < 3) {
        response.put("msg", "username must be more then 3 character");
        return response.toString(4);
    }

    if (!user.containsField(PASSWORD)) {
        response.put("msg", "password is mandotary");
        return response.toString(4);
    }

    if (((String) user.get(PASSWORD)).length() < 3) {
        response.put("msg", "password must be more then 3 character");
        return response.toString(4);
    }

    DBCollection dbCollection = mongoTemplate.getCollection(projectId + "_User");

    BasicDBObject query = new BasicDBObject();
    query.append(USERNAME, user.get(USERNAME));

    DBObject existingUser = dbCollection.findOne(query);

    if (existingUser != null && !existingUser.get("_id").equals(user.get("_id"))) {
        response.put("msg", "username already exists");
        return response.toString(4);
    }

    if (encryptPassword) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.put(PASSWORD, encoder.encode((String) user.get(PASSWORD)));
    }

    relationToDBRef(user, projectId);

    dbCollection.save(user);
    user.removeField(PASSWORD);
    dbRefToRelation(user);
    String json = user.toString();

    // Indentation
    response = new JSONObject(json);
    return response.toString(4);
}

From source file:com.restfeel.controller.rest.EntitySessionController.java

License:Apache License

@RequestMapping(value = "/api/{projectId}/entities/login", method = RequestMethod.POST, headers = "Accept=application/json", consumes = "application/json")
public @ResponseBody String createEntityData(@PathVariable("projectId") String projectId,
        @RequestBody Object userDTO) {
    DBObject data;/*from   w w  w.j  av  a 2s.co  m*/
    if (!(userDTO instanceof Map)) {
        return null;
    }

    JSONObject response = new JSONObject();

    Map map = (Map) userDTO;
    JSONObject jsonObj = new JSONObject(map);
    try {
        data = authService.authenticate(jsonObj, projectId);
    } catch (Exception e) {
        response.put("msg", e.getMessage());
        return response.toString(4);
    }
    DBCollection userCollection = mongoTemplate.getCollection(projectId + "_User");

    DBObject user = userCollection.findOne(((DBRef) (data.get("user"))).getId());
    user.removeField("password");
    data.put("user", user);

    dbRefToRelation(data);
    data.put("authToken", data.get("_id"));
    data.removeField("_id");
    data.removeField("expireAt");
    String json = data.toString();

    // Indentation
    response = new JSONObject(json);
    return response.toString(4);
}

From source file:com.sitewhere.mongodb.device.MongoDeviceManagement.java

License:Open Source License

@Override
public IDeviceAssignment endDeviceAssignment(String token) throws SiteWhereException {
    DBObject match = assertDeviceAssignment(token);
    match.put(MongoDeviceAssignment.PROP_RELEASED_DATE, Calendar.getInstance().getTime());
    match.put(MongoDeviceAssignment.PROP_STATUS, DeviceAssignmentStatus.Released.name());
    DBCollection assignments = getMongoClient().getDeviceAssignmentsCollection();
    BasicDBObject query = new BasicDBObject(MongoDeviceAssignment.PROP_TOKEN, token);
    MongoPersistence.update(assignments, query, match);

    // Update cache with new assignment data.
    if (getCacheProvider() != null) {
        DeviceAssignment updated = MongoDeviceAssignment.fromDBObject(match);
        getCacheProvider().getDeviceAssignmentCache().put(updated.getToken(), updated);
    }/*from   w ww . j ava  2 s. co m*/

    // Remove device assignment reference.
    DBCollection devices = getMongoClient().getDevicesCollection();
    String hardwareId = (String) match.get(MongoDeviceAssignment.PROP_DEVICE_HARDWARE_ID);
    DBObject deviceMatch = getDeviceDBObjectByHardwareId(hardwareId);
    deviceMatch.removeField(MongoDevice.PROP_ASSIGNMENT_TOKEN);
    query = new BasicDBObject(MongoDevice.PROP_HARDWARE_ID, hardwareId);
    MongoPersistence.update(devices, query, deviceMatch);

    // Update cache with new device data.
    if (getCacheProvider() != null) {
        Device updated = MongoDevice.fromDBObject(deviceMatch);
        getCacheProvider().getDeviceCache().put(updated.getHardwareId(), updated);
    }

    DeviceAssignment assignment = MongoDeviceAssignment.fromDBObject(match);
    return assignment;
}

From source file:com.softinstigate.restheart.db.CollectionDAO.java

License:Open Source License

/**
 * Upsert the collection properties./*from   w  ww .j  a  v  a  2  s  .  c om*/
 *
 * @param dbName the database name of the collection
 * @param collName the collection name
 * @param content the new collection properties
 * @param etag the entity tag. must match to allow actual write (otherwise
 * http error code is returned)
 * @param updating true if updating existing document
 * @param patching true if use patch semantic (update only specified fields)
 * @return the HttpStatus code to set in the http response
 */
public static int upsertCollection(String dbName, String collName, DBObject content, ObjectId etag,
        boolean updating, boolean patching) {
    DB db = DBDAO.getDB(dbName);

    DBCollection coll = db.getCollection(collName);

    if (patching && !updating) {
        return HttpStatus.SC_NOT_FOUND;
    }

    if (updating) {
        if (etag == null) {
            return HttpStatus.SC_CONFLICT;
        }

        BasicDBObject idAndEtagQuery = new BasicDBObject("_id", "_properties");
        idAndEtagQuery.append("_etag", etag);

        if (coll.count(idAndEtagQuery) < 1) {
            return HttpStatus.SC_PRECONDITION_FAILED;
        }
    }

    ObjectId timestamp = new ObjectId();
    Instant now = Instant.ofEpochSecond(timestamp.getTimestamp());

    if (content == null) {
        content = new BasicDBObject();
    }

    content.removeField("_id"); // make sure we don't change this field

    if (updating) {
        content.removeField("_crated_on"); // don't allow to update this field
        content.put("_etag", timestamp);
    } else {
        content.put("_id", "_properties");
        content.put("_created_on", now.toString());
        content.put("_etag", timestamp);
    }

    if (patching) {
        coll.update(PROPS_QUERY, new BasicDBObject("$set", content), true, false);
        return HttpStatus.SC_OK;
    } else {
        // we use findAndModify to get the @created_on field value from the existing properties document
        // we need to put this field back using a second update 
        // it is not possible in a single update even using $setOnInsert update operator
        // in this case we need to provide the other data using $set operator and this makes it a partial update (patch semantic) 

        DBObject old = coll.findAndModify(PROPS_QUERY, fieldsToReturn, null, false, content, false, true);

        if (old != null) {
            Object oldTimestamp = old.get("_created_on");

            if (oldTimestamp == null) {
                oldTimestamp = now.toString();
                logger.warn("properties of collection {} had no @created_on field. set to now",
                        coll.getFullName());
            }

            // need to readd the @created_on field 
            BasicDBObject createdContet = new BasicDBObject("_created_on", "" + oldTimestamp);
            createdContet.markAsPartialObject();
            coll.update(PROPS_QUERY, new BasicDBObject("$set", createdContet), true, false);

            return HttpStatus.SC_OK;
        } else {
            // need to readd the @created_on field 
            BasicDBObject createdContet = new BasicDBObject("_created_on", now.toString());
            createdContet.markAsPartialObject();
            coll.update(PROPS_QUERY, new BasicDBObject("$set", createdContet), true, false);

            initDefaultIndexes(coll);

            return HttpStatus.SC_CREATED;
        }
    }
}

From source file:com.softinstigate.restheart.db.DBDAO.java

License:Open Source License

/**
 *
 * @param dbName/* ww w  .j  a  va2  s. c o m*/
 * @param content
 * @param etag
 * @param patching
 * @return
 */
public static int upsertDB(String dbName, DBObject content, ObjectId etag, boolean patching) {
    DB db = client.getDB(dbName);

    boolean existing = db.getCollectionNames().size() > 0;

    if (patching && !existing) {
        return HttpStatus.SC_NOT_FOUND;
    }

    DBCollection coll = db.getCollection("_properties");

    // check the etag
    if (db.collectionExists("_properties")) {
        if (etag == null) {
            return HttpStatus.SC_CONFLICT;
        }

        BasicDBObject idAndEtagQuery = new BasicDBObject("_id", "_properties");
        idAndEtagQuery.append("_etag", etag);

        if (coll.count(idAndEtagQuery) < 1) {
            return HttpStatus.SC_PRECONDITION_FAILED;
        }
    }

    // apply new values
    ObjectId timestamp = new ObjectId();
    Instant now = Instant.ofEpochSecond(timestamp.getTimestamp());

    if (content == null) {
        content = new BasicDBObject();
    }

    content.put("_etag", timestamp);
    content.removeField("_created_on"); // make sure we don't change this field
    content.removeField("_id"); // make sure we don't change this field

    if (patching) {
        coll.update(METADATA_QUERY, new BasicDBObject("$set", content), true, false);

        return HttpStatus.SC_OK;
    } else {
        // we use findAndModify to get the @created_on field value from the existing document
        // we need to put this field back using a second update 
        // it is not possible in a single update even using $setOnInsert update operator
        // in this case we need to provide the other data using $set operator and this makes it a partial update (patch semantic) 
        DBObject old = coll.findAndModify(METADATA_QUERY, fieldsToReturn, null, false, content, false, true);

        if (old != null) {
            Object oldTimestamp = old.get("_created_on");

            if (oldTimestamp == null) {
                oldTimestamp = now.toString();
                logger.warn("properties of collection {} had no @created_on field. set to now",
                        coll.getFullName());
            }

            // need to readd the @created_on field 
            BasicDBObject createdContet = new BasicDBObject("_created_on", "" + oldTimestamp);
            createdContet.markAsPartialObject();
            coll.update(METADATA_QUERY, new BasicDBObject("$set", createdContet), true, false);

            return HttpStatus.SC_OK;
        } else {
            // need to readd the @created_on field 
            BasicDBObject createdContet = new BasicDBObject("_created_on", now.toString());
            createdContet.markAsPartialObject();
            coll.update(METADATA_QUERY, new BasicDBObject("$set", createdContet), true, false);

            return HttpStatus.SC_CREATED;
        }
    }
}

From source file:com.softinstigate.restheart.db.DocumentDAO.java

License:Open Source License

/**
 *
 *
 * @param dbName/*from w ww.  j  a v  a  2s  .  com*/
 * @param collName
 * @param documentId
 * @param content
 * @param requestEtag
 * @param patching
 * @return the HttpStatus code to retrun
 */
public static int upsertDocument(String dbName, String collName, String documentId, DBObject content,
        ObjectId requestEtag, boolean patching) {
    DB db = DBDAO.getDB(dbName);

    DBCollection coll = db.getCollection(collName);

    ObjectId timestamp = new ObjectId();
    Instant now = Instant.ofEpochSecond(timestamp.getTimestamp());

    if (content == null) {
        content = new BasicDBObject();
    }

    content.put("_etag", timestamp);

    BasicDBObject idQuery = new BasicDBObject("_id", getId(documentId));

    if (patching) {
        content.removeField("_created_on"); // make sure we don't change this field

        DBObject oldDocument = coll.findAndModify(idQuery, null, null, false,
                new BasicDBObject("$set", content), false, false);

        if (oldDocument == null) {
            return HttpStatus.SC_NOT_FOUND;
        } else {
            // check the old etag (in case restore the old document version)
            return optimisticCheckEtag(coll, oldDocument, requestEtag, HttpStatus.SC_OK);
        }
    } else {
        content.put("_created_on", now.toString()); // let's assume this is an insert. in case we'll set it back with a second update

        // we use findAndModify to get the @created_on field value from the existing document
        // in case this is an update well need to put it back using a second update 
        // it is not possible to do it with a single update
        // (even using $setOnInsert update because we'll need to use the $set operator for other data and this would make it a partial update (patch semantic) 
        DBObject oldDocument = coll.findAndModify(idQuery, null, null, false, content, false, true);

        if (oldDocument != null) { // upsert
            Object oldTimestamp = oldDocument.get("_created_on");

            if (oldTimestamp == null) {
                oldTimestamp = now.toString();
                logger.warn("properties of document /{}/{}/{} had no @created_on field. set to now", dbName,
                        collName, documentId);
            }

            // need to readd the @created_on field 
            BasicDBObject created = new BasicDBObject("_created_on", "" + oldTimestamp);
            created.markAsPartialObject();
            coll.update(idQuery, new BasicDBObject("$set", created), true, false);

            // check the old etag (in case restore the old document version)
            return optimisticCheckEtag(coll, oldDocument, requestEtag, HttpStatus.SC_OK);
        } else { // insert
            return HttpStatus.SC_CREATED;
        }
    }
}

From source file:com.softinstigate.restheart.db.DocumentDAO.java

License:Open Source License

/**
 *
 *
 * @param exchange/* www . ja v a2 s .com*/
 * @param dbName
 * @param collName
 * @param content
 * @param requestEtag
 * @return the HttpStatus code to retrun
 */
public static int upsertDocumentPost(HttpServerExchange exchange, String dbName, String collName,
        DBObject content, ObjectId requestEtag) {
    DB db = DBDAO.getDB(dbName);

    DBCollection coll = db.getCollection(collName);

    ObjectId timestamp = new ObjectId();
    Instant now = Instant.ofEpochSecond(timestamp.getTimestamp());

    if (content == null) {
        content = new BasicDBObject();
    }

    content.put("_etag", timestamp);
    content.put("_created_on", now.toString()); // make sure we don't change this field

    Object _id = content.get("_id");
    content.removeField("_id");

    if (_id == null) {
        ObjectId id = new ObjectId();
        content.put("_id", id);

        coll.insert(content);

        exchange.getResponseHeaders().add(HttpString.tryFromString("Location"),
                getReferenceLink(exchange.getRequestURL(), id.toString()).toString());

        return HttpStatus.SC_CREATED;
    }

    BasicDBObject idQuery = new BasicDBObject("_id", getId("" + _id));

    // we use findAndModify to get the @created_on field value from the existing document
    // we need to put this field back using a second update 
    // it is not possible in a single update even using $setOnInsert update operator
    // in this case we need to provide the other data using $set operator and this makes it a partial update (patch semantic) 
    DBObject oldDocument = coll.findAndModify(idQuery, null, null, false, content, false, true);

    if (oldDocument != null) { // upsert
        Object oldTimestamp = oldDocument.get("_created_on");

        if (oldTimestamp == null) {
            oldTimestamp = now.toString();
            logger.warn("properties of document /{}/{}/{} had no @created_on field. set to now", dbName,
                    collName, _id.toString());
        }

        // need to readd the @created_on field 
        BasicDBObject createdContet = new BasicDBObject("_created_on", "" + oldTimestamp);
        createdContet.markAsPartialObject();
        coll.update(idQuery, new BasicDBObject("$set", createdContet), true, false);

        // check the old etag (in case restore the old document version)
        return optimisticCheckEtag(coll, oldDocument, requestEtag, HttpStatus.SC_OK);
    } else { // insert
        return HttpStatus.SC_CREATED;
    }
}

From source file:com.softinstigate.restheart.handlers.injectors.BodyInjectorHandler.java

License:Open Source License

/**
 *
 * @param exchange//from  ww w  . j  av  a 2 s . c  o m
 * @param context
 * @throws Exception
 */
@Override
public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception {
    if (context.getMethod() == RequestContext.METHOD.GET || context.getMethod() == RequestContext.METHOD.OPTIONS
            || context.getMethod() == RequestContext.METHOD.DELETE) {
        next.handleRequest(exchange, context);
        return;
    }

    // check content type
    HeaderValues contentTypes = exchange.getRequestHeaders().get(Headers.CONTENT_TYPE);

    if (contentTypes == null || contentTypes.isEmpty() || contentTypes.stream().noneMatch(
            ct -> ct.startsWith(Representation.HAL_JSON_MEDIA_TYPE) || ct.startsWith(JSON_MEDIA_TYPE))) // content type header can be also: Content-Type: application/json; charset=utf-8
    {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE,
                "Contet-Type must be either " + Representation.HAL_JSON_MEDIA_TYPE + " or " + JSON_MEDIA_TYPE);
        return;
    }

    String _content = ChannelReader.read(exchange.getRequestChannel());

    DBObject content;

    try {
        content = (DBObject) JSON.parse(_content);
    } catch (JSONParseException ex) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE, "invalid data", ex);
        return;
    }

    HashSet<String> keysToRemove = new HashSet<>();

    if (content == null) {
        context.setContent(null);
    } else {
        // filter out reserved keys
        content.keySet().stream().filter(key -> key.startsWith("_") && !key.equals("_id")).forEach(key -> {
            keysToRemove.add(key);
        });

        keysToRemove.stream().map(keyToRemove -> {
            content.removeField(keyToRemove);
            return keyToRemove;
        }).forEach(keyToRemove -> {
            context.addWarning("the reserved field " + keyToRemove + " was filtered out from the request");
        });

        // inject the request content in the context
        context.setContent(content);
    }

    next.handleRequest(exchange, context);
}