public static DBCollection createFeedsItemsCollectionMock(DB db) { DBCollection feedItemsCollection = mock(DBCollection.class); when(db.getCollection("feedItems")).thenReturn(feedItemsCollection); DBCursor feedsItemsCursor = createCursorMock(createFeedsItemDbObjectMock()); when(feedsItemsCursor.sort(any(DBObject.class))).thenReturn(feedsItemsCursor); when(feedsItemsCursor.limit(any(Integer.class))).thenReturn(feedsItemsCursor); when(feedsItemsCursor.skip(any(Integer.class))).thenReturn(feedsItemsCursor); when(feedItemsCollection.find(any(BasicDBObject.class))).thenReturn(feedsItemsCursor); AggregationOutput aggregationOutput = Mockito.mock(AggregationOutput.class); List<DBObject> results = new ArrayList<DBObject>(); DBObject result1 = new BasicDBObject(); result1.put("_id", "tag1"); result1.put("count", 5); results.add(result1); DBObject result2 = new BasicDBObject(); result2.put("_id", "tag2"); result2.put("count", 8); results.add(result2); when(aggregationOutput.results()).thenReturn(results); when(feedItemsCollection.aggregate( any(DBObject.class), any(DBObject.class), any(DBObject.class), any(DBObject.class))) .thenReturn(aggregationOutput); AggregationOutput countAggregate = Mockito.mock(AggregationOutput.class); List<DBObject> countResults = new ArrayList<DBObject>(); DBObject countResult1 = new BasicDBObject(); countResult1.put("_id", "12345"); countResult1.put("count", 5); countResults.add(countResult1); when(countAggregate.results()).thenReturn(countResults); when(feedItemsCollection.aggregate(any(DBObject.class), any(DBObject.class))) .thenReturn(countAggregate); DBObject feedItem = new BasicDBObject(); feedItem.put("_id", "52ffe096e81f7a9bb906b6f9"); feedItem.put("categoryId", "5581e900d4c6cda2d04d0a98"); feedItem.put("feedId", "55893938e4b0c822dc99fa2f"); feedItem.put("delete", true); feedItem.put("description", "description"); feedItem.put( "link", "http://thedailyedge.thejournal.ie/irish-supermarket-fails-2176781-Jun2015/"); feedItem.put("imageUrl", "http://thedailyedge.thejournal.ie/image.jpg"); feedItem.put("read", true); feedItem.put("source", "The Daily Edge"); feedItem.put("title", "title"); feedItem.put("username", "bob"); feedItem.put("pubDate", new Date()); when(feedItemsCollection.findOne(any(DBObject.class))).thenReturn(feedItem); return feedItemsCollection; }
protected void doFindAll(Exchange exchange) throws Exception { DBCollection dbCol = calculateCollection(exchange); // do not use getMandatoryBody, because if the body is empty we want to retrieve all objects in // the collection DBObject query = null; // do not run around looking for a type converter unless there is a need for it if (exchange.getIn().getBody() != null) { query = exchange.getIn().getBody(DBObject.class); } DBObject fieldFilter = exchange.getIn().getHeader(MongoDbConstants.FIELDS_FILTER, DBObject.class); // get the batch size and number to skip Integer batchSize = exchange.getIn().getHeader(MongoDbConstants.BATCH_SIZE, Integer.class); Integer numToSkip = exchange.getIn().getHeader(MongoDbConstants.NUM_TO_SKIP, Integer.class); Integer limit = exchange.getIn().getHeader(MongoDbConstants.LIMIT, Integer.class); DBObject sortBy = exchange.getIn().getHeader(MongoDbConstants.SORT_BY, DBObject.class); DBCursor ret = null; try { if (query == null && fieldFilter == null) { ret = dbCol.find(new BasicDBObject()); } else if (fieldFilter == null) { ret = dbCol.find(query); } else { ret = dbCol.find(query, fieldFilter); } if (sortBy != null) { ret.sort(sortBy); } if (batchSize != null) { ret.batchSize(batchSize.intValue()); } if (numToSkip != null) { ret.skip(numToSkip.intValue()); } if (limit != null) { ret.limit(limit.intValue()); } Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.findAll); resultMessage.setBody(ret.toArray()); resultMessage.setHeader(MongoDbConstants.RESULT_TOTAL_SIZE, ret.count()); resultMessage.setHeader(MongoDbConstants.RESULT_PAGE_SIZE, ret.size()); } finally { // make sure the cursor is closed if (ret != null) { ret.close(); } } }
private DBCursor getDBCursor() { if (select != null) select.put("__version", 1); // Forced retrieval of __version final DBCursor cursor = store.collection.find(where, select); if (limit != 0) cursor.limit(limit); else cursor.limit(100); if (skip != 0) cursor.skip(skip); if (sort != null) { cursor.sort(sort); } // System.out.println(where); return cursor; }
@Override public List<AdminEvent> getResultList() { DBCursor cur = audit.find(query).sort(new BasicDBObject("time", -1)); if (firstResult != null) { cur.skip(firstResult); } if (maxResults != null) { cur.limit(maxResults); } List<AdminEvent> events = new LinkedList<AdminEvent>(); while (cur.hasNext()) { events.add(MongoEventStoreProvider.convertAdminEvent((BasicDBObject) cur.next())); } return events; }
public static JSONObject getComments(int page, String key) { JSONObject retour = new JSONObject(); try { Mongo mongo = DBStatic.getMongo(); DBCollection comments = DBStatic.getMongoCollection(mongo, "comments"); DBCursor cursor; if (key != null && !key.isEmpty()) { int userId = ServicesTools.getIdUserBySession(key); BasicDBObject query = new BasicDBObject(); query.put("user_id", userId); cursor = comments.find(query); } else { cursor = comments.find(); } ArrayList<DBObject> commentsArray = new ArrayList<DBObject>(); cursor.sort(new BasicDBObject("post_date", -1)); cursor.skip(10 * (page - 1)); cursor.limit(10); while (cursor.hasNext()) { commentsArray.add(cursor.next()); } retour.put("comments", commentsArray); mongo.close(); } catch (ClassNotFoundException e) { return ServicesTools.error(e.getMessage(), ServicesTools.CLASS_NOT_FOUND_EXCEPTION); } catch (SQLException e) { return ServicesTools.error(e.getMessage(), ServicesTools.SQL_EXCEPTION); } catch (UnknownHostException e) { return ServicesTools.error(e.getMessage(), ServicesTools.UNKNOWN_HOST_EXCEPTION); } catch (JSONException e) { return ServicesTools.error(e.getMessage(), ServicesTools.JSON_EXCEPTION); } return retour; }
public Page query(Page page) { int perPageSize = page.getPerPageSize(); int pageNo = page.getPageNo(); System.out.println("UserLibraryDAO.query(Page page)"); System.out.println("准备查询数据, from:" + page.getPageFromIndex() + " size:" + perPageSize); Page pageData = new Page(); List users = new ArrayList(); DBCollection userCol = this.getCollInLibraryDB(); DBCursor userCur = null; BasicDBObject queryCondition = new BasicDBObject(); if (page.keywords.equals("")) { DBObject soryViewCount = new BasicDBObject("followers_count", -1); BasicDBObject registeQuery = new BasicDBObject(); registeQuery.put(QueryOperators.GT, 0); queryCondition.put("vv_count", registeQuery); userCur = userCol.find(queryCondition); userCur.sort(soryViewCount); userCur.skip((page.getPageFromIndex())).limit(perPageSize); } else { queryCondition.put("name", page.keywords); userCur = userCol.find(queryCondition); } int count = userCur.count(); System.out.println("查询数据量:" + count); while (userCur.hasNext()) { DBObject show = userCur.next(); Userlibrary showLib = morphia.fromDBObject(Userlibrary.class, show); users.add(showLib); } System.out.println("返回查询数据"); pageData.setPerPageSize(perPageSize); pageData.setCount(count); pageData.setList(users); pageData.setPageNo(pageNo); return pageData; }
/** * Execute the interaction and return output record. The spec is either GET, PUT or DELETE * interaction. */ public Record execute(InteractionSpec spec, Record record) throws ResourceException { if (!(spec instanceof MongoInteractionSpec)) { throw EISException.invalidInteractionSpecType(); } if (!(record instanceof MongoRecord)) { throw EISException.invalidRecordType(); } MongoInteractionSpec mongoSpec = (MongoInteractionSpec) spec; MongoRecord input = (MongoRecord) record; MongoOperation operation = mongoSpec.getOperation(); String collectionName = mongoSpec.getCollection(); if (operation == null) { ResourceException resourceException = new ResourceException("Mongo operation must be set"); throw resourceException; } if (operation == MongoOperation.EVAL) { Object result = this.connection.getDB().eval(mongoSpec.getCode()); return buildRecordFromDBObject((DBObject) result); } if (collectionName == null) { ResourceException resourceException = new ResourceException("DB Collection name must be set"); throw resourceException; } try { DBCollection collection = this.connection.getDB().getCollection(collectionName); if (mongoSpec.getOptions() > 0) { collection.setOptions(mongoSpec.getOptions()); } if (mongoSpec.getReadPreference() != null) { collection.setReadPreference(mongoSpec.getReadPreference()); } if (mongoSpec.getWriteConcern() != null) { collection.setWriteConcern(mongoSpec.getWriteConcern()); } if (operation == MongoOperation.INSERT) { DBObject object = buildDBObject(input); collection.insert(object); } else if (operation == MongoOperation.REMOVE) { DBObject object = buildDBObject(input); collection.remove(object); } else if (operation == MongoOperation.FIND) { DBObject sort = null; if (input.containsKey(MongoRecord.SORT)) { sort = buildDBObject((MongoRecord) input.get(MongoRecord.SORT)); input.remove(MongoRecord.SORT); } DBObject select = null; if (input.containsKey("$select")) { select = buildDBObject((MongoRecord) input.get("$select")); input.remove("$select"); } DBObject object = buildDBObject(input); DBCursor cursor = collection.find(object, select); if (sort != null) { cursor.sort(sort); } try { if (mongoSpec.getSkip() > 0) { cursor.skip(mongoSpec.getSkip()); } if (mongoSpec.getLimit() != 0) { cursor.limit(mongoSpec.getLimit()); } if (mongoSpec.getBatchSize() != 0) { cursor.batchSize(mongoSpec.getBatchSize()); } if (!cursor.hasNext()) { return null; } MongoListRecord results = new MongoListRecord(); while (cursor.hasNext()) { DBObject result = cursor.next(); results.add(buildRecordFromDBObject(result)); } return results; } finally { cursor.close(); } } else { throw new ResourceException("Invalid operation: " + operation); } } catch (Exception exception) { ResourceException resourceException = new ResourceException(exception.toString()); resourceException.initCause(exception); throw resourceException; } return null; }