List of usage examples for com.mongodb.client MongoCollection find
FindIterable<TDocument> find(ClientSession clientSession);
From source file:org.codinjutsu.tools.nosql.mongo.logic.SingleMongoClient.java
License:Apache License
public Document findMongoDocument(ServerConfiguration configuration, SingleMongoCollection singleMongoCollection, Object _id) { MongoClient mongo = null;/* w w w . j av a 2 s .c o m*/ try { String databaseName = singleMongoCollection.getDatabaseName(); mongo = createMongoClient(configuration); MongoDatabase database = mongo.getDatabase(databaseName); com.mongodb.client.MongoCollection<Document> collection = database .getCollection(singleMongoCollection.getName()); return collection.find(Filters.eq("_id", _id)).first(); } catch (UnknownHostException ex) { throw new ConfigurationException(ex); } finally { if (mongo != null) { mongo.close(); } } }
From source file:org.codinjutsu.tools.nosql.mongo.logic.SingleMongoClient.java
License:Apache License
private MongoResult find(MongoQueryOptions mongoQueryOptions, final MongoResult mongoResult, MongoCollection<Document> collection) { Bson filter = mongoQueryOptions.getFilter(); Bson projection = mongoQueryOptions.getProjection(); Bson sort = mongoQueryOptions.getSort(); FindIterable<Document> findIterable; if (projection == null) { findIterable = collection.find(filter); } else {// w w w . ja v a 2s. c o m findIterable = collection.find(filter).projection(projection); } if (sort != null) { findIterable = findIterable.sort(sort); } findIterable.limit(mongoQueryOptions.getResultLimit()); findIterable.forEach(new Block<Document>() { @Override public void apply(Document document) { mongoResult.add(document); } }); return mongoResult; }
From source file:org.eclipse.leshan.server.demo.servlet.FetchServlet.java
License:Open Source License
/** * {@inheritDoc}//from w w w . j a va2 s . co m */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Properties props = new Properties(); props.put("zookeeper.connect", "localhost:2181"); props.put("group.id", "testgroup"); props.put("zookeeper.session.timeout.ms", "400"); props.put("zookeeper.sync.time.ms", "300"); props.put("auto.commit.interval.ms", "1000"); ConsumerConfig conConfig = new ConsumerConfig(props); consumerConnector = Consumer.createJavaConsumerConnector(conConfig); resp.setContentType("application/json"); MongoClient client = new MongoClient(mongoDBAdd, mongoDBPort); // MongoClient client = new MongoClient("54.161.178.113", 27017); MongoDatabase database = client.getDatabase(mongoDBName); MongoCollection<Document> collection = database.getCollection("events"); Gson gson = new Gson(); ArrayList<ClientDao> clientDaoList = new ArrayList<ClientDao>(); if (req.getPathInfo() == null) { try { MongoCursor<String> mongoCursor = database.getCollection("events") .distinct("client_ep", String.class).iterator(); while (mongoCursor.hasNext()) { String clientEp = mongoCursor.next(); ClientDao clientDao = new ClientDao(); clientDao.setClientEP(clientEp); clientDao.setTimestamp(null); clientDaoList.add(clientDao); } String json = gson.toJson(clientDaoList); resp.getWriter().write(json.toString()); resp.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { e.printStackTrace(); } finally { client.close(); } } if (req.getPathInfo() != null) { String[] path = StringUtils.split(req.getPathInfo(), '/'); if (path.length == 1) { try { BasicDBObject query1 = new BasicDBObject(); BasicDBObject sort = new BasicDBObject(); sort.put("timestamp", -1); query1.put("client_ep", path[0].toString()); Iterable<Document> cur = collection.find(query1).sort(sort); Iterator<Document> itr = cur.iterator(); while (itr.hasNext()) { Document document = itr.next(); ClientDao clientDao = new ClientDao(); clientDao.setClientEP(document.getString("client_ep")); clientDao.setEvent(document.getString("event")); clientDao.setTimestamp(document.getString("timestamp")); clientDaoList.add(clientDao); } // String json = gson.toJson(clientDaoList); // resp.getWriter().write(json.toString()); // resp.setStatus(HttpServletResponse.SC_OK); Map<String, Integer> topicCount = new HashMap<String, Integer>(); topicCount.put(topic, new Integer(1)); //ConsumerConnector creates the message stream for each topic Map<String, List<KafkaStream<byte[], byte[]>>> consumerStreams = consumerConnector .createMessageStreams(topicCount); // Get Kafka stream for topic 'mytopic' List<KafkaStream<byte[], byte[]>> kStreamList = consumerStreams.get(topic); // Iterate stream using ConsumerIterator for (final KafkaStream<byte[], byte[]> kStreams : kStreamList) { ConsumerIterator<byte[], byte[]> consumerIte = kStreams.iterator(); int count = 0; while (consumerIte.hasNext()) { count++; // Shutdown the consumer connector if (consumerConnector != null && count == 10) consumerConnector.shutdown(); Message msg = new Message(consumerIte.next().message()); ByteBuffer buffer = msg.payload(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); String result = new String(bytes); JSONObject jsonObj = new JSONObject(result); ClientDao clientDao = new ClientDao(); clientDao.setClientEP(jsonObj.getString("client_ep")); clientDao.setEvent(jsonObj.getString("event")); clientDao.setTimestamp(jsonObj.getString("timestamp")); clientDaoList.add(clientDao); } } String json = gson.toJson(clientDaoList); resp.getWriter().write(json.toString()); resp.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { e.printStackTrace(); } finally { client.close(); } } } }
From source file:org.flinkmon.mongo.conn.MongoOplogTailMapper.java
License:Open Source License
private Bson getFilterLastTimeStamp(MongoCollection<Document> tsCollection, MongoClientWrapper client) { Document lastTimeStamp = tsCollection.find(new Document("_id", client.getHost())).limit(1).first(); return getTimeQuery(lastTimeStamp == null ? null : (BsonTimestamp) lastTimeStamp.get(OPLOG_TIMESTAMP)); }
From source file:org.helm.rest.MongoDB.java
public JSONObject LoadRow(String table, BsonDocument where) { MongoCollection coll = db.getCollection(table); MongoCursor cur = coll.find(where).limit(1).iterator(); return Result2Json(cur); }
From source file:org.helm.rest.MongoDB.java
public long SelectID(String table, String key, String value) { key = key.toLowerCase();/*from www . jav a 2s. c om*/ MongoCollection coll = db.getCollection(table); BsonDocument where = BsonDocument .parse("{\"" + key + "\": {$regex: \"^" + value.replace("\"", "\\\"") + "$\", $options: \"i\"}}"); // case insensitive Document fields = new Document("_id", false); fields.append("id", true); MongoCursor cur = coll.find(where).limit(1).projection(fields).iterator(); if (cur == null || !cur.hasNext()) return 0; Document d = (Document) cur.next(); return (long) d.get("id"); }
From source file:org.iotivity.cloud.accountserver.db.MongoDB.java
License:Open Source License
/** * API for inserting a record into DB table. the record will not be inserted * if duplicated one.//from w w w.java2s . c o m * * @param tableName * table name to be inserted * @param doc * document to be inserted */ public Boolean insertRecord(String tableName, Document doc) { if (tableName == null || doc == null) return false; MongoCollection<Document> collection = db.getCollection(tableName); try { if (collection.find(doc).first() == null) { collection.insertOne(doc); } else { Log.w("DB insert failed due to duplecated one."); return false; } } catch (Exception e) { e.printStackTrace(); return false; } showRecord(tableName); return true; }
From source file:org.iotivity.cloud.accountserver.db.MongoDB.java
License:Open Source License
/** * API for selecting records from DB table. * // www . j a v a2 s. c om * @param tableName * table name for the record to be selected * @param doc * document filter to be selected * @return record list according to the filter document */ public ArrayList<HashMap<String, Object>> selectRecord(String tableName, Document doc) { if (tableName == null || doc == null) return null; MongoCollection<Document> collection = db.getCollection(tableName); MongoCursor<Document> cursor = collection.find(doc).iterator(); ArrayList<HashMap<String, Object>> recordList = new ArrayList<HashMap<String, Object>>(); try { while (cursor.hasNext()) { Document selectedDoc = cursor.next(); recordList.add(convertDocumentToHashMap(selectedDoc)); } } finally { cursor.close(); } return recordList; }
From source file:org.iotivity.cloud.rdserver.db.MongoDB.java
License:Open Source License
/** * API for selecting records from DB table. * // w w w. j a va 2 s. c o m * @param tableName * table name for the record to be selected * @param doc * document filter to be selected * @return record list according to the filter document */ public ArrayList<HashMap<String, Object>> selectRecord(String tableName, Document doc) { if (tableName == null || doc == null) return null; MongoCollection<Document> collection = db.getCollection(tableName); MongoCursor<Document> cursor = collection.find(doc).iterator(); ArrayList<HashMap<String, Object>> recordList = new ArrayList<>(); try { while (cursor.hasNext()) { Document selectedDoc = cursor.next(); recordList.add(convertDocumentToHashMap(selectedDoc)); } } finally { cursor.close(); } return recordList; }
From source file:org.iotivity.cloud.rdserver.MongoDB.java
License:Open Source License
/** * API for finding resources matched filterValue of filterKey in collection * * @param filterKey// w w w . j a v a 2s.com * field name in collection * @param filterValue * field value about field name * @param tablename * collection name * @return ArrayList<PublishPayloadFormat> - array list of resource * information */ public ArrayList<PublishPayloadFormat> readResource(String filterKey, String filterValue, String tablename) { MongoCollection<Document> collection = db.getCollection(tablename); ArrayList<PublishPayloadFormat> resourceFormatList = new ArrayList<PublishPayloadFormat>(); MongoCursor<Document> cursor = collection.find(Filters.eq(filterKey, filterValue)).iterator(); try { while (cursor.hasNext()) { Document doc = cursor.next(); resourceFormatList.add(convertDocumentToResourceFormat(doc)); } } finally { cursor.close(); } return resourceFormatList; }