List of usage examples for com.mongodb DBCollection findOne
@Nullable public DBObject findOne(final Object id)
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 . j a va 2 s .c o 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 ww w.j a v a 2s. 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 www . j a va2 s. c o 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.restfiddle.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) { DBCollection dbCollection = mongoTemplate.getCollection(entityName); BasicDBObject queryObject = new BasicDBObject(); queryObject.append("_id", new ObjectId(entityDataId)); DBObject resultObject = dbCollection.findOne(queryObject); String json = resultObject.toString(); // Indentation JSONObject jsonObject = new JSONObject(json); return jsonObject.toString(4); }
From source file:com.restfiddle.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) { 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); }/*from www. jav a 2 s . co m*/ JSONObject uiJson = createJsonFromMap(map); // ID is stored separately (in a different column). uiJson.remove("id"); DBCollection dbCollection = mongoTemplate.getCollection(entityName); BasicDBObject queryObject = new BasicDBObject(); queryObject.append("_id", new ObjectId(uuid)); resultObject = dbCollection.findOne(queryObject); Set<String> keySet = uiJson.keySet(); for (String key : keySet) { resultObject.put(key, uiJson.get(key)); } dbCollection.save(resultObject); } String json = resultObject.toString(); // Indentation JSONObject jsonObject = new JSONObject(json); return jsonObject.toString(4); }
From source file:com.sanaldiyar.projects.nanohttpd.mongodbbasedsessionhandler.MongoDBBasedSessionHandler.java
/** * Request parser for session. Gets and builds session information * * @param request the request// w ww . j av a 2 s . c o m * @return session manager */ @Override public NanoSessionManager parseRequest(Request request) { MongoDBBasedSessionManager nanoSessionManager = null; DBObject session = null; String sessionid = null; for (Cookie cookie : request.getCookies()) { if (cookie.getName().equals(SESSIONCOOKIEID)) { sessionid = cookie.getValue(); break; } } DBCollection sessions = managers.getCollection("sessions"); if (sessionid != null) { DBCursor cursor = sessions.find(new BasicDBObject("sessionid", sessionid)); List<DBObject> result = cursor.toArray(); cursor.close(); if (result.size() == 1) { session = result.get(0); } if (session != null) { if (((Date) session.get("expires")).getTime() <= new Date().getTime()) { sessions.remove(new BasicDBObject().append("sessionid", sessionid)); session = null; } } } if (session == null) { do { sessionid = new BigInteger(128, srng).toString(32); } while (sessions.findOne(new BasicDBObject().append("sessionid", sessionid)) != null && !sessionid.equals("0")); session = new BasicDBObject(); nanoSessionManager = new MongoDBBasedSessionManager(session); nanoSessionManager.setSessionID(sessionid); sessions.insert(session); } else { nanoSessionManager = new MongoDBBasedSessionManager(session); } return nanoSessionManager; }
From source file:com.sfelf.connectors.mongoOplogCursorConnector.java
License:Open Source License
/** * Returns a {@link BSONTimestamp} of either the timestamp in the specified log collection for the specified namespace or * the timestamp of the newest entry in the oplog.rs. * /*from w w w. j a va 2 s . c om*/ * @param oplog The {@link DBCollection} containing the oplog (local.oplog.rs) * @param log The {@link DBCollection} containing a log of the timestamp for the last entry processed for the specified namespace * @param namespace The namespace for which the last timestamp is being requested * @return {@link BSONTimestamp} * @throws MongoOplogCursorException */ private BSONTimestamp getLastTimestamp(DBCollection oplog, DBCollection log, String namespace) throws MongoOplogCursorException { BSONTimestamp lastTimestamp = null; if (log != null) { DBObject queryParams = new BasicDBObject("_id", namespace); DBObject result = log.findOne(queryParams); if (result != null && result.get(LAST_TIMESTAMP_LOG_FIELD) != null) { lastTimestamp = (BSONTimestamp) result.get(LAST_TIMESTAMP_LOG_FIELD); } } if (lastTimestamp == null) { DBObject orderBy = new BasicDBObject("$natural", SORT_ORDER_DESCENDING); DBCursor cursor = oplog.find().sort(orderBy); if (cursor.hasNext()) { lastTimestamp = (BSONTimestamp) cursor.next().get("ts"); } else { throw new MongoOplogCursorException("Unable to establish cursor as the oplog is empty"); } } return lastTimestamp; }
From source file:com.sitewhere.mongodb.asset.MongoAssetManagement.java
License:Open Source License
/** * Return the {@link DBObject} for the asset category with the given id. * /*from w ww . j a v a 2 s. co m*/ * @param id * @return * @throws SiteWhereException */ protected DBObject getAssetCategoryDBObject(String id) throws SiteWhereException { try { DBCollection categories = getMongoClient().getAssetCategoriesCollection(getTenant()); BasicDBObject query = new BasicDBObject(MongoAssetCategory.PROP_ID, id); DBObject result = categories.findOne(query); return result; } catch (MongoTimeoutException e) { throw new SiteWhereException("Connection to MongoDB lost.", e); } }
From source file:com.sitewhere.mongodb.asset.MongoAssetManagement.java
License:Open Source License
/** * Retirn the {@link DBObject} for the given asset. Returns null if not found. * //from ww w .ja va 2 s .com * @param categoryId * @param assetId * @return * @throws SiteWhereException */ protected DBObject getAssetDBObject(String categoryId, String assetId) throws SiteWhereException { try { DBCollection assets = getMongoClient().getAssetsCollection(getTenant()); BasicDBObject query = new BasicDBObject(MongoAsset.PROP_CATEGORY_ID, categoryId) .append(MongoAsset.PROP_ID, assetId); return assets.findOne(query); } catch (MongoTimeoutException e) { throw new SiteWhereException("Connection to MongoDB lost.", e); } }