public MongoTable(String host, String port, String dbName, String collectionName) { try { this.db = new Mongo(host, Integer.valueOf(port)).getDB(dbName); this.collection = db.getCollection(collectionName); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } }
public DbLogger(String dbHost, int dbPort, String dbName, String collectionName) { Mongo mongo; try { mongo = new Mongo(dbHost, dbPort); DB db = mongo.getDB(dbName); dbCollection = db.getCollection(collectionName); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } }
private static Mongo getMongo() { if (mongo == null) { try { mongo = new Mongo(HOST, PORT); System.out.println("New Mongo created with [" + HOST + "] and [" + PORT + "]"); } catch (MongoException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } } return mongo; }
public MongoDBGroup() { try { m = new Mongo(sHost); DB db = m.getDB(sDB); collection = db.getCollection(sCollection); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MongoException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** @throws NullPointerException */ public static void PrintHighestJerseyNumber() throws NullPointerException { Mongo m = null; try { m = new Mongo("dbh63.mongolab.com", 27637); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } DB trendrr = m.getDB("trendrr"); /* authentication line */ trendrr.authenticate("", "".toCharArray()); DBCollection players = trendrr.getCollection("players"); BasicDBObject query = new BasicDBObject(); query.put("team", "jets"); query.put("position", "wr"); DBCursor cur = players.find(query); int maxJerseyNumber = 0; String playerName = ""; while (cur.hasNext()) { DBObject playerDetails = cur.next(); String nameAndNumber = playerDetails.get("name").toString(); String NameNumberTokens[] = nameAndNumber.split(","); try { if (NameNumberTokens.length != 2) { System.out.println("Invalid name field in the database"); System.out.println( "Name: " + NameNumberTokens[0] + " Jersey Number: " + NameNumberTokens[1]); } } catch (NullPointerException e) { System.out.println("NULL value in name field " + e); continue; } try { if (maxJerseyNumber < Integer.parseInt(NameNumberTokens[1].trim())) { maxJerseyNumber = Integer.parseInt(NameNumberTokens[1].trim()); playerName = NameNumberTokens[0]; } } catch (NumberFormatException e) { System.out.println("Invalid data in name field " + e); continue; } } System.out.println("Player Name: " + playerName); }
public static void put(String id, String msg) { try { DBCollection message = Database.gardensharing().getCollection("message"); BasicDBObject document = new BasicDBObject(); document.put("id", id); document.put("msg", msg); message.insert(document); } catch (MongoException e) { e.printStackTrace(); } // messages.put(id, msg); }
public String returnAllEmployees() throws Exception { ToJson converter = new ToJson(); // JSONArray json = new JSONArray(); String json = ""; try { /** ** Connect to MongoDB *** */ // Since 2.10.0, uses MongoClient // MongoClient mongo = new MongoClient("localhost", 27017); MongoClient mongo = new MongoClient("54.214.0.233", 27017); /** ** Get database *** */ // if database doesn't exists, MongoDB will create it for you DB db = mongo.getDB("telemedicine"); /** ** Get collection / table from 'testdb' *** */ // if collection doesn't exists, MongoDB will create it for you DBCollection table = db.getCollection("person"); /** ** Find and display *** */ BasicDBObject searchQuery = new BasicDBObject(); // searchQuery.put("name", name); DBCursor cursor = table.find(); System.out.println(cursor.count()); while (cursor.hasNext()) { System.out.println(cursor.next()); } json = converter.toJsonArray(cursor); } catch (MongoException e) { e.printStackTrace(); } catch (Exception Error) { Error.printStackTrace(); return json; } finally { // if (conn != null) conn.close(); } return json; }
public static void main(String[] args) { try { Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("yourdb"); DBCollection collection = db.getCollection("dummyColl"); System.out.println("Testing 1..."); insertDummyDocuments(collection); // find hosting = hostB, and update it with new document BasicDBObject newDocument = new BasicDBObject(); newDocument.put("hosting", "hostB"); newDocument.put("type", "shared host"); newDocument.put("clients", 111); collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument); printAllDocuments(collection); removeAllDocuments(collection); System.out.println("Testing 2..."); insertDummyDocuments(collection); BasicDBObject newDocument2 = new BasicDBObject().append("$inc", new BasicDBObject().append("clients", 99)); collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument2); printAllDocuments(collection); removeAllDocuments(collection); System.out.println("Testing 3..."); insertDummyDocuments(collection); BasicDBObject newDocument3 = new BasicDBObject() .append("$set", new BasicDBObject().append("type", "dedicated server")); collection.update(new BasicDBObject().append("hosting", "hostA"), newDocument3); printAllDocuments(collection); removeAllDocuments(collection); System.out.println("Testing 4..."); insertDummyDocuments(collection); BasicDBObject updateQuery = new BasicDBObject().append("$set", new BasicDBObject().append("clients", "888")); collection.update(new BasicDBObject().append("type", "vps"), updateQuery, false, true); printAllDocuments(collection); removeAllDocuments(collection); System.out.println("Done"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } }
public static Datastore getInstance() { if (ds == null) { Mongo mongo; try { mongo = new Mongo(); ds = new Morphia().createDatastore(mongo, "jg"); ds.ensureIndexes(); ds.ensureCaps(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MongoException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return ds; }
@Override public void update(TestData testData) { try { DB db = MongoDBProvider.getInstance().getDB(); DBCollection coll = db.getCollection("testdata"); BasicDBObject query = new BasicDBObject(); query.put("source", testData.getClassName()); BasicDBObject object = new BasicDBObject(); object.put("source", testData.getClassName()); object.put("fails", testData.getFails()); coll.update(query, object, true, false); } catch (MongoException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } }
public static String get(String id) { // Since 2.10.0, uses MongoClient try { DBCollection message = Database.gardensharing().getCollection("message"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("id", id); DBCursor cursor = message.find(searchQuery); if (cursor.hasNext()) { DBObject object = cursor.next(); return object.toString(); } else { return null; } } catch (MongoException e) { e.printStackTrace(); } return null; }
@Override public List<TestData> getList() { try { DB db = MongoDBProvider.getInstance().getDB(); DBCollection coll = db.getCollection("testdata"); List<TestData> results = new ArrayList<TestData>(); DBCursor cursor = coll.find(); while (cursor.hasNext()) { DBObject result = cursor.next(); TestData testData = new TestData((String) result.get("source"), (Integer) result.get("fails")); results.add(testData); } return results; } catch (MongoException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } return null; }
@Override public TestData get(String className) { DB db = null; try { db = MongoDBProvider.getInstance().getDB(); DBCollection coll = db.getCollection("testdata"); BasicDBObject query = new BasicDBObject(); query.put("source", className); DBCursor cursor = coll.find(query); if (cursor.hasNext()) { DBObject result = cursor.next(); TestData testData = new TestData((String) result.get("source"), (Integer) result.get("fails")); return testData; } } catch (MongoException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } return new TestData(className, 0); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { int l = 0; int k = 0; // String carID = request.getParameter("reservation"); String carCategory = request.getParameter("carCategory"); String carID = request.getParameter("carID"); String start_date_string = request.getParameter("startDate"); String end_date_string = request.getParameter("endDate"); // String start_time_string = request.getParameter("startTime"); // String end_time_string = request.getParameter("endTime"); // start_date_string = start_date_string + start_time_string; // end_date_string = end_date_string + end_time_string; PrintWriter out = response.getWriter(); out.println(start_date_string); try { Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse((start_date_string).trim()); Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse((end_date_string).trim()); // Date startDate = new // SimpleDateFormat("yyyy-MM-ddhh:mm").parse((start_date_string).trim()); // Date endDate = new SimpleDateFormat("yyyy-MM-ddhh:mm").parse((end_date_string).trim()); int diffInDays = (int) ((startDate.getTime() - endDate.getTime()) / (1000 * 60 * 60 * 24)); out.print("the difference is these many days: "); out.println(diffInDays); DB db = mongo.getDB("practice"); DBCollection reservations = db.getCollection("reservations"); DBCursor dbCursor = null; dbCursor = reservations.find(); if (!dbCursor.hasNext()) { out.println("Database is empty"); BasicDBObject doc = new BasicDBObject("carCategory", carCategory) .append("carID", carID) .append("start_date_string", start_date_string) .append("end_date_string", end_date_string); reservations.insert(doc); k = 1; } while (dbCursor.hasNext()) { BasicDBObject bobj = (BasicDBObject) dbCursor.next(); String temp_car_id = (bobj.getString("carID")).trim(); if (temp_car_id.equals(carID)) { String start_date_string_db = (bobj.getString("start_date_string")).trim(); String end_date_string_db = (bobj.getString("end_date_string")).trim(); Date startDate_db = new SimpleDateFormat("yyyy-MM-dd").parse((start_date_string_db).trim()); Date endDate_db = new SimpleDateFormat("yyyy-MM-dd").parse((end_date_string_db).trim()); boolean c1 = startDate.after(startDate_db) && startDate.before(endDate_db); // if(c1)out.println("c1 is true"); // else out.println("c1 is not true"); boolean c2 = endDate.after(startDate_db) && endDate.before(endDate_db); // if(c2)out.println("c2 is true"); // else out.println("c2 is not true"); boolean c3 = startDate_db.after(startDate) && startDate_db.before(endDate); // if(c3)out.println("c3 is true"); // else out.println("c3 is not true"); boolean c4 = endDate_db.after(startDate) && endDate_db.before(endDate); // if(c4)out.println("c4 is true"); // else out.println("c4 is not true"); boolean c5 = (c1 || c2 || c3 || c4); if (c5) { l = l + 1; // out.print(l); // out.println("th loop"); } } } if (l > 0) { out.println("reservation not possible"); } if ((l == 0) && (k == 0)) { BasicDBObject doc = new BasicDBObject("carID", carID) .append("start_date_string", start_date_string) .append("end_date_string", end_date_string); reservations.insert(doc); } } catch (ParseException e) { e.printStackTrace(); } // BasicDBObject query = new BasicDBObject(); // query.put("username", n); // query.put("password", p); // // If the collection does not exists, MongoDB will create it for you // DBCollection loindet = db.getCollection("loindet"); // // collection selected successfully. // DBCursor cursor = loindet.find(query); // //int cnt = 0; // int cnt = loindet.find(query).count(); // if(cnt!=0) // { // PrintWriter out = response.getWriter(); // //out.println("okay"); // HttpSession session = request.getSession(); // session.setAttribute( "sUserName", n ); // response.sendRedirect("index.jsp"); // } // if(cnt == 0) // { // response.sendRedirect("login.jsp"); // } } catch (MongoException e) { e.printStackTrace(); } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HashMapProducts hmp = new HashMapProducts(); hmp.setHashMapProduct(); hmap = hmp.getHashMapProduct(); PrintWriter out = response.getWriter(); HttpSession s = request.getSession(); String username = (String) s.getAttribute("userName"); String role = (String) s.getAttribute("role"); try { out.println("<html>"); out.println("<head>"); out.println("<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"); out.println("<title>GameZon"); out.println("</title>"); out.println("<link rel='stylesheet' href='styles.css' type='text/css' />"); out.println("</head>"); out.println("<body>"); out.println("<div id='container'>"); out.println("<header>"); out.println("<h1>"); out.println("<a href='/'>Game"); out.println("<span>Zon"); out.println("</span>"); out.println("</a>"); out.println("</h1>"); if (username != null) { out.println("<h5 style='float:right'>Welcome " + username + " !</h5>"); } out.println("</header>"); out.println("<nav>"); out.println("<ul>"); out.println("<li>"); out.println("<a href='index.html'>Home"); out.println("</a>"); out.println("</li>"); out.println("<li class=''>"); out.println("<a href='/GameWebsite/Microsoft'>Microsoft"); out.println("</a>"); out.println("</li>"); out.println("<li class=''>"); out.println("<a href='/GameWebsite/Sony'>Sony"); out.println("</a>"); out.println("</li>"); out.println("<li class='end'>"); out.println("<a href='/GameWebsite/Nintendo'>Nintendo"); out.println("</a>"); out.println("</li>"); out.println("<li class='end'>"); out.println("<a href='/GameWebsite/Accessories'>Accessories"); out.println("</a>"); out.println("</li>"); if (username == null) { out.println("<li class='end'>"); out.println("<a href='signin.html'>Sign In"); out.println("</a>"); out.println("</li>"); out.println("<li class='end'>"); out.println("<a href='signup.html'>Sign Up"); out.println("</a>"); out.println("</li>"); } if (role != null) { if (role.equals("customer")) { out.println("<li class='end'><a href='/GameWebsite/MyOrders'>My Orders</a></li>"); out.println("<li class='end'><a href='/GameWebsite/MyCart'>My Cart</a></li>"); } if (role.equals("salesMan")) { out.println("<li ><a href='/GameWebsite/CustomerOrders'>Customer Orders</a></li>"); } if (role.equals("storeManager")) { out.println( "<li class='start selected'><a href='/GameWebsite/UpdateProducts'>Update Products</a></li>"); } } if (username != null) { out.println( "<li class='end' style='float:right'><a href='/GameWebsite/LogOut'>Log Out</a></li>"); } out.println("</ul>"); out.println("</nav>"); out.println( "<img class='header-image' src='images/indexheader.jpg' width = '100%' height = '100%' alt='Index Page Image' />"); out.println("<div id='body'>"); out.println("<section id='content'>"); out.println("<article>"); out.println("<h2>All Orders"); out.println("</h2>"); out.println("<table>"); List<Integer> cartList = new ArrayList<>(); out.println("<tr>"); out.println("<td>"); out.println("</td>"); out.println("</tr>"); out.println("<tr>"); // out.println("<td>"); // out.println("Id"); // out.println("</td>"); out.println("<td>"); out.println("Name"); out.println("</td>"); out.println("<td>"); out.println("Price"); out.println("</td>"); out.println("<td>"); out.println("Action"); out.println("</td>"); out.println("<td>"); out.println("Action"); out.println("</td>"); out.println("</tr>"); /* if(cursor.length()==0) { out.println("<tr><td><h5>No Orders</h5></td></tr>"); }*/ // out.println("<td>"); // out.println(obj.get("_id")); // Object orderId=(Object)obj.get("_id"); // out.println("</td>"); // BasicDBList itemsList = (BasicDBList) obj.get("items"); // out.println(itemsList.get(i)); Iterator<Integer> productIterator = hmap.keySet().iterator(); while (productIterator.hasNext()) { out.println("<tr>"); out.println("<td>"); Integer id = productIterator.next(); Product p = hmap.get(id); out.println(p.Name); out.println("</td>"); out.println("<td>"); out.println(p.price); out.println("</td>"); out.println("<td>"); out.println("<form class = 'submit-button' method = 'get' action = 'UpdateOrder'>"); out.println("<input type='hidden' name = 'productId' value = '" + p.Id + "'>"); out.println("<input type='submit' name = 'quantity' value = 'Update'>"); out.println("</form>"); out.println("</td>"); out.println("<td>"); out.println("<form class = 'submit-button' method = 'get' action = 'DeleteOrder'>"); out.println("<input type='hidden' name = 'productId' value = '" + p.Id + "'>"); out.println("<input type='submit' name = 'quantity' value = 'Delete'>"); out.println("</form>"); out.println("</td>"); out.println("</tr>"); } // cartList=(List<Integer>)obj.get("items"); // for(int c:cartList) // { // out.println(c); // } // out.println(obj.get("username")); // HttpSession s=request.getSession(); // s.setAttribute("userName",uname); // System.out.println("user logged in successfully"); // request.getRequestDispatcher("/Index").forward(request, response); out.println("</table>"); out.println("</article>"); out.println("</section>"); out.println("<aside class='sidebar'>"); out.println("<ul>"); out.println("<li>"); out.println("<h4>Our Products"); out.println("</h4>"); out.println("<ul>"); out.println("<li>"); out.println("<a href='/GameWebsite/Microsoft'>Microsoft"); out.println("</a>"); out.println("</li>"); out.println("<li>"); out.println("<a href='/GameWebsite/Sony'>Sony"); out.println("</a>"); out.println("</li>"); out.println("<li>"); out.println("<a href='/GameWebsite/Nintendo'>Nintendo"); out.println("</a>"); out.println("</li>"); out.println("<li>"); out.println("<a href='/GameWebsite/Accessories'>Accessories"); out.println("</a>"); out.println("</li>"); out.println("</ul>"); out.println("</li>"); out.println("</ul>"); out.println("</aside>"); out.println("<div class='clear'>"); out.println("</div>"); out.println("</div>"); out.println("<footer>"); out.println("<div class='footer-bottom'>"); out.println("<p>Let the Game began !"); out.println("</p>"); out.println("</div>"); out.println("</footer>"); out.println("</div>"); out.println("</body>"); out.println("</html>"); } catch (MongoException e) { e.printStackTrace(); } }
private DBCollection getMongoDBConnection() { String vcap_services = System.getenv("VCAP_SERVICES"); String hostname = NULL_STRING; String dbname = NULL_STRING; String username = NULL_STRING; String password = NULL_STRING; String port = NULL_STRING; if (vcap_services != null && vcap_services.length() > 0) { try { ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getJsonFactory(); JsonParser jp; try { jp = factory.createJsonParser(vcap_services); JsonNode actualObj = mapper.readTree(jp); JsonNode credentials = actualObj.get("mongodb-1.8").get(0).get("credentials"); dbname = credentials.get("name").toString(); hostname = credentials.get("hostname").toString(); username = credentials.get("username").toString(); password = credentials.get("password").toString(); port = credentials.get("port").toString(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("dbname : " + dbname); System.out.println("hostname : " + hostname); System.out.println("port : " + port); System.out.println("user : "******"password : "******"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); Mongo mongo = new Mongo(hostname, Integer.parseInt(port)); mongo.getConnector(); CommandResult auth = mongo.getDB(dbname).authenticateCommand(username, password.toCharArray()); System.out.println(auth); DB db = mongo.getDB(dbname); // db.authenticate(username, password.toCharArray()); DBCollection collection = db.getCollection("cloudfoundry"); BasicDBObject doc = new BasicDBObject("name", "MongoDB") .append("type", "database") .append("count", 1) .append("info", new BasicDBObject("x", 201).append("y", 102)); collection.insert(doc); DBObject myDoc = collection.findOne(); System.out.println(myDoc); return collection; } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } } else { try { Mongo mongo = new Mongo("192.168.1.172", 25004); mongo.getConnector(); System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); CommandResult auth = mongo .getDB("3829864b-7a61-4bd7-be70-7627b7e044ad") .authenticateCommand( "ecf963e6-92e7-49d6-a3c5-0ea6ee4cf586", "cb3c03ad-8731-4d8e-ac81-c139ce2ed4c3".toCharArray()); System.out.println(auth); DB db = mongo.getDB("3829864b-7a61-4bd7-be70-7627b7e044ad"); DBCollection collection = db.getCollection("cloudfoundry"); /* BasicDBObject doc = new BasicDBObject("name", "MongoDB") .append("type", "database") .append("count", 1) .append("info", new BasicDBObject("x", 203).append("y", 102)); collection.insert(doc); DBObject myDoc = collection.findOne(); System.out.println(myDoc); */ return collection; } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } } return null; }
public static void main(String[] args) { try { /** ** Connect to MongoDB *** */ // Since 2.10.0, uses MongoClient MongoClient mongo = new MongoClient("localhost", 27017); /** ** Get database *** */ // if database doesn't exists, MongoDB will create it for you DB db = mongo.getDB("testdb"); /** ** Get collection / table from 'testdb' *** */ // if collection doesn't exists, MongoDB will create it for you DBCollection table = db.getCollection("user"); /** ** Insert *** */ // create a document to store key and value BasicDBObject document = new BasicDBObject(); document.put("name", "mkyong"); document.put("age", 30); document.put("createdDate", new Date()); table.insert(document); /** ** Find and display *** */ BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("name", "mkyong"); DBCursor cursor = table.find(searchQuery); while (cursor.hasNext()) { System.out.println(cursor.next()); } /** ** Update *** */ // search document where name="mkyong" and update it with new values BasicDBObject query = new BasicDBObject(); query.put("name", "mkyong"); BasicDBObject newDocument = new BasicDBObject(); newDocument.put("name", "mkyong-updated"); BasicDBObject updateObj = new BasicDBObject(); updateObj.put("$set", newDocument); table.update(query, updateObj); /** ** Find and display *** */ BasicDBObject searchQuery2 = new BasicDBObject().append("name", "mkyong-updated"); DBCursor cursor2 = table.find(searchQuery2); while (cursor2.hasNext()) { System.out.println(cursor2.next()); } /** ** Done *** */ System.out.println("Done"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } }
public void receiveData( String ip, String paramName, String paramNo, int paramBote, int paramLength, int parmParity, int parmStopBit, int parmDelay) { try { try { m = new Mongo(ip, 27017); db = m.getDB(paramName); // db.authenticate("test", "123".toCharArray()); } catch (UnknownHostException ex) { ex.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } final DBCollection coll = db.getCollection("DATAIN"); final DBCollection collout = db.getCollection("DATAOUT"); DBCollection meta = db.getCollection("META"); // 记录数据字段 final Map map1 = new HashMap(); final Map map2 = new HashMap(); Map map00 = new HashMap(); Map map01 = new HashMap(); Map map02 = new HashMap(); Map map03 = new HashMap(); final Map m_ai_max = new HashMap(); final Map m_ai_min = new HashMap(); final Map m_ao_max = new HashMap(); final Map m_ao_min = new HashMap(); DBCursor cursor = meta.find(); while (cursor.hasNext()) { // 记录数据类型 DBObject dbo = cursor.next(); String name = dbo.get("_id").toString(); String type = dbo.get("type").toString(); String addr = dbo.get("addr").toString(); Double max = (Double) dbo.get("max"); Double min = (Double) dbo.get("min"); if (type.equals("AI")) { map00.put(name, addr); m_ai_max.put(name, max); m_ai_min.put(name, min); } if (type.equals("DI")) { map01.put(name, addr); } if (type.equals("AO")) { map02.put(name, addr); } if (type.equals("DO")) { map03.put(name, addr); } } map1.put("AI", map00); map1.put("DI", map01); map2.put("AO", map02); map2.put("DO", map03); SerialParameters params = new SerialParameters(); params.setCommPortId(paramNo); params.setBaudRate(paramBote); params.setDataBits(paramLength); params.setParity(parmParity); params.setStopBits(parmStopBit); ModbusFactory modbusFactory = new ModbusFactory(); slave = modbusFactory.createRtuSlave(params); slave.addProcessImage(getModscanProcessImage(1, map00, coll)); slave.addProcessImage(getModscanProcessImage(2, map01, coll)); slave.addProcessImage(getModscanProcessImage(3, map02, collout)); slave.addProcessImage(getModscanProcessImage(4, map03, collout)); new Thread( new Runnable() { public void run() { try { slave.start(); // JOptionPane.showMessageDialog(f, "通讯连接成功!"); } catch (ModbusInitException e) { e.printStackTrace(); } } }) .start(); ScheduledExecutorService timerRead = Executors.newScheduledThreadPool(1); timerRead.scheduleAtFixedRate( new Runnable() { public void run() { new TaskRead(map1, m_ai_max, m_ai_min, coll, slave); } }, 500, parmDelay, TimeUnit.MILLISECONDS); ScheduledExecutorService timerWrite = Executors.newScheduledThreadPool(2); timerWrite.scheduleAtFixedRate( new Runnable() { public void run() { new TaskWrite(map2, m_ao_max, m_ao_min, collout, slave); } }, 500, parmDelay, TimeUnit.MILLISECONDS); } catch (Exception ex) { } }
public static void main(String[] args) { try { // connect to mongoDB, ip and port number Mongo mongo = new Mongo("127.0.0.1", 27017); // get database from MongoDB, // if database doesn't exists, mongoDB will create it automatically DB db = mongo.getDB("yourdb"); // Getting A List Of Collections Set<String> collections = db.getCollectionNames(); for (String s : collections) { System.out.println(s); } // Get collection from MongoDB, database named "yourDB" // if collection doesn't exists, mongoDB will create it automatically DBCollection collection = db.getCollection("yourCollection"); // create a document to store key and value DBObject document = new BasicDBObject(); document.put("id", 1001); document.put("msg", "hello world mongoDB in Java"); // save it into collection named "yourCollection" collection.insert(document); // search query DBObject searchQuery = new BasicDBObject(); searchQuery.put("id", 1001); // query it DBCursor cursor = collection.find(searchQuery); // loop over the cursor and display the retrieved result while (cursor.hasNext()) { System.out.println("Our collection after putting document here: " + cursor.next()); } // Counting Documents in Collection System.out.println("Elements in collection " + collection.getCount()); // update document (just replase exist - it is normal practise) DBObject updatedDocument = new BasicDBObject(); updatedDocument.put("id", 1001); updatedDocument.put("msg", "hello world mongoDB in Java updated"); collection.update(new BasicDBObject().append("id", 1001), updatedDocument); // query it DBCursor cursorAfterUpdate = collection.find(searchQuery); // loop over the cursor and display the retrieved result while (cursorAfterUpdate.hasNext()) { System.out.println("Our collection after update: " + cursorAfterUpdate.next()); } // Counting Documents in Collection System.out.println("Elements in collection " + collection.getCount()); // Map to object Message message = new Message(); message.setId((Integer) document.get("id")); message.setMessage((String) document.get("msg")); System.out.println("Id putted in object: " + message.getId()); System.out.println("Message putted in object: " + message.getMessage()); // Remove document from collection DBObject doc = collection.findOne(); // get first document collection.remove(doc); // query it DBCursor cursorAfterDelete = collection.find(searchQuery); // loop over the cursor and display the retrieved result while (cursorAfterDelete.hasNext()) { System.out.println("Our collection after delete: " + cursorAfterDelete.next()); } // Counting Documents in Collection System.out.println("Elements in collection " + collection.getCount()); // Close connection to db mongo.close(); System.out.println("Done"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } }