List of usage examples for com.mongodb DBCursor limit
public DBCursor limit(final int limit)
From source file:recomendacao.Recomendacao.java
/** * Filmes para o usurio/*from ww w .j a v a 2 s . c o m*/ */ public void recomendar() { long startTime = System.currentTimeMillis(); double soma = 0; //Recuperar todos os usurios DBCursor usersCursor = usersCollection.find(); //Para cada usuro while (usersCursor.hasNext()) { long startTimeUser = System.currentTimeMillis(); BasicDBObject user = (BasicDBObject) usersCursor.next(); //Ver qual o gnero que ele mais assiste (baseado nos rates) //e recuperar todos os filmes assistidos pelo user DBCursor ratesCursor = ratesCollection.find(new BasicDBObject("userID", user.get("_id"))); Map<String, Integer> categoriasCount = new HashMap<>(); BasicDBList moviesAssistidos = new BasicDBList(); while (ratesCursor.hasNext()) { BasicDBObject rate = (BasicDBObject) ratesCursor.next(); //Recuperar o filme Integer movieID = rate.getInt("movieID"); BasicDBObject movie = (BasicDBObject) moviesCollection.findOne(new BasicDBObject("_id", movieID)); BasicDBList categories = (BasicDBList) movie.get("categories"); moviesAssistidos.add(movieID); try { //Guardar a contagem for (Object categoryObject : categories) { String category = (String) categoryObject; int count = 0; if (categoriasCount.containsKey(category)) { count = categoriasCount.get(category); } count++; categoriasCount.put(category, count); } } catch (NullPointerException ex) { System.out.println(movie.get("name") + " no tem categoria..."); } // System.out.println("movie: " + movie); // break; } //Selecionar a melhor categoria String melhorCategoria = null; int maior = -1; for (String category : categoriasCount.keySet()) { int count = categoriasCount.get(category); if (count > maior) { maior = count; melhorCategoria = category; } } BasicDBObject categoryObject = (BasicDBObject) categoriesCollection .findOne(new BasicDBObject("name", melhorCategoria)); BasicDBList todosMoviesDaCategoria = (BasicDBList) categoryObject.get("movies"); // System.out.println("moviesAssistidos: " + moviesAssistidos.size()); // System.out.println("todosMoviesDaCategoria: " + todosMoviesDaCategoria.size()); //Selecionar os filmes da categoria que o user no assistiu todosMoviesDaCategoria.removeAll(moviesAssistidos); // System.out.println("todosMoviesDaCategoria: " + todosMoviesDaCategoria.size()); BasicDBObject selectObject = new BasicDBObject(); selectObject.put("movieID", new BasicDBObject("$in", todosMoviesDaCategoria)); BasicDBObject sortObject = new BasicDBObject(); sortObject.put("rating", -1); sortObject.put("timestamp", -1); ratesCursor = ratesCollection.find(selectObject); ratesCursor.sort(sortObject); ratesCursor.limit(5); BasicDBList moviesRecomendados = new BasicDBList(); while (ratesCursor.hasNext()) { BasicDBObject rate = (BasicDBObject) ratesCursor.next(); Integer movieID = rate.getInt("movieID"); DBObject movie = moviesCollection.findOne(new BasicDBObject("_id", movieID)); moviesRecomendados.add(movie); } // System.out.println("Recomendao para " + user.getInt("_id") + ":"); // for (Object movie : moviesRecomendados) { // System.out.println("\t" + movie); // } // System.out.println(); long finishTimeUser = System.currentTimeMillis(); System.out.print("Tempo de execuo para recomendar o user " + user.getInt("_id") + ": "); System.out.println(((double) (finishTimeUser - startTimeUser)) / 1000.0 + " segundos."); soma += ((double) (finishTimeUser - startTimeUser)) / 1000.0; // break; } System.out.println(); System.out.println("Mdia de tempo de execuo para cada usurio: " + soma / 943.0 + " segundos."); System.out.println(); long finishTime = System.currentTimeMillis(); System.out.print("Tempo de execuo do algortmo: "); System.out.println(((double) (finishTime - startTime)) / 1000.0 + " segundos."); }
From source file:uk.ac.soton.itinnovation.sad.service.helpers.PluginsHelper.java
License:Open Source License
/** * @param type data type./*from w w w. j a va 2 s . c o m*/ * @param num_posts number of ites to retrieve from the database. * @return all input data items as JSON from the database. */ public ArrayList<JSONObject> getInputData(String type, String num_posts) { logger.debug("Request: input data for job [" + getJobId() + "] of type '" + type + "' with limit of '" + num_posts + "' posts"); ArrayList<JSONObject> result = new ArrayList<>(); if (jobInputs == null) { logger.error("Job inputs are NULL"); return result; } if (jobInputs.isEmpty()) { logger.error("Job inputs are EMPTY"); return result; } int numInputs = jobInputs.size(); ArrayList<String> input_jobIds = new ArrayList<>(); ArrayList<String> input_pluginNames = new ArrayList<>(); JSONObject tempInput; String temp_input_pluginName, temp_input_jobId; for (int i = 0; i < numInputs; i++) { tempInput = jobInputs.getJSONObject(i); if (tempInput.containsKey("job_id")) { temp_input_jobId = tempInput.getString("job_id"); input_jobIds.add(temp_input_jobId); logger.debug("Detected input 'job_id': " + temp_input_jobId); } if (tempInput.containsKey("plugin_name")) { temp_input_pluginName = tempInput.getString("plugin_name"); input_pluginNames.add(temp_input_pluginName); logger.debug("Detected input 'plugin_name': " + temp_input_pluginName); } } if (input_pluginNames.isEmpty() && input_jobIds.isEmpty()) { logger.error("No input values found for keys 'job_id' or 'plugin_name'"); return result; } if (!input_jobIds.isEmpty()) { logger.debug("Using " + input_jobIds.size() + " job IDs to get job data"); } if (!input_pluginNames.isEmpty()) { logger.debug("Using " + input_pluginNames.size() + " plugin names to get job data"); } int num_posts_int; if (num_posts == null) { num_posts_int = -1; } else if (num_posts.replace("\\s+", "").trim().length() < 1) { num_posts_int = -1; } else if (num_posts.equals("all")) { num_posts_int = -1; } else { try { num_posts_int = Integer.parseInt(num_posts); } catch (NumberFormatException ex) { logger.error("Failed to convert input string num_posts '" + num_posts + "' to integer"); num_posts_int = -1; } } logger.debug("Searching database using " + num_posts_int + " as the number of posts. If '-1', returning all posts."); DBCollection collection = coordinator.getDBCollection(SADCollections.SADJobData); BasicDBObject filter, sorter = new BasicDBObject("whenCollected", -1); DBCursor cursor; DBObject object; SADJobData sadjd; ArrayList<SADJobData> jobData = new ArrayList<>(); if (!input_pluginNames.isEmpty()) { for (String input_pluginName : input_pluginNames) { filter = new BasicDBObject("pluginName", input_pluginName); cursor = collection.find(filter).sort(sorter); if (num_posts_int > 0) { cursor = cursor.limit(num_posts_int); } while (cursor.hasNext()) { object = cursor.next(); sadjd = dh.dBObjectToSADJobData(object); jobData.add(sadjd); } } } if (!input_jobIds.isEmpty()) { // Using job ids as an input for (String input_jobId : input_jobIds) { filter = new BasicDBObject("SADJobID", new ObjectId(input_jobId)); cursor = collection.find(filter).sort(sorter); if (num_posts_int > 0) { cursor = cursor.limit(num_posts_int); } while (cursor.hasNext()) { object = cursor.next(); sadjd = dh.dBObjectToSADJobData(object); jobData.add(sadjd); } } } if (jobData.isEmpty()) { logger.debug("No database entries where found"); return result; } else { logger.debug("Processing " + jobData.size() + " data entries"); String returnResultsOfType; if (type == null) { returnResultsOfType = null; } else if (type.replace("\\s+", "").trim().length() < 1) { returnResultsOfType = null; } else { returnResultsOfType = type; } if (returnResultsOfType == null) { logger.debug("Looking for data of any type"); } else { logger.debug("Looking for data of type '" + returnResultsOfType + "'"); } for (SADJobData dataEntry : jobData) { if (returnResultsOfType != null) { if (dataEntry.getDataType().equalsIgnoreCase(returnResultsOfType)) { result.add(JSONObject.fromObject(dataEntry.getJsonData())); } } else { result.add(JSONObject.fromObject(dataEntry.getJsonData())); } } logger.debug("Returning " + result.size() + " input data items"); return result; } }
From source file:v7views.mongo.DBCollectionDataProvider.java
License:Open Source License
public Iterable<BSONBackedObject> getData() { int start = table.getFirstRow(); int pageSize = table.getPageSize(); if (ids != null) { // skip and pageSize if (start >= ids.size()) return Collections.emptyList(); int toIndex = Integer.MAX_VALUE; if (pageSize > 0) toIndex = start + pageSize;//from ww w . j ava2 s . c o m if (toIndex > ids.size()) toIndex = ids.size(); final List<Object> page = ids.subList(start, toIndex); return new Iterable<BSONBackedObject>() { public Iterator<BSONBackedObject> iterator() { final Iterator<Object> p = page.iterator(); Iterator<BSONObject> x = new Iterator<BSONObject>() { public boolean hasNext() { return p.hasNext(); } public BSONObject next() { return collection.findOne(p.next()); } public void remove() { throw new UnsupportedOperationException(); } }; return BSONBackedObjectLoader.wrapIterator(x, null); } }; } DBCursor cursor = collection.find(query).sort(orderBy).skip(start); if (pageSize > 0) cursor = cursor.limit(pageSize); return BSONBackedObjectLoader.wrapIterable(cursor, null); }
From source file:xbdd.webapp.resource.feature.AutomationStatistics.java
License:Apache License
@GET @Path("/recent-builds/{product}") public DBObject getRecentBuildStatsForProduct(@BeanParam final Coordinates coordinates, @QueryParam("limit") final Integer limit) { final BasicDBList returns = new BasicDBList(); final DB db = this.client.getDB("bdd"); final DBCollection collection = db.getCollection("reportStats"); final BasicDBObject example = coordinates.getQueryObject(Field.PRODUCT); final DBCursor cursor = collection.find(example).sort(Coordinates.getFeatureSortingObject()); if (limit != null) { cursor.limit(limit); }//www . j a v a2s.c om try { while (cursor.hasNext()) { final DBObject doc = cursor.next(); returns.add(doc); } } finally { cursor.close(); } return returns; }
From source file:xbdd.webapp.resource.feature.AutomationStatistics.java
License:Apache License
/** * Go through the prior versions of this product; for each version, find the latest build and contribute the stats for that to the * returned list./*from w w w.j av a 2 s .com*/ * * @param coordinates * @param limit * @return A list of report stats in reverse version order. * @throws UnknownHostException */ @GET @Path("/recent-versions/{product}") public DBObject getRecentVersionStatsForProduct(@BeanParam final Coordinates coordinates, @QueryParam("limit") final Integer limit) { final BasicDBList returns = new BasicDBList(); final DB db = this.client.getDB("bdd"); final DBCollection summaryCollection = db.getCollection("summary"); final DBCollection reportStatsCollection = db.getCollection("reportStats"); final DBCursor versions = summaryCollection.find(coordinates.getQueryObject(Field.PRODUCT)) .sort(Coordinates.getFeatureSortingObject()); if (limit != null) { versions.limit(limit); } try { while (versions.hasNext()) { // go through each summary document final DBObject version = versions.next(); // each represents the coordinates for a given version final Coordinates c = new Coordinates((DBObject) version.get("coordinates")); final BasicDBList builds = (BasicDBList) version.get("builds"); c.setBuild((String) builds.get(builds.size() - 1)); // we need to specify which build (the latest is last in the list) final DBObject query = c.getQueryObject(); returns.add(reportStatsCollection.findOne(query)); } } finally { versions.close(); } return returns; }
From source file:xbdd.webapp.resource.feature.Report.java
License:Apache License
@GET @Path("/{product}/{major}.{minor}.{servicePack}/{build}") @Produces("application/json") public DBObject getReportByProductVersionId(@BeanParam final Coordinates coordinates, @QueryParam("searchText") final String searchText, @QueryParam("viewPassed") final Integer viewPassed, @QueryParam("viewFailed") final Integer viewFailed, @QueryParam("viewUndefined") final Integer viewUndefined, @QueryParam("viewSkipped") final Integer viewSkipped, @QueryParam("start") final String start, @QueryParam("limit") final Integer limit) { final BasicDBObject example = QueryBuilder.getInstance().buildFilterQuery(coordinates, searchText, viewPassed, viewFailed, viewUndefined, viewSkipped, start); final DB db = this.client.getDB("bdd"); final DBCollection collection = db.getCollection("features"); final DBCursor cursor = collection.find(example).sort(Coordinates.getFeatureSortingObject()); try {/*from w w w.j a va 2 s. c o m*/ if (limit != null) { cursor.limit(limit); } final BasicDBList featuresToReturn = new BasicDBList(); while (cursor.hasNext()) { featuresToReturn.add(cursor.next()); } embedTestingTips(featuresToReturn, coordinates, db); return featuresToReturn; } finally { cursor.close(); } }