List of usage examples for com.mongodb.client MongoCursor next
@Override TResult next();
From source file:com.spleefleague.superspleef.game.TeamSpleefArena.java
public static void init() { arenas = new HashMap<>(); MongoCursor<Document> dbc = SuperSpleef.getInstance().getPluginDB().getCollection("Arenas") .find(new Document("spleefMode", "TEAM")).iterator(); while (dbc.hasNext()) { TeamSpleefArena arena = EntityBuilder.load(dbc.next(), TeamSpleefArena.class); arenas.put(arena.getName(), arena); SuperSpleef.getInstance().getBattleManager().registerArena(arena); }/*www . java 2s . co m*/ SuperSpleef.getInstance().log("Loaded " + arenas.size() + " team spleef arenas!"); }
From source file:com.streamsets.pipeline.stage.processor.mongodb.MongoDBLookupLoader.java
License:Apache License
private Optional<List<Map<String, Field>>> lookupValuesForRecord(Document doc) throws StageException { List<Map<String, Field>> lookupItems = new ArrayList<>(); if (LOG.isTraceEnabled()) { LOG.trace("Going to lookup with:" + doc.toJson()); }//from ww w . j ava2 s . c o m FindIterable<Document> it = mongoCollection.find(doc); if (it.first() != null) { MongoCursor<Document> ite = it.iterator(); while (ite.hasNext()) { Document result = ite.next(); if (LOG.isTraceEnabled()) { LOG.trace("Found document:" + result.toJson()); } try { Map<String, Field> fields = MongoDBUtil.createFieldFromDocument(result); lookupItems.add(fields); } catch (IOException io) { LOG.error(Errors.MONGODB_06.getMessage(), mongoCollection, result.toJson()); throw new OnRecordErrorException(Errors.MONGODB_10, result.toJson()); } } } else { // no lookup result. return Optional.empty(); } return Optional.of(lookupItems); }
From source file:com.um.mongodb.converter.EhealthRecordConverter.java
/** * /*from ww w. ja v a 2 s.c o m*/ * @param ags * @return */ public static int main(String[] ags) { MongoClient client = new MongoClient("localhost", 27017); if (client != null) { System.out.println("success"); } else { System.out.println("failed"); } MongoDatabase database = client.getDatabase("db"); if (database == null) { System.out.println("db is null"); } else { System.out.println("db is not null"); } MongoCollection<Document> collection = database.getCollection("ehealth"); // System.out.println(collection.count()); MongoCursor<Document> cursor = collection .find(new BasicDBObject("ehealthrecord.registrationno", "600025873102")).iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } return 0; }
From source file:com.yahoo.ycsb.db3.MongoDbClient.java
License:Open Source License
/** * Perform a range scan for a set of records in the database. Each field/value * pair from the result will be stored in a HashMap. * //w w w. j a va 2 s . c om * @param table * The name of the table * @param startkey * The record key of the first record to read. * @param recordcount * The number of records to read * @param fields * The list of fields to read, or null for all of them * @param result * A Vector of HashMaps, where each HashMap is a set field/value * pairs for one record * @return Zero on success, a non-zero error code on error. See the {@link DB} * class's description for a discussion of error codes. */ @Override public Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { MongoCursor<Document> cursor = null; try { MongoCollection<Document> collection = database.getCollection(table); Document scanRange = new Document("$gte", startkey); Document query = new Document("_id", scanRange); Document sort = new Document("_id", INCLUDE); FindIterable<Document> findIterable = collection.find(query).sort(sort).limit(recordcount); if (fields != null) { Document projection = new Document(); for (String fieldName : fields) { projection.put(fieldName, INCLUDE); } findIterable.projection(projection); } cursor = findIterable.iterator(); if (!cursor.hasNext()) { System.err.println("Nothing found in scan for key " + startkey); return Status.ERROR; } result.ensureCapacity(recordcount); while (cursor.hasNext()) { HashMap<String, ByteIterator> resultMap = new HashMap<String, ByteIterator>(); Document obj = cursor.next(); fillMap(resultMap, obj); result.add(resultMap); } return Status.OK; } catch (Exception e) { System.err.println(e.toString()); return Status.ERROR; } finally { if (cursor != null) { cursor.close(); } } }
From source file:course.homework.Homework3.java
License:Apache License
public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase database = client.getDatabase("school"); MongoCollection<Document> collection = database.getCollection("students"); MongoCursor<Document> iterator = collection.find().iterator(); while (iterator.hasNext()) { Document doc = iterator.next(); List<Document> scores = (List<Document>) doc.get("scores"); Optional<Document> bestHomeWork = scores.stream() .max((a, b) -> a.getString("type").equals("homework") && b.getString("type").equals("homework") ? Double.compare(a.getDouble("score"), b.getDouble("score")) : -1);/*w w w.jav a 2 s . co m*/ Double bestScore = bestHomeWork.get().getDouble("score"); List<Document> result = scores.stream() .filter(x -> !x.getString("type").equals("homework") || x.getDouble("score").equals(bestScore)) .collect(Collectors.toList()); collection.updateOne(eq("_id", doc.get("_id")), new Document("$set", new Document("scores", result))); } iterator.close(); client.close(); }
From source file:course.homework.week2.RemoveLowest.java
License:Apache License
public static void main(final String[] args) { MongoClient client = new MongoClient(); MongoDatabase numbersDB = client.getDatabase("students"); MongoCollection<Document> grades = numbersDB.getCollection("grades"); MongoCursor<Document> cursor = grades.find(eq("type", "homework")).sort(ascending("student_id", "score")) .iterator();//from ww w . jav a2 s .c o m Object studentId = -1; try { while (cursor.hasNext()) { Document entry = cursor.next(); if (!entry.get("student_id").equals(studentId)) { System.out.println("Removing: " + entry); Object id = entry.get("_id"); grades.deleteOne(eq("_id", id)); } studentId = entry.get("student_id"); } } finally { cursor.close(); } }
From source file:course.PrivateCloudController.java
License:Apache License
private void initializeRoutes() throws IOException { // this is the blog home page get(new FreemarkerBasedRoute("/", "blog_template.ftl") { @Override//from w ww . jav a 2s.c o m public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); // this is where we would normally load up the blog data // but this week, we just display a placeholder. HashMap<String, String> root = new HashMap<String, String>(); template.process(root, writer); } }); get(new FreemarkerBasedRoute("/display_vms", "display_vms.ftl") { @Override public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { //String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); List<Document> posts = new ArrayList<Document>();// = statsDAO.findByDateDescending(10); ManagedEntity[] mes = new InventoryNavigator(Path).searchManagedEntities("VirtualMachine"); SimpleHash root = new SimpleHash(); System.out.println("Display VM: VM list"); BasicDBObject query = new BasicDBObject(); VMsDBCollection.deleteMany(query); //HashMap<String, String> root = new HashMap<String, String>(); if (!(mes == null || mes.length == 0)) { for (int i = 0; i < mes.length; i++) { Document text = new Document(); VirtualMachine vm = (VirtualMachine) mes[i]; if (!vm.getName().contains("Template")) { String name = vm.getName(); text.append("name", name); Document DB_VMs = new Document("_id", name); if (vm.getConfig() != null) { String instanceId = vm.getConfig().getInstanceUuid(); text.append("instanceId", instanceId); } System.out.println("VM Name : " + name); String conectionState = vm.getRuntime().getConnectionState().toString(); text.append("conectionState", conectionState); DB_VMs.append("conectionState", conectionState); String ip = vm.getGuest().getIpAddress(); text.append("ip", ip); DB_VMs.append("ip", ip); String powerState = vm.getRuntime().getPowerState().toString(); text.append("powerState", powerState); if (vm.getTriggeredAlarmState() == null) { text.append("alarmState", "notTriggered"); DB_VMs.append("powerState", "notTriggered"); } else { text.append("alarmState", "Triggered"); DB_VMs.append("powerState", "Triggered"); } String launchTime = writeActualDate(vm.getRuntime().getBootTime()); text.append("launchTime", launchTime); DB_VMs.append("launchTime", launchTime); posts.add(text); VMsDBCollection.insertOne(DB_VMs); } } } root.put("VMs", posts); template.process(root, writer); } }); get(new FreemarkerBasedRoute("/create_vm", "create_vm.ftl") { @Override public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); System.out.println("Inside Create VM backend"); template.process(root, writer); } }); post(new FreemarkerBasedRoute("/create_vm", "/create_vm.ftl") { @Override public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { if (request.queryParams("Create") != null) { ManagedEntity[] mes = new InventoryNavigator(Path).searchManagedEntities("VirtualMachine"); //Clone VM String vmname = request.queryParams("vmname"); String vm_template = request.queryParams("OS"); VirtualMachine vm = (VirtualMachine) new InventoryNavigator(Path) .searchManagedEntity("VirtualMachine", vm_template); VirtualMachineRuntimeInfo vmri = vm.getRuntime(); HostSystem hs = new HostSystem(vm.getServerConnection(), vmri.getHost()); Datacenter dc = (Datacenter) new InventoryNavigator(Path).searchManagedEntity("Datacenter", "T03-DC"); ResourcePool rp = (ResourcePool) new InventoryNavigator(dc) .searchManagedEntities("ResourcePool")[0]; if (vm == null) { System.out.println("No VM found with name " + vm_template); SimpleHash root = new SimpleHash(); root.put("login_error", "No template available"); template.process(root, writer); } else { try { VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); VirtualMachineRelocateSpec locateSpec = new VirtualMachineRelocateSpec(); locateSpec.setPool(rp.getMOR()); cloneSpec.setLocation(locateSpec); cloneSpec.setPowerOn(false); cloneSpec.setTemplate(false); Task task = vm.cloneVM_Task((Folder) vm.getParent(), vmname, cloneSpec); System.out.println("Launching the VM clone task. " + "Please wait ..."); /*String status = task.waitForTask(); if (status == Task.SUCCESS) { System.out.println("VM got cloned successfully."); } else { System.out.println("Failure -: VM cannot be cloned"); }*/ } catch (Exception e) { e.printStackTrace(); } response.redirect("/display_vms"); } } else if (request.queryParams("Cancel") != null) { response.redirect("/display_vms"); } } }); post(new FreemarkerBasedRoute("/display_vms", "display_vms.ftl") { @Override public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { //String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); List<Document> posts = new ArrayList<Document>();// = statsDAO.findByDateDescending(10); SimpleHash root = new SimpleHash(); BasicDBObject query = new BasicDBObject(); ArrayList<String> VM_list = new ArrayList<String>(); MongoCursor<Document> cursor = VMsDBCollection.find(query).iterator(); while (cursor.hasNext()) { String a = cursor.next().toJson(); System.out.println(a); try { JSONObject jsonObject = new JSONObject(a); String vm_name = jsonObject.getString("_id"); VM_list.add(vm_name); } catch (JSONException e) { e.printStackTrace(); } } //take VM list from DB if (request.queryParams("PowerOn") != null) { Iterator vm_iterator = VM_list.iterator(); while (vm_iterator.hasNext()) { String VM_name = vm_iterator.next().toString(); boolean myCheckBox = request.queryParams(VM_name) != null; if (myCheckBox) { System.out.println("Power ON VM " + VM_name); powerOn(VM_name); } } response.redirect("/display_vms"); } else if (request.queryParams("PowerOff") != null) { Iterator vm_iterator = VM_list.iterator(); while (vm_iterator.hasNext()) { String VM_name = vm_iterator.next().toString(); boolean myCheckBox = request.queryParams(VM_name) != null; if (myCheckBox) { System.out.println("Power Off VM " + VM_name); powerOff(VM_name); } } response.redirect("/display_vms"); } else if (request.queryParams("Delete") != null) { Iterator vm_iterator = VM_list.iterator(); while (vm_iterator.hasNext()) { String VM_name = vm_iterator.next().toString(); boolean myCheckBox = request.queryParams(VM_name) != null; if (myCheckBox) { System.out.println("Delete VM " + VM_name); deleteVM(VM_name); } } response.redirect("/display_vms"); } else if (request.queryParams("Get_Chart") != null) { Iterator vm_iterator = VM_list.iterator(); while (vm_iterator.hasNext()) { String VM_name = vm_iterator.next().toString(); boolean myCheckBox = request.queryParams(VM_name) != null; if (myCheckBox) { System.out.println("Get VM " + VM_name + " Charts"); CurrentSelectedVM = VM_name; } } response.redirect("/gChart"); } else if (request.queryParams("Create") != null) { response.redirect("/create_vm"); } else { System.out.println("Invalid "); response.redirect("/display_vms"); // ??? } } }); // google chart handler get(new FreemarkerBasedRoute("/gChart", "GoogleLine.ftl") { @Override public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); if (CurrentSelectedVM != null) { ArrayList<ArrayList> gchartMData = statsDAO.getMGchart(CurrentSelectedVM); ArrayList<ArrayList> gchartCData = statsDAO.getCGchart(CurrentSelectedVM); SimpleHash root = new SimpleHash(); root.put("VMName", CurrentSelectedVM); BasicDBObject query = new BasicDBObject(); query.put("_id", CurrentSelectedVM); MongoCursor<Document> cursor = VMsDBCollection.find(query).iterator(); while (cursor.hasNext()) { String a = cursor.next().toJson(); System.out.println("Json :::: \n" + a); try { JSONObject jsonObject = new JSONObject(a); if (jsonObject.has("ip") && jsonObject.has("_id")) { root.put("IPAD", jsonObject.getString("ip")); System.out.println("IP address for this VM is " + jsonObject.getString("ip")); } } catch (JSONException e) { e.printStackTrace(); } } if (CurrentSelectedVM.contains("Lin")) root.put("vm_type", "Lin"); else if (CurrentSelectedVM.contains("Win")) root.put("vm_type", "Win"); CurrentSelectedVM = null; root.put("usernameVM", "administrator"); root.put("passwordVM", "12!@qwQW"); root.put("gcdata1", gchartMData); root.put("gcdata2", gchartCData); //System.out.println(gchartData); // System.out.println(gchartData.get(0)); template.process(root, writer); } } }); post(new FreemarkerBasedRoute("/gChart", "GoogleLine.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { if (request.queryParams("Home") != null) { response.redirect("/display_vms"); } } }); // handle the signup post post(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String email = request.queryParams("email"); String username = request.queryParams("username"); String password = request.queryParams("password"); String verify = request.queryParams("verify"); HashMap<String, String> root = new HashMap<String, String>(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("email", StringEscapeUtils.escapeHtml4(email)); if (validateSignup(username, password, verify, email, root)) { // good user System.out.println("Signup: Creating user with: " + username + " " + password); if (!userDAO.addUser(username, password, email)) { // duplicate user root.put("username_error", "Username already in use, Please choose another"); template.process(root, writer); } else { // good user, let's start a session String sessionID = sessionDAO.startSession(username); System.out.println("Session ID is" + sessionID); response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/login"); } } else { // bad signup System.out.println("User Registration did not validate"); template.process(root, writer); } } }); // present signup form for blog get(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); // initialize values for the form. root.put("username", ""); root.put("password", ""); root.put("email", ""); root.put("password_error", ""); root.put("username_error", ""); root.put("email_error", ""); root.put("verify_error", ""); template.process(root, writer); } }); get(new FreemarkerBasedRoute("/welcome", "welcome.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String cookie = getSessionCookie(request); String username = sessionDAO.findUserNameBySessionId(cookie); if (username == null) { System.out.println("welcome() can't identify the user, redirecting to signup"); response.redirect("/signup"); } else { SimpleHash root = new SimpleHash(); root.put("username", username); template.process(root, writer); } } }); // present the login page get(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("username", ""); root.put("login_error", ""); template.process(root, writer); } }); // process output coming from login form. On success redirect folks to the welcome page // on failure, just return an error and let them try again. post(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = request.queryParams("username"); String password = request.queryParams("password"); System.out.println("Login: User submitted: " + username + " " + password); Document user = userDAO.validateLogin(username, password); if (user != null) { // valid user, let's log them in String sessionID = sessionDAO.startSession(user.get("_id").toString()); if (sessionID == null) { response.redirect("/internal_error"); } else { // set the cookie for the user's browser response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/display_vms"); } } else { SimpleHash root = new SimpleHash(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("password", ""); root.put("login_error", "Invalid Login"); template.process(root, writer); } } }); // allows the user to logout of the blog get(new FreemarkerBasedRoute("/logout", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String sessionID = getSessionCookie(request); if (sessionID == null) { // no session to end response.redirect("/login"); } else { // deletes from session table sessionDAO.endSession(sessionID); // this should delete the cookie Cookie c = getSessionCookieActual(request); c.setMaxAge(0); response.raw().addCookie(c); response.redirect("/login"); } } }); // used to process internal errors get(new FreemarkerBasedRoute("/internal_error", "error_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("error", "System has encountered an error."); template.process(root, writer); } }); }
From source file:course.StatsDAO.java
License:Apache License
public ArrayList<ArrayList> getCGchart(String vm) { List<Document> gcdata; BasicDBObject query = new BasicDBObject(); query.put("Name", vm); //gcdata=statsCollection.find(query).into(new ArrayList<Document>()); //System.out.println(gcdata); MongoCursor<Document> cursor = statsCollection.find(query).iterator(); Integer i = 0;/*w w w .j a v a 2 s . c o m*/ ArrayList<ArrayList> finalGraph = new ArrayList<ArrayList>(); while (cursor.hasNext()) { String a = cursor.next().toJson(); //System.out.println(a); try { JSONObject jsonObject = new JSONObject(a); ArrayList<String> drawRow1 = new ArrayList<String>(); drawRow1.add(i.toString()); i++; if (jsonObject.has("MaxMemoryUsage") && jsonObject.has("MaxCPUusage")) { drawRow1.add(jsonObject.getString("MaxCPUusage")); drawRow1.add(jsonObject.getString("overallCpuDemand")); drawRow1.add(jsonObject.getString("overallCpuUsage")); } finalGraph.add(drawRow1); } catch (JSONException e) { e.printStackTrace(); } // memoryData.add(Integer.parseInt(a.g)) } return finalGraph; }
From source file:course.StatsDAO.java
License:Apache License
public ArrayList<ArrayList> getMGchart(String vm) { List<Document> gcdata; BasicDBObject query = new BasicDBObject(); query.put("Name", vm); //gcdata=statsCollection.find(query).into(new ArrayList<Document>()); //System.out.println(gcdata); MongoCursor<Document> cursor = statsCollection.find(query).iterator(); Integer i = 0;/*from ww w . j av a 2 s. c o m*/ ArrayList<ArrayList> finalGraph = new ArrayList<ArrayList>(); while (cursor.hasNext()) { String a = cursor.next().toJson(); System.out.println(a); try { JSONObject jsonObject = new JSONObject(a); ArrayList<String> drawRow = new ArrayList<String>(); drawRow.add(i.toString()); i++; if (jsonObject.has("MaxMemoryUsage") && jsonObject.has("MaxCPUusage")) { drawRow.add(jsonObject.getString("MaxMemoryUsage")); drawRow.add(jsonObject.getString("HostMemoryUsage")); drawRow.add(jsonObject.getString("guestMemoryUsage")); } finalGraph.add(drawRow); } catch (JSONException e) { e.printStackTrace(); } // memoryData.add(Integer.parseInt(a.g)) } return finalGraph; }
From source file:course.StatsDAO.java
License:Apache License
public List<Integer> getMemoryData() { //List<Document> vms=new ArrayList<Document>(); List<Integer> memoryData = new ArrayList<Integer>(); BasicDBObject query = new BasicDBObject(); query.put("IpAdd", "130.65.133.244"); Document filter = new Document(); filter.append("MaxMemoryUsage", 1); MongoCursor<Document> cursor = statsCollection.find(query).iterator(); System.out.println("Inside test"); while (cursor.hasNext()) { String a = cursor.next().toJson(); System.out.println(a);/*from w ww . j av a 2s . c om*/ try { JSONObject jsonObject = new JSONObject(a); memoryData.add(Integer.parseInt(jsonObject.getString("MaxMemoryUsage"))); } catch (JSONException e) { e.printStackTrace(); } // memoryData.add(Integer.parseInt(a.g)) } return memoryData; }