List of usage examples for com.mongodb MongoClient close
public void close()
From source file:Dbconnection.java
public Connection getconnection() { Logger mongoLogger = Logger.getLogger("org.mongodb.driver"); mongoLogger.setLevel(Level.SEVERE); // To connect to mongodb server MongoClient mongoClient = new MongoClient("localhost", 27017); // Now connect to your databases MongoDatabase db = mongoClient.getDatabase("mydb"); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate("",""); //System.out.println("Authentication: "+auth); // MongoCollection<Document> coll = db.getCollection("yelp"); System.out.println("Collection yelp selected successfully"); /*FindIterable<Document> cursor = coll.find(); //from w w w . ja v a2 s. co m cursor.forEach(new Block<Document>() { @Override public void apply(final Document document) { System.out.println(document); } });*/ // BasicDBObject clause1 = new BasicDBObject("yelping_since", "2012-02"); // //clause1.put("yelping_since", "2012-02"); // // BasicDBObject clause2 = new BasicDBObject("review_count",new BasicDBObject("$gt",500)); // BasicDBObject clause3 = new BasicDBObject("fans",new BasicDBObject("$gt",15)); // BasicDBObject clause4 = new BasicDBObject("average_stars",new BasicDBObject("$gt",3)); // //BasicDBObject cl5 = new BasicDBObject("$exist",true); // //BasicDBObject cl6 = new BasicDBObject("$where","this.friends.length>49"); // //String cl = cl5.toString(); // //BasicDBObject c = new BasicDBObject(cl,cl6); // //BasicDBObject f = new BasicDBObject("friends",new BasicDBObject("$exist",true)); // BasicDBObject clause5 = new BasicDBObject("friends.50",new BasicDBObject("$exists",true)); // //BasicDBObject cl5 = new BasicDBObject("$where","this.friends.length>3"); // // /*BasicDBList fl = new BasicDBList(); // fl.add(f); // fl.add(cl6);*/ // // //clause2.put("review_count",gtquery); // BasicDBList or = new BasicDBList(); // // or.add(clause1); // or.add(clause2); // or.add(clause3); // or.add(clause4); // or.add(clause5); // //or.add(fl); // // //fields.put("name",1); // //fields.put("average_stars",1); // //fields.put("fans",1); // BasicDBObject query = new BasicDBObject("$and", or); // // // FindIterable<Document> cursor = coll.find(query); // System.out.println(query); // cursor.forEach(new Block<Document>() { // @Override // public void apply(final Document document) { // System.out.println(document.get("user_id")); // System.out.println(document.get("name")); // System.out.println(document.get("fans")); // System.out.println(document.get("average_stars")); // System.out.println(document.get("friends")); // // } // }); // // mongoClient.close(); System.out.println("Connection successfully closed"); return null; }
From source file:MongoRyaDirectExample.java
License:Apache License
private static Configuration getConf() throws IOException { final MongoDBRdfConfiguration conf = new MongoDBRdfConfiguration(); conf.set(ConfigUtils.USE_MONGO, "true"); if (USE_MOCK) { mock = MockMongoFactory.newFactory(); final MongoClient c = mock.newMongoClient(); final ServerAddress address = c.getAddress(); final String url = address.getHost(); final String port = Integer.toString(address.getPort()); c.close(); conf.set(MongoDBRdfConfiguration.MONGO_INSTANCE, url); conf.set(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT, port); } else {//from ww w .java2 s .c om // User name and password must be filled in: conf.set(MongoDBRdfConfiguration.MONGO_USER, "fill this in"); conf.set(MongoDBRdfConfiguration.MONGO_USER_PASSWORD, "fill this in"); conf.set(MongoDBRdfConfiguration.MONGO_INSTANCE, MONGO_INSTANCE_URL); conf.set(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT, MONGO_INSTANCE_PORT); } conf.set(MongoDBRdfConfiguration.MONGO_DB_NAME, MONGO_DB); conf.set(MongoDBRdfConfiguration.MONGO_COLLECTION_PREFIX, MONGO_COLL_PREFIX); conf.set(ConfigUtils.GEO_PREDICATES_LIST, "http://www.opengis.net/ont/geosparql#asWKT"); // conf.set(ConfigUtils.USE_GEO, "true"); conf.set(ConfigUtils.USE_FREETEXT, "true"); conf.setTablePrefix(MONGO_COLL_PREFIX); conf.set(ConfigUtils.GEO_PREDICATES_LIST, GeoConstants.GEO_AS_WKT.stringValue()); conf.set(ConfigUtils.FREETEXT_PREDICATES_LIST, RDFS.LABEL.stringValue()); conf.set(ConfigUtils.FREETEXT_PREDICATES_LIST, RDFS.LABEL.stringValue()); conf.set(RdfCloudTripleStoreConfiguration.CONF_INFER, Boolean.toString(USE_INFER)); return conf; }
From source file:UnitTest3.java
License:Open Source License
public static int testgridfs() { long time1;//w w w . j a v a 2s . c om long time2; long time3; long time4; try { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("JFileDB"); // TODO JFileMetaDataTable should be in MetaDB database DBCollection collection = db.getCollection("JFileMetaDataTable"); String newFileName = "com.dilmus.scabi.testdata.in.App.class"; File jFile = new File("/home/anees/workspace/testdata/in/App.class"); // create a JFileTable namespace GridFS gfsj = new GridFS(db, "JFileTable"); // get file from local drive GridFSInputFile gfsFile = gfsj.createFile(jFile); // set a new filename for identify purpose gfsFile.setFilename(newFileName); gfsFile.setContentType("class"); // jar, zip, war // save the image file into mongoDB gfsFile.save(); // Let's create a new JSON document with some "metadata" information BasicDBObject info = new BasicDBObject(); info.put("DBHost", "localhost"); info.put("DBPort", "27017"); info.put("JFileName", newFileName); info.put("JFileID", gfsFile.getId()); info.put("JFileMD5", gfsFile.getMD5()); collection.insert(info, WriteConcern.ACKNOWLEDGED); // print the result DBCursor cursor = gfsj.getFileList(); while (cursor.hasNext()) { System.out.println(cursor.next()); } DBCursor cursor2 = collection.find(); while (cursor2.hasNext()) { System.out.println(cursor2.next()); } // get file by it's filename GridFSDBFile jForOutput = gfsj.findOne(newFileName); // save it into a new image file jForOutput.writeTo("/home/anees/workspace/testdata/out/AppOut.class"); // remove the file from mongoDB // gfsj.remove(gfsj.findOne(newFileName)); System.out.println("Done"); mongo.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return 0; }
From source file:UnitTest3.java
License:Open Source License
public static void testgridfs2() throws FileNotFoundException, IOException { long time1;//ww w .j a v a 2 s . co m long time2; long time3; long time4; String fileName = "makezip3.rar"; MongoClient mongo = new MongoClient("localhost", 27017); //DB db = mongo.getDB("JFileDB"); MongoDatabase db = mongo.getDatabase("JFileDB"); GridFSBucket gridFSBucket = GridFSBuckets.create(db); // Get the input stream time1 = System.currentTimeMillis(); InputStream streamToUploadFrom = new FileInputStream("/home/anees/workspace/testdata/in/" + fileName); // Create some custom options GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024 * 1024) .metadata(new Document("type", "class")); ObjectId fileId = gridFSBucket.uploadFromStream(fileName, streamToUploadFrom, options); streamToUploadFrom.close(); time2 = System.currentTimeMillis(); time3 = System.currentTimeMillis(); Date date = new Date(); FileOutputStream streamToDownloadTo = new FileOutputStream( "/home/anees/workspace/testdata/out/" + fileName + "_" + date.toString()); // latest file with same name in DB GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(-1); //original file with same file name in DB GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(0); //downloadOptions. gridFSBucket.downloadToStreamByName(fileName, streamToDownloadTo, downloadOptions); streamToDownloadTo.close(); time4 = System.currentTimeMillis(); System.out.println("The fileId of the uploaded file is: " + fileId.toHexString()); System.out.println("Upload time taken : time2 - time1 : " + (time2 - time1)); System.out.println("Download time taken : time4 - time3 : " + (time4 - time3)); /* Set the revision of the file to retrieve. Revision numbers are defined as follows: 0 = the original stored file 1 = the first revision 2 = the second revision etc.. -2 = the second most recent revision -1 = the most recent revision */ mongo.close(); }
From source file:UnitTest3.java
License:Open Source License
public static void testgridfs3() throws FileNotFoundException, IOException { long time1;/*from w w w . j a va 2 s. com*/ long time2; long time3; long time4; int n = 0; // "/home/anees/workspace/testdata/in/App3.class" String fileName = "makezip4.rar"; MongoClient mongo = new MongoClient("localhost", 27017); //DB db = mongo.getDB("JFileDB"); MongoDatabase db = mongo.getDatabase("JFileDB"); GridFSBucket gridFSBucket = GridFSBuckets.create(db); // Get the input stream time1 = System.currentTimeMillis(); InputStream streamToUploadFrom = new FileInputStream("/home/anees/workspace/testdata/in/" + fileName); // Create some custom options GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024 * 1024) .metadata(new Document("type", "class")); byte data[] = new byte[64 * 1024 * 1024]; GridFSUploadStream uploadStream = gridFSBucket.openUploadStream(fileName, options); while ((n = streamToUploadFrom.read(data)) > 0) { uploadStream.write(data, 0, n); } uploadStream.close(); time2 = System.currentTimeMillis(); time3 = System.currentTimeMillis(); Date date = new Date(); FileOutputStream streamToDownloadTo = new FileOutputStream( "/home/anees/workspace/testdata/out/" + fileName + "_" + date.toString()); GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(-1); GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStreamByName(fileName, downloadOptions); long fileLength = downloadStream.getGridFSFile().getLength(); byte[] bytesToWriteTo = new byte[64 * 1024 * 1024]; while ((n = downloadStream.read(bytesToWriteTo)) > 0) { streamToDownloadTo.write(bytesToWriteTo, 0, n); } downloadStream.close(); time4 = System.currentTimeMillis(); System.out.println("The fileId of the uploaded file is: " + uploadStream.getFileId().toHexString()); System.out.println("Upload time taken : time2 - time1 : " + (time2 - time1)); System.out.println("Download time taken : time4 - time3 : " + (time4 - time3)); streamToDownloadTo.close(); streamToUploadFrom.close(); mongo.close(); }
From source file:UnitTest3.java
License:Open Source License
public static void testgridfs4() throws FileNotFoundException, IOException { MongoClient mongo = new MongoClient("localhost", 27017); //DB db = mongo.getDB("JFileDB"); MongoDatabase db = mongo.getDatabase("JFileDB"); GridFSBucket gridFSBucket = GridFSBuckets.create(db); // Get the input stream InputStream streamToUploadFrom = new ByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8)); // Create some custom options GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024) .metadata(new Document("type", "file")); ObjectId fileId = gridFSBucket.uploadFromStream("test", streamToUploadFrom, options); streamToUploadFrom.close();/*w w w .ja v a2s . c om*/ System.out.println("The fileId of the uploaded file is: " + fileId.toHexString()); // Get some data to write byte[] data = "some data to upload into GridFS".getBytes(StandardCharsets.UTF_8); GridFSUploadStream uploadStream = gridFSBucket.openUploadStream("sample_data"); uploadStream.write(data); uploadStream.close(); System.out.println("The fileId of the uploaded file is: " + uploadStream.getFileId().toHexString()); /* gridFSBucket.find().forEach(new Block<GridFSFile>() { public void apply(final GridFSFile gridFSFile) { System.out.println(gridFSFile.getFilename()); } }); */ /* gridFSBucket.find(eq("metadata.contentType", "image/png")).forEach( new Block<GridFSFile>() { public void apply(final GridFSFile gridFSFile) { System.out.println(gridFSFile.getFilename()); } }); */ FileOutputStream streamToDownloadTo = new FileOutputStream("/tmp/test.txt"); gridFSBucket.downloadToStream(fileId, streamToDownloadTo); streamToDownloadTo.close(); streamToDownloadTo = new FileOutputStream("/tmp/test.txt"); GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(0); gridFSBucket.downloadToStreamByName("test", streamToDownloadTo, downloadOptions); streamToDownloadTo.close(); GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId); int fileLength = (int) downloadStream.getGridFSFile().getLength(); byte[] bytesToWriteTo = new byte[fileLength]; downloadStream.read(bytesToWriteTo); downloadStream.close(); System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8)); downloadStream = gridFSBucket.openDownloadStreamByName("sample_data"); fileLength = (int) downloadStream.getGridFSFile().getLength(); bytesToWriteTo = new byte[fileLength]; downloadStream.read(bytesToWriteTo); downloadStream.close(); System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8)); gridFSBucket.rename(fileId, "test2"); gridFSBucket.delete(fileId); mongo.close(); }
From source file:JavaSimpleExample.java
License:MIT License
public static void main(String[] args) throws UnknownHostException { // Create seed data final BasicDBObject[] seedData = createSeedData(); // Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname MongoClientURI uri = new MongoClientURI("mongodb://user:pass@host:port/db"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); /*/* w w w. j a va 2s. c o m*/ * First we'll add a few songs. Nothing is required to create the * songs collection; it is created automatically when we insert. */ DBCollection songs = db.getCollection("songs"); // Note that the insert method can take either an array or a document. songs.insert(seedData); /* * Then we need to give Boyz II Men credit for their contribution to * the hit "One Sweet Day". */ BasicDBObject updateQuery = new BasicDBObject("song", "One Sweet Day"); songs.update(updateQuery, new BasicDBObject("$set", new BasicDBObject("artist", "Mariah Carey ft. Boyz II Men"))); /* * Finally we run a query which returns all the hits that spent 10 * or more weeks at number 1. */ BasicDBObject findQuery = new BasicDBObject("weeksAtOne", new BasicDBObject("$gte", 10)); BasicDBObject orderBy = new BasicDBObject("decade", 1); DBCursor docs = songs.find(findQuery).sort(orderBy); while (docs.hasNext()) { DBObject doc = docs.next(); System.out.println("In the " + doc.get("decade") + ", " + doc.get("song") + " by " + doc.get("artist") + " topped the charts for " + doc.get("weeksAtOne") + " straight weeks."); } // Since this is an example, we'll clean up after ourselves. songs.drop(); // Only close the connection when your app is terminating client.close(); }
From source file:InferenceExamples.java
License:Apache License
private static Configuration getConf() throws IOException { // MongoDBIndexingConfigBuilder builder = MongoIndexingConfiguration.builder() // .setUseMockMongo(USE_MOCK).setUseInference(USE_INFER).setAuths("U"); MongoDBIndexingConfigBuilder builder = MongoIndexingConfiguration.builder() .setUseMockMongo(USE_EMBEDDED_MONGO).setUseInference(true).setAuths("U"); if (USE_EMBEDDED_MONGO) { final MongoClient c = EmbeddedMongoFactory.newFactory().newMongoClient(); final ServerAddress address = c.getAddress(); final String url = address.getHost(); final String port = Integer.toString(address.getPort()); c.close(); builder.setMongoHost(url).setMongoPort(port); } else {// ww w .ja va 2 s. c o m // User name and password must be filled in: builder = builder.setMongoUser(MongoUserName).setMongoPassword(MongoUserPassword) .setMongoHost(MONGO_INSTANCE_URL).setMongoPort(MONGO_INSTANCE_PORT); } return builder.setMongoDBName(MONGO_DB).setMongoCollectionPrefix(MONGO_COLL_PREFIX) .setUseMongoFreetextIndex(true).setMongoFreeTextPredicates(RDFS.LABEL.stringValue()).build(); }
From source file:DataSimulate.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes no args// ww w.jav a 2s . com * @throws IOException */ public static void main(final String[] args) throws IOException { // connect to the local database server MongoClient mongoClient = new MongoClient(); /* // Authenticate - optional MongoCredential credential = MongoCredential.createMongoCRCredential(userName, database, password); MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential)); */ // get handle to "mydb" DB db = mongoClient.getDB("awf_db"); // 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 coll = db.getCollection("influencer"); //Create a boolean for either advertiser or influencer boolean advOrInf; //Loop 100 times creating new users //Should create about 50 influencers and about 50 advertisers /*for(int i = 0; i < 100; i++) { advOrInf = new Random().nextInt(2)==0; if(advOrInf == true) { //Create an advertiser account generateAdvertiser(); } else { //Create an influencer account generateInfluencer(); } }*/ for (int i = 0; i < 1000; i++) { generateInfluencer(); } System.out.println(coll); /* BasicDBObject doc = new BasicDBObject("_id", "josh") .append("isActive", "true") .append("sphere", "Politics") .append("allowExplicit", "true") .append("totalValue", 0) .append("totalTweets", 0) .append("payoutOption", 50); coll.insert(doc); DBObject myDoc = coll.findOne(); System.out.println(myDoc); */ mongoClient.close(); }
From source file:aic2013.extractor.TwitterExtractor.java
public static void main(String[] args) throws Exception { EntityManagerFactory emf = null;//from www. j av a 2s.c o m MongoClient mongoClient = null; Twitter twitter = null; Neo4jConnection neo4j = null; try { // Database configuration Properties prop = new Properties(); prop.load(new FileInputStream("hibernate.properties")); // prop.load(TwitterExtractor.class.getClassLoader().getResourceAsStream("hibernate.properties")); emf = Persistence.createEntityManagerFactory("twitterdb", prop); final String mongoServer = "localhost"; mongoClient = new MongoClient(mongoServer); twitter = TwitterFactory.getSingleton(); // final String neo4jJdbc = "jdbc:neo4j:ec2-54-217-131-208.eu-west-1.compute.amazonaws.com:7474"; final String neo4jJdbc = "jdbc:neo4j://localhost:7474"; neo4j = new Driver().connect(neo4jJdbc, new Properties()); neo4j.setAutoCommit(true);//false); final TwitterDataAccess twitterDataAccess = new TwitterDataAccess(twitter); final MongoDataAccess mongoDataAccess = new MongoDataAccess(mongoClient); final Neo4jService neo4jService = new Neo4jService(neo4j); final EntityManager em = emf.createEntityManager(); final UserDataAccess userDataAcces = new UserDataAccess(em); final TopicExtractionCoordinator extractionCoordinator = new TopicExtractionCoordinatorImpl(); // final ConcurrentLinkedQueue<E> final UserService userService = new UserService(em); final Processor<Status> mongoProcessor = new Processor<Status>() { @Override public void process(final Status status) { final TwitterUser user = new TwitterUser(status.getUser()); userService.persist(user); neo4jService.transactional(new Neo4jUnitOfWork() { @Override public void process() throws SQLException { neo4jService.createPersonIfAbsent(user); // HashtagEntity[] topics = // status.getHashtagEntities(); Status originalStatus = status; if (status.isRetweet()) { originalStatus = status.getRetweetedStatus(); } extractionCoordinator.doExtraction(originalStatus, new TopicExtractionCallback() { @Override public void handleExtractionResult(Set<Topic> extractedTopics) { /* TODO: comment out outputs */ // System.out.println(status.getText()); // for (Topic t : extractedTopics) { // System.out.println(t.getName()); // } try { /* add hash tags to topics */ for (HashtagEntity tag : status.getHashtagEntities()) { extractedTopics.add(new Topic(new String[] { tag.getText() })); } for (Topic topic : extractedTopics) { neo4jService.createTopicIfAbsent(topic); if (status.isRetweet()) { neo4jService.createRelationIfAbsent("RETWEETS", user, topic); } else { neo4jService.createRelationIfAbsent("TWEETS", user, topic); } } } catch (SQLException e) { throw new RuntimeException(e); } } @Override public void handleExtractionError(ExtractionException e) { throw new RuntimeException(e); } }); } }); } }; final Processor<TwitterUser> userProcessor = new Processor<TwitterUser>() { @Override public void process(final TwitterUser user) { try { twitterDataAccess.forAllFollowers(user, new Processor<User>() { @Override public void process(User u) { final TwitterUser follower = em.find(TwitterUser.class, u.getId()); if (follower != null) { neo4jService.transactional(new Neo4jUnitOfWork() { @Override public void process() throws SQLException { neo4jService.createUniqueRelation("FOLLOWS", user, follower); } }); } } }); } catch (Exception ex) { throw new RuntimeException(ex); } } }; // invoke the processor for every entry in mongo mongoDataAccess.forAll(mongoProcessor); extractionCoordinator.awaitTermination(-1, TimeUnit.SECONDS); // invoke the processor for every entry in the rdbms // userDataAcces.forAll(userProcessor); } finally { if (emf != null && emf.isOpen()) { emf.close(); } if (mongoClient != null) { mongoClient.close(); } if (twitter != null) { twitter.shutdown(); } if (neo4j != null) { neo4j.close(); } } }