List of usage examples for com.mongodb DBCollection insert
public WriteResult insert(final List<? extends DBObject> documents)
From source file:example.QuickTour.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes no args/*from w w w.j a va 2 s. c o m*/ * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017 */ public static void main(final String[] args) throws UnknownHostException { // connect to the local database server MongoClient mongoClient = new MongoClient(); // get handle to "mydb" DB db = mongoClient.getDB("mydb"); // Authenticate - optional // boolean auth = db.authenticate("foo", "bar"); // get a list of the collections in this database and print them out Set<String> collectionNames = db.getCollectionNames(); for (final String s : collectionNames) { System.out.println(s); } // get a collection object to work with DBCollection testCollection = db.getCollection("testCollection"); // drop all the data in it testCollection.drop(); // make a document and insert it BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1) .append("info", new BasicDBObject("x", 203).append("y", 102)); testCollection.insert(doc); // get it (since it's the only one in there since we dropped the rest earlier on) DBObject myDoc = testCollection.findOne(); System.out.println(myDoc); // now, lets add lots of little documents to the collection so we can explore queries and cursors for (int i = 0; i < 100; i++) { testCollection.insert(new BasicDBObject().append("i", i)); } System.out.println( "total # of documents after inserting 100 small ones (should be 101) " + testCollection.getCount()); // lets get all the documents in the collection and print them out DBCursor cursor = testCollection.find(); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // now use a query to get 1 document out BasicDBObject query = new BasicDBObject("i", 71); cursor = testCollection.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // now use a range query to get a larger subset query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50 cursor = testCollection.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // range query with multiple constraints query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30 cursor = testCollection.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // create an index on the "i" field testCollection.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending // list the indexes on the collection List<DBObject> list = testCollection.getIndexInfo(); for (final DBObject o : list) { System.out.println(o); } // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); // see if any previous operation had an error System.out.println("Previous error : " + db.getPreviousError()); // force an error db.forceError(); // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); db.resetError(); // release resources mongoClient.close(); }
From source file:examples.QuickTour.java
License:Apache License
public static void main(String[] args) throws Exception { // connect to the local database server Mongo m = new Mongo(); // get handle to "mydb" DB db = m.getDB("mydb"); // Authenticate - optional boolean auth = db.authenticate("foo", new char[] { 'b', 'a', 'r' }); // get a list of the collections in this database and print them out Set<String> colls = db.getCollectionNames(); for (String s : colls) { System.out.println(s);//from w w w .jav a 2 s . co m } // get a collection object to work with DBCollection coll = db.getCollection("testCollection"); // drop all the data in it coll.drop(); // make a document and insert it BasicDBObject doc = new BasicDBObject(); doc.put("name", "MongoDB"); doc.put("type", "database"); doc.put("count", 1); BasicDBObject info = new BasicDBObject(); info.put("x", 203); info.put("y", 102); doc.put("info", info); coll.insert(doc); // get it (since it's the only one in there since we dropped the rest earlier on) DBObject myDoc = coll.findOne(); System.out.println(myDoc); // now, lets add lots of little documents to the collection so we can explore queries and cursors for (int i = 0; i < 100; i++) { coll.insert(new BasicDBObject().append("i", i)); } System.out .println("total # of documents after inserting 100 small ones (should be 101) " + coll.getCount()); // lets get all the documents in the collection and print them out DBCursor cur = coll.find(); while (cur.hasNext()) { System.out.println(cur.next()); } // now use a query to get 1 document out BasicDBObject query = new BasicDBObject(); query.put("i", 71); cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // now use a range query to get a larger subset query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50 cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // range query with multiple contstraings query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30 cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // create an index on the "i" field coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending // list the indexes on the collection List<DBObject> list = coll.getIndexInfo(); for (DBObject o : list) { System.out.println(o); } // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); // see if any previous operation had an error System.out.println("Previous error : " + db.getPreviousError()); // force an error db.forceError(); // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); db.resetError(); }
From source file:exifIndexer.MetadataReader.java
private void mongoCreator() throws UnknownHostException { DBHandler db = new DBHandler(); MongoHandler dbmon = new MongoHandler(); DB dbmongo = dbmon.connect();/*from w w w . j a v a 2 s . com*/ dbmongo.dropDatabase(); db.openConnection(); Statement st; String cadena[]; String cadena2; try { st = db.getCon().createStatement(); //Coleccin por marca de cmara ResultSet rs = st.executeQuery( "SELECT CATEGORIES.VALUE_NAME AS CAMERA_BRAND, IMAGES.IMG_PATH, IMAGES.IMG_NAME , IMAGES.EXTENSION FROM ASOCIATED, IMAGES, CATEGORIES WHERE ASOCIATED.ID_IMG = IMAGES.ID_IMG AND ASOCIATED.VALUE_NAME = CATEGORIES.VALUE_NAME AND CATEGORIES.CAT_NAME like 'Exif IFD0' and CATEGORIES.TAG_NAME like 'Make'"); JSONArray ja; ja = ResultSetConverter.convert(rs); DBObject dbObject; DBCollection collection = dbmongo.getCollection("CameraBrands"); cadena2 = (ja.toString().substring(1, ja.toString().length() - 1)); cadena2 = cadena2.replaceAll("},", "}<<->>"); cadena = cadena2.split("<<->>"); System.out.println(cadena2); for (String lenguaje : cadena) { dbObject = (DBObject) JSON.parse(lenguaje); collection.insert(dbObject); } st = db.getCon().createStatement(); //Coleccion modelo de cmara rs = st.executeQuery( "SELECT CATEGORIES.VALUE_NAME AS CAMERA_MODEL, IMAGES.IMG_PATH, IMAGES.IMG_NAME , IMAGES.EXTENSION FROM ASOCIATED, IMAGES, CATEGORIES WHERE ASOCIATED.ID_IMG = IMAGES.ID_IMG AND ASOCIATED.VALUE_NAME = CATEGORIES.VALUE_NAME AND CATEGORIES.CAT_NAME like 'Exif IFD0' and CATEGORIES.TAG_NAME like 'Model'"); ja = ResultSetConverter.convert(rs); collection = dbmongo.getCollection("CameraModels"); cadena2 = (ja.toString().substring(1, ja.toString().length() - 1)); cadena2 = cadena2.replaceAll("},", "}<<->>"); cadena = cadena2.split("<<->>"); System.out.println(cadena2); for (String lenguaje : cadena) { dbObject = (DBObject) JSON.parse(lenguaje); collection.insert(dbObject); } //Coleccion por ISO rs = st.executeQuery( "SELECT CATEGORIES.VALUE_NAME AS ISO_VALUE, IMAGES.IMG_PATH, IMAGES.IMG_NAME , IMAGES.EXTENSION FROM ASOCIATED, IMAGES, CATEGORIES WHERE ASOCIATED.ID_IMG = IMAGES.ID_IMG AND ASOCIATED.VALUE_NAME = CATEGORIES.VALUE_NAME AND CATEGORIES.CAT_NAME like 'Exif SubIFD' and CATEGORIES.TAG_NAME like 'ISO Speed Ratings'"); ja = ResultSetConverter.convert(rs); collection = dbmongo.getCollection("SearchByISO"); cadena2 = (ja.toString().substring(1, ja.toString().length() - 1)); cadena2 = cadena2.replaceAll("},", "}<<->>"); cadena2 = cadena2.replaceAll("(\"ISO_VALUE\"[:])(\")([0-9]+)(\")", "$1$3"); cadena = cadena2.split("<<->>"); System.out.println("DDD " + cadena2); for (String lenguaje : cadena) { dbObject = (DBObject) JSON.parse(lenguaje); collection.insert(dbObject); } //Coleccion por Shutter Speed rs = st.executeQuery( "SELECT CATEGORIES.VALUE_NAME AS SHUTTER_VALUE, IMAGES.IMG_PATH, IMAGES.IMG_NAME , IMAGES.EXTENSION FROM ASOCIATED, IMAGES, CATEGORIES WHERE ASOCIATED.ID_IMG = IMAGES.ID_IMG AND ASOCIATED.VALUE_NAME = CATEGORIES.VALUE_NAME AND CATEGORIES.CAT_NAME like 'Exif SubIFD' and CATEGORIES.TAG_NAME like 'Shutter Speed Value'"); ja = ResultSetConverter.convert(rs); collection = dbmongo.getCollection("Shutter_Speed"); cadena2 = (ja.toString().substring(1, ja.toString().length() - 1)); cadena2 = cadena2.replaceAll("},", "}<<->>"); cadena = cadena2.split("<<->>"); System.out.println(cadena2); for (String lenguaje : cadena) { dbObject = (DBObject) JSON.parse(lenguaje); collection.insert(dbObject); } //Coleccion por distintas posibles Shutter Speed rs = st.executeQuery( "SELECT DISTINCT CATEGORIES.VALUE_NAME AS SHUTTERSPEED FROM ASOCIATED, IMAGES, CATEGORIES WHERE ASOCIATED.ID_IMG = IMAGES.ID_IMG AND ASOCIATED.VALUE_NAME = CATEGORIES.VALUE_NAME AND CATEGORIES.CAT_NAME like 'Exif SubIFD' and CATEGORIES.TAG_NAME like 'Shutter Speed Value'"); ja = ResultSetConverter.convert(rs); collection = dbmongo.getCollection("Possible_shutterSpeeds"); cadena2 = (ja.toString().substring(1, ja.toString().length() - 1)); cadena2 = cadena2.replaceAll("},", "}<<->>"); cadena = cadena2.split("<<->>"); System.out.println(cadena2); for (String lenguaje : cadena) { dbObject = (DBObject) JSON.parse(lenguaje); collection.insert(dbObject); } //Coleccion por Date created rs = st.executeQuery( "SELECT CATEGORIES.VALUE_NAME AS DATE_VALUE, IMAGES.IMG_PATH, IMAGES.IMG_NAME , IMAGES.EXTENSION FROM ASOCIATED, IMAGES, CATEGORIES WHERE ASOCIATED.ID_IMG = IMAGES.ID_IMG AND ASOCIATED.VALUE_NAME = CATEGORIES.VALUE_NAME AND CATEGORIES.CAT_NAME like 'Exif SubIFD' and CATEGORIES.TAG_NAME like 'Date/Time Original'"); ja = ResultSetConverter.convert(rs); collection = dbmongo.getCollection("Date_created"); cadena2 = (ja.toString().substring(1, ja.toString().length() - 1)); cadena2 = cadena2.replaceAll("},", "}<<->>"); cadena2 = cadena2.replaceAll( "(\"DATE_VALUE\"[:]\")([0-9]{4})[:]([0-9]{2})[:]([0-9]{2})([\\s][0-9]{2}[:][0-9]{2}[:][0-9]{2}\")", "$1$2-$3-$4\""); System.out.println("ddd" + cadena2); cadena = cadena2.split("<<->>"); for (String lenguaje : cadena) { dbObject = (DBObject) JSON.parse(lenguaje); collection.insert(dbObject); } //Coleccion por GPS rs = st.executeQuery( "SELECT CATEGORIES.VALUE_NAME AS GPS_VALUE, IMAGES.ID_IMG, IMAGES.IMG_PATH, IMAGES.IMG_NAME , IMAGES.EXTENSION FROM ASOCIATED, IMAGES, CATEGORIES WHERE ASOCIATED.ID_IMG = IMAGES.ID_IMG AND ASOCIATED.VALUE_NAME = CATEGORIES.VALUE_NAME AND CATEGORIES.CAT_NAME like 'GPS%' and (CATEGORIES.TAG_NAME like 'GPS Latitude' or CATEGORIES.TAG_NAME like 'GPS Longitude' or CATEGORIES.TAG_NAME like 'GPS Latitude Ref' or CATEGORIES.TAG_NAME like 'GPS Longitude Ref')order by IMAGES.ID_IMG, CATEGORIES.TAG_NAME"); ja = ResultSetConverter.convert(rs); collection = dbmongo.getCollection("GPSFotos"); cadena2 = (ja.toString().substring(1, ja.toString().length() - 1)); cadena2 = cadena2.replaceAll("},", "}<<->>"); cadena = cadena2.split("<<->>"); System.out.println(cadena2); for (String lenguaje : cadena) { dbObject = (DBObject) JSON.parse(lenguaje); collection.insert(dbObject); } st.close(); System.out.println("Mongo creada"); } catch (SQLException ex) { System.err.println("SQL Error.\n" + ex); } }
From source file:explorasi.GettingStarted.java
public static void main(String args[]) { MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("pat_13512042"); DBCollection coll = db.getCollection("users"); BasicDBObject doc = new BasicDBObject("name", "joshua").append("kelas", "01").append("timestamp", new Date()); coll.insert(doc); DBCursor cursor = coll.find(doc);// w ww . j a v a2 s . co m while (cursor.hasNext()) { DBObject tmp = cursor.next(); System.out.println(tmp.get("name")); System.out.println(tmp.get("kelas")); System.out.println(tmp.get("timestamp")); System.out.println(tmp.get("_id")); } }
From source file:ezbake.locksmith.db.MongoDBService.java
License:Apache License
/** * Inserts a document into a collection// w w w .j a v a 2 s .c o m * @param collection - collection to insert document into * @param doc - the document to be inserted * @return - true on success, false otherwise */ public ObjectId insertDocumentIntoCollection(String collection, DBObject doc) { boolean success = true; log.info("Insert Document into collection [{}]", collection); DBCollection coll = db.getCollection(collection); WriteResult result = coll.insert(doc); return (ObjectId) result.getUpsertedId(); }
From source file:facebook.metrics.FacebookMetricsGroup.java
public static void main(String[] args) { try {// ww w . j a v a 2 s . c o m // Se crea el libro HSSFWorkbook libro = new HSSFWorkbook(); // Se crea una hoja dentro del libro HSSFSheet hoja = libro.createSheet(); // Se crea una fila dentro de la hoja HSSFRow fila = hoja.createRow(0); // Se crea una celda dentro de la fila HSSFCell celda = fila.createCell(1); // Se crea el contenido de la celda y se mete en ella. HSSFRichTextString texto = new HSSFRichTextString("Metricas de Grupo Cinepolitos"); celda.setCellValue(texto); /************************************/ /*Mongo DB Conection*/ MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("JavaMongoFacebookGroup"); DBCollection datos = db.getCollection("Datos"); /********************/ Facebook facebook = new FacebookFactory().getInstance(); facebook.setOAuthAppId("603320016402931", "202694064e7a4e77f0c0042b1a16ebd4"); System.out.println(facebook.getOAuthAppAccessToken().getToken()); ResponseList<Post> feedX = facebook.getGroupFeed("17761155026", new Reading().limit(1135)); List<ResponseList<Post>> X = new ArrayList<ResponseList<Post>>(); do { X.add(feedX); Paging<Post> pag1 = feedX.getPaging(); feedX = facebook.fetchNext(pag1); } while (feedX.getPaging() != null); fila = hoja.createRow(2); celda = fila.createCell(1); celda.setCellValue(new HSSFRichTextString("Id Post:")); celda = fila.createCell(2); celda.setCellValue(new HSSFRichTextString("Fecha del Post:")); celda = fila.createCell(3); celda.setCellValue(new HSSFRichTextString("Usuario que posteo:")); celda = fila.createCell(4); celda.setCellValue(new HSSFRichTextString("Post:")); celda = fila.createCell(5); celda.setCellValue(new HSSFRichTextString("# de Likes del Post:")); celda = fila.createCell(6); celda.setCellValue(new HSSFRichTextString("# de Comentarios del Post:")); celda = fila.createCell(7); celda.setCellValue(new HSSFRichTextString("Comentarios del Post:")); int filasX = 3; for (int j = 0; j < X.size(); j++) { ResponseList<Post> feed = X.get(j); System.out.println(feed.size()); for (int i = 0; i < feed.size(); i++) { System.out.println("Feed: " + i); BasicDBObject obj = new BasicDBObject(); ResponseList<Like> likes = facebook.getPostLikes(feed.get(i).getId(), new Reading().limit(1135)); ResponseList<Comment> comments = facebook.getPostComments(feed.get(i).getId(), new Reading().limit(1135)); obj.append("idPost", feed.get(i).getId() + ""); if (feed.get(i).getMessage() == null) { obj.append("Post", " "); //System.out.println("Null"); } else { obj.append("Post", feed.get(i).getMessage()); } obj.append("Likes", likes.size() + ""); obj.append("Comments", comments.size() + ""); datos.insert(obj); fila = hoja.createRow(filasX); celda = fila.createCell(1); celda.setCellValue(new HSSFRichTextString(feed.get(i).getId() + "")); celda = fila.createCell(2); celda.setCellValue(new HSSFRichTextString(feed.get(i).getCreatedTime() + "")); celda = fila.createCell(3); celda.setCellValue(new HSSFRichTextString(feed.get(i).getFrom().getName())); celda = fila.createCell(4); celda.setCellValue(new HSSFRichTextString(feed.get(i).getMessage())); celda = fila.createCell(5); celda.setCellValue(new HSSFRichTextString(likes.size() + "")); celda = fila.createCell(6); celda.setCellValue(new HSSFRichTextString(comments.size() + "")); filasX++; for (int y = 0; y < comments.size(); y++) { fila = hoja.createRow(filasX); celda = fila.createCell(7); celda.setCellValue(new HSSFRichTextString(comments.get(y).getMessage() + "")); filasX++; } } System.out.println(); } FileOutputStream elFichero = new FileOutputStream("Metricas_Cinepolitos.xls"); libro.write(elFichero); elFichero.close(); } catch (Exception e) { System.err.println("Fatal Error: " + e); } }
From source file:facebook.metrics.FacebookMetricsPage.java
public static void main(String[] args) throws IOException { int varFeed = 0; int filasX = 0; HSSFRow fila = null;//from ww w. j a va2s.c o m HSSFRow filam = null; HSSFCell celda = null; List<ResponseList<Post>> X = null; int j = 0; int i = 0; HSSFSheet hoja = null; Facebook facebook = null; HSSFWorkbook libro = null; try { // Se crea el libro libro = new HSSFWorkbook(); hoja = libro.createSheet(); fila = hoja.createRow(0); celda = fila.createCell(1); HSSFRichTextString texto = new HSSFRichTextString("Metricas de Infinitum"); celda.setCellValue(texto); /************************************/ /*Mongo DB Conection*/ MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("JavaMongoFacebookGroup"); DBCollection datos = db.getCollection("Datos"); /********************/ facebook = new FacebookFactory().getInstance(); facebook.setOAuthAppId("603320016402931", "202694064e7a4e77f0c0042b1a16ebd4"); System.out.println(facebook.getOAuthAppAccessToken().getToken()); ResponseList<Post> feedX = facebook.getFeed("216786388331757", new Reading().limit(1000)); X = new ArrayList<ResponseList<Post>>(); int ui = 0; do { X.add(feedX); Paging<Post> pag1 = feedX.getPaging(); feedX = facebook.fetchNext(pag1); System.out.println("" + ui); ui++; } while (feedX.getPaging() != null && ui < 25); fila = hoja.createRow(2); celda = fila.createCell(1); celda.setCellValue(new HSSFRichTextString("Id Post:")); celda = fila.createCell(2); celda.setCellValue(new HSSFRichTextString("Fecha del Post:")); celda = fila.createCell(3); celda.setCellValue(new HSSFRichTextString("Usuario que posteo:")); celda = fila.createCell(4); celda.setCellValue(new HSSFRichTextString("Post:")); celda = fila.createCell(5); celda.setCellValue(new HSSFRichTextString("# de Likes del Post:")); celda = fila.createCell(6); celda.setCellValue(new HSSFRichTextString("# de Comentarios del Post:")); celda = fila.createCell(7); celda.setCellValue(new HSSFRichTextString("Comentarios del Post:")); celda = fila.createCell(8); celda.setCellValue(new HSSFRichTextString("Tipo de Post:")); filasX = 4; for (j = 0; j < X.size(); j++) { ResponseList<Post> feed = X.get(j); System.out.println(feed.size()); for (i = 0; i < feed.size(); i++) { System.out.println("Feed: " + i); BasicDBObject obj = new BasicDBObject(); ResponseList<Like> likes = facebook.getPostLikes(feed.get(i).getId(), new Reading().limit(1135)); ResponseList<Comment> comments = facebook.getPostComments(feed.get(i).getId(), new Reading().limit(1135)); obj.append("idPost", feed.get(i).getId() + ""); if (feed.get(i).getMessage() == null) { obj.append("Post", " "); //System.out.println("Null"); } else { obj.append("Post", feed.get(i).getMessage()); } obj.append("Likes", likes.size() + ""); obj.append("Comments", comments.size() + ""); datos.insert(obj); filam = hoja.createRow(filasX); celda = filam.createCell(1); celda.setCellValue(new HSSFRichTextString(feed.get(i).getId() + "")); celda = filam.createCell(2); celda.setCellValue(new HSSFRichTextString(feed.get(i).getCreatedTime() + "")); celda = filam.createCell(3); celda.setCellValue(new HSSFRichTextString(feed.get(i).getFrom().getName())); celda = filam.createCell(4); celda.setCellValue(new HSSFRichTextString(feed.get(i).getMessage())); celda = filam.createCell(5); celda.setCellValue(new HSSFRichTextString(likes.size() + "")); celda = filam.createCell(6); celda.setCellValue(new HSSFRichTextString(comments.size() + "")); celda = filam.createCell(8); celda.setCellValue(new HSSFRichTextString(feed.get(i).getType() + "")); filasX++; for (int y = 0; y < comments.size(); y++) { filam = hoja.createRow(filasX); celda = filam.createCell(7); celda.setCellValue(new HSSFRichTextString(comments.get(y).getMessage() + "")); filasX++; } } } FileOutputStream elFichero = new FileOutputStream("Metricas_Infinitum.xls"); libro.write(elFichero); elFichero.close(); } catch (Exception e) { System.err.println("Fatal Error: " + e); FacebookMetricsPage s = new FacebookMetricsPage(); s.porsi(i, j, filasX + 1, filam, celda, facebook, X, hoja, libro); } }
From source file:facebook.metrics.FacebookMetricsPage2.java
public static void main(String[] args) throws IOException { int varFeed = 0; int filasX = 0; HSSFRow fila = null;//from ww w . ja v a 2 s. com HSSFCell celda = null; List<ResponseList<Post>> X = null; int j = 0; int i = 0; HSSFSheet hoja = null; Facebook facebook = null; HSSFWorkbook libro = null; try { // Se crea el libro libro = new HSSFWorkbook(); // Se crea una hoja dentro del libro hoja = libro.createSheet(); // Se crea una fila dentro de la hoja fila = hoja.createRow(0); // Se crea una celda dentro de la fila celda = fila.createCell(1); // Se crea el contenido de la celda y se mete en ella. HSSFRichTextString texto = new HSSFRichTextString("Metricas de Sony Futbol"); celda.setCellValue(texto); /************************************/ /*Mongo DB Conection*/ MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("JavaMongoFacebookGroup"); DBCollection datos = db.getCollection("Datos"); /********************/ facebook = new FacebookFactory().getInstance(); facebook.setOAuthAppId("603320016402931", "202694064e7a4e77f0c0042b1a16ebd4"); System.out.println(facebook.getOAuthAppAccessToken().getToken()); ResponseList<Post> feedX = facebook.getFeed("120472297979101", new Reading().limit(1000)); X = new ArrayList<ResponseList<Post>>(); int ui = 0; do { X.add(feedX); Paging<Post> pag1 = feedX.getPaging(); feedX = facebook.fetchNext(pag1); System.out.println("" + ui); ui++; } while (feedX.getPaging() != null && ui < 5); fila = hoja.createRow(2); celda = fila.createCell(1); celda.setCellValue(new HSSFRichTextString("Id Post:")); celda = fila.createCell(2); celda.setCellValue(new HSSFRichTextString("Fecha del Post:")); celda = fila.createCell(3); celda.setCellValue(new HSSFRichTextString("Usuario que posteo:")); celda = fila.createCell(4); celda.setCellValue(new HSSFRichTextString("Post:")); celda = fila.createCell(5); celda.setCellValue(new HSSFRichTextString("# de Likes del Post:")); celda = fila.createCell(6); celda.setCellValue(new HSSFRichTextString("# de Comentarios del Post:")); celda = fila.createCell(7); celda.setCellValue(new HSSFRichTextString("Comentarios del Post:")); celda = fila.createCell(8); celda.setCellValue(new HSSFRichTextString("Tipo de Post:")); filasX = 3; for (j = 0; j < X.size(); j++) { ResponseList<Post> feed = X.get(j); System.out.println(feed.size()); for (i = 0; i < feed.size(); i++) { System.out.println("Feed: " + i); BasicDBObject obj = new BasicDBObject(); ResponseList<Like> likes = facebook.getPostLikes(feed.get(i).getId(), new Reading().limit(1135)); ResponseList<Comment> comments = facebook.getPostComments(feed.get(i).getId(), new Reading().limit(1135)); obj.append("idPost", feed.get(i).getId() + ""); if (feed.get(i).getMessage() == null) { obj.append("Post", " "); //System.out.println("Null"); } else { obj.append("Post", feed.get(i).getMessage()); } obj.append("Likes", likes.size() + ""); obj.append("Comments", comments.size() + ""); datos.insert(obj); fila = hoja.createRow(filasX); celda = fila.createCell(1); celda.setCellValue(new HSSFRichTextString(feed.get(i).getId() + "")); celda = fila.createCell(2); celda.setCellValue(new HSSFRichTextString(feed.get(i).getCreatedTime() + "")); celda = fila.createCell(3); celda.setCellValue(new HSSFRichTextString(feed.get(i).getFrom().getName())); celda = fila.createCell(4); celda.setCellValue(new HSSFRichTextString(feed.get(i).getMessage())); celda = fila.createCell(5); celda.setCellValue(new HSSFRichTextString(likes.size() + "")); celda = fila.createCell(6); celda.setCellValue(new HSSFRichTextString(comments.size() + "")); celda = fila.createCell(8); celda.setCellValue(new HSSFRichTextString(feed.get(i).getType() + "")); filasX++; for (int y = 0; y < comments.size(); y++) { fila = hoja.createRow(filasX); celda = fila.createCell(7); celda.setCellValue(new HSSFRichTextString(comments.get(y).getMessage() + "")); filasX++; } } } FileOutputStream elFichero = new FileOutputStream("Metricas_SonyFutbol.xls"); libro.write(elFichero); elFichero.close(); } catch (Exception e) { System.err.println("Fatal Error: " + e); FacebookMetricsPage s = new FacebookMetricsPage(); s.porsi(i, j, filasX, fila, celda, facebook, X, hoja, libro); } }
From source file:field_sum.Field_sum.java
/** * @param args the command line arguments * @throws java.net.UnknownHostException */// www .j a v a 2 s . c o m public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient("localhost", 27017); DB myDB = client.getDB("m101"); DBCollection collection = myDB.getCollection("Sample3"); /** * random_number field generates random numbers */ Random random_numbers = new Random(); collection.drop(); DBObject query = QueryBuilder.start("x").greaterThan(10).lessThan(70).and("y").greaterThan(10).lessThan(70) .get(); for (int i = 0; i < 100; i++) { collection.insert(new BasicDBObject("x", random_numbers.nextInt(100)) .append("y", random_numbers.nextInt(100)).append("z", random_numbers.nextInt(200))); } DBCursor cursor = collection.find(query); int sum = 0; try { while (cursor.hasNext()) { DBObject dBObject = cursor.next(); sum += (int) dBObject.get("x"); System.out.println(dBObject.get("x")); } } finally { cursor.close(); } System.out.println(sum); }
From source file:firesystem.MainGui.java
public FireSensor[] getSensors(Stage primaryStage) { FireSensor[] sensors = new FireSensor[13]; try {//from w ww. j av a 2 s. c o m MongoClient mongoClient = new MongoClient(DatabaseConnectionPopup.getsHostName()); DB db = mongoClient.getDB(DatabaseConnectionPopup.getsDbname()); DBCollection coll = db.getCollection("users"); DBCursor cursor = coll.find(); for (int i = 0; i < 13; i++) { DBObject thisUser; //Make sure the users exist if (cursor.hasNext()) { thisUser = cursor.next(); } else { thisUser = new BasicDBObject(); coll.insert(thisUser); } int j = i + 1; sensors[i] = new FireSensor(j, thisUser.get("_id").toString()); } } catch (UnknownHostException e) { System.out.println(e.getMessage()); } catch (Exception e) { new ExceptionPopup( "Der kunne ikke oprettes forbindelse til mongodb. Mongodb gav flgende fejlbesked: ", e.getMessage()); System.exit(0); } return sensors; }