List of usage examples for com.mongodb MongoClientURI MongoClientURI
public MongoClientURI(final String uri)
From source file:fi.vm.sade.osoitepalvelu.kooste.config.MongoConfig.java
License:EUPL
@Bean @Override/*from w ww. j a v a2 s .co m*/ public Mongo mongo() throws UnknownHostException { return new Mongo(new MongoURI(new MongoClientURI(mongoUri))); }
From source file:geojson.sof20181050.ConvertToGeoJSON.java
License:Apache License
/** * Performs the document updates using the legacy driver. * <p>//from w w w. ja v a 2s .c om * The main draw back here (other than those discussed in * {@link #doSynchronously()}) is the difficulty creating the GeoJSON * documents. * </p> * * @throws UnknownHostException * On an invalid URI. */ protected static void doLegacy() throws UnknownHostException { // Execute the query to find all of the documents and then // update them. final com.mongodb.MongoClient legacyClient = new com.mongodb.MongoClient(new MongoClientURI(URI)); final com.mongodb.DBCollection legacyCollection = legacyClient.getDB(theCollection.getDatabaseName()) .getCollection(theCollection.getName()); try { int count = 0; for (final DBObject doc : legacyCollection.find()) { final Object id = doc.get("_id"); final Number lat = (Number) doc.get("latitude_deg"); final Number lon = (Number) doc.get("longitude_deg"); final BasicDBObject query = new BasicDBObject(); query.append("_id", id); final ArrayList<Double> coordinates = new ArrayList<>(); coordinates.add(lon.doubleValue()); coordinates.add(lat.doubleValue()); final BasicDBObject geojson = new BasicDBObject("type", "Point"); geojson.append("coordinates", coordinates); final BasicDBObject set = new BasicDBObject("loc", geojson); final BasicDBObject update = new BasicDBObject("$set", set); legacyCollection.update(query, update, /* upsert= */false, /* multi= */false, WriteConcern.ACKNOWLEDGED); count += 1; } System.out.printf("Updated %d documents via the legacy driver.%n", count); } finally { // Always close the client. legacyClient.close(); } }
From source file:gridfs.GridFSTour.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes an optional single argument for the connection string * @throws FileNotFoundException if the sample file cannot be found * @throws IOException if there was an exception closing an input stream *//* w w w .j a va 2s .com*/ public static void main(final String[] args) throws FileNotFoundException, IOException { MongoClient mongoClient; if (args.length == 0) { // connect to the local database server mongoClient = new MongoClient(); } else { mongoClient = new MongoClient(new MongoClientURI(args[0])); } // get handle to "mydb" database MongoDatabase database = mongoClient.getDatabase("mydb"); database.drop(); GridFSBucket gridFSBucket = GridFSBuckets.create(database); /* * UploadFromStream Example */ // 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", "presentation")); ObjectId fileId = gridFSBucket.uploadFromStream("mongodb-tutorial", streamToUploadFrom, options); streamToUploadFrom.close(); System.out.println("The fileId of the uploaded file is: " + fileId.toHexString()); /* * OpenUploadStream Example */ // Get some data to write byte[] data = "Data to upload into GridFS".getBytes(StandardCharsets.UTF_8); GridFSUploadStream uploadStream = gridFSBucket.openUploadStream("sampleData"); uploadStream.write(data); uploadStream.close(); System.out.println("The fileId of the uploaded file is: " + uploadStream.getFileId().toHexString()); /* * Find documents */ gridFSBucket.find().forEach(new Block<GridFSFile>() { @Override public void apply(final GridFSFile gridFSFile) { System.out.println(gridFSFile.getFilename()); } }); /* * Find documents with a filter */ gridFSBucket.find(eq("metadata.contentType", "image/png")).forEach(new Block<GridFSFile>() { @Override public void apply(final GridFSFile gridFSFile) { System.out.println(gridFSFile.getFilename()); } }); /* * DownloadToStream */ FileOutputStream streamToDownloadTo = new FileOutputStream("/tmp/mongodb-tutorial.txt"); gridFSBucket.downloadToStream(fileId, streamToDownloadTo); streamToDownloadTo.close(); /* * DownloadToStreamByName */ streamToDownloadTo = new FileOutputStream("/tmp/mongodb-tutorial.txt"); GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(0); gridFSBucket.downloadToStreamByName("mongodb-tutorial", streamToDownloadTo, downloadOptions); streamToDownloadTo.close(); /* * OpenDownloadStream */ 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)); /* * OpenDownloadStreamByName */ downloadStream = gridFSBucket.openDownloadStreamByName("sampleData"); fileLength = (int) downloadStream.getGridFSFile().getLength(); bytesToWriteTo = new byte[fileLength]; downloadStream.read(bytesToWriteTo); downloadStream.close(); System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8)); /* * Rename */ gridFSBucket.rename(fileId, "mongodbTutorial"); /* * Delete */ gridFSBucket.delete(fileId); database.drop(); }
From source file:hadoop.mongo.treasury.TreasuryYieldMulti.java
License:Apache License
public static void main(final String[] pArgs) throws Exception { //Here is an example of how to use multiple collections as the input to //a hadoop job, from within Java code directly. MultiCollectionSplitBuilder builder = new MultiCollectionSplitBuilder(); builder.add(new MongoClientURI("mongodb://localhost:27017/mongo_hadoop.yield_historical.in"), null, true, null, null, null, false, null); Configuration conf = new Configuration(); conf.set(MultiMongoCollectionSplitter.MULTI_COLLECTION_CONF_KEY, builder.toJSON()); System.exit(ToolRunner.run(conf, new TreasuryYieldXMLConfig(conf), pArgs)); }
From source file:io.dirigible.mongodb.jdbc.MongodbConnection.java
License:Apache License
public MongodbConnection(String url, Properties info) { String dbUrl = url.replace("jdbc:", ""); MongoClientURI uri = new MongoClientURI(dbUrl); this.uri = uri; this.dbName = this.uri.getDatabase(); this.collectionName = this.uri.getCollection(); this.client = new MongoClient(this.uri); this.isClosed = false; this.info = info; if (this.info == null) this.info = new Properties(); this.clientOptions = this.client.getMongoClientOptions(); this.info.putAll(this.mongoClientOptionsAsProperties(this.clientOptions, this.info)); //retrieve these from connected client this.dbName = this.uri.getDatabase(); if (this.dbName != null) this.db = this.client.getDatabase(this.dbName); if (this.collectionName != null) this.collection = this.db.getCollection(this.collectionName); LOG.debug("Connected with client properties: " + this.info.toString()); }
From source file:io.leishvl.core.config.MongoConfiguration.java
License:Apache License
@Bean protected MongoClient mongoClient() throws UnknownHostException { return new MongoClient(new MongoClientURI(env.getRequiredProperty("spring.data.mongodb.uri"))); }
From source file:io.macgyver.mongodb.MongoDBServiceFactory.java
License:Apache License
public Object doCreateInstance(ServiceDefinition def) { Properties props = def.getProperties(); try {//from w w w. j a va 2 s . c o m return new ExtendedMongoClient(new MongoClientURI(injectCredentials(props.getProperty("uri"), props.getProperty("username"), props.getProperty("password")))); } catch (UnknownHostException e) { throw new ConfigurationException(e); } }
From source file:iss_trab_farmacia.util.SingletonBd.java
private SingletonBd() { final Morphia morphia = new Morphia(); morphia.mapPackage("iss_trab_farmacia.entity"); morphia.mapPackage("iss_trab_farmacia.util"); final Datastore datastore; datastore = morphia.createDatastore( new MongoClient(new MongoClientURI("mongodb://teste:123456@ds159737.mlab.com:59737/farmacia")), "farmacia"); datastore.ensureIndexes();//w w w. j a va 2s .c o m this.setDs(datastore); }
From source file:khp.pba.dba42.mongo.java
public static MongoDatabase db() { // To connect to mongodb server MongoClientURI conn = new MongoClientURI("mongodb://localhost:27017"); MongoClient mongoClient = new MongoClient(conn); // Now connect to your databases MongoDatabase db = mongoClient.getDatabase("social_net"); return db;/* ww w .ja va 2s .c om*/ }
From source file:localdomain.localhost.MongoDbTroubleshooter.java
License:Open Source License
public void run() throws Exception { try (PrintWriter writer = new PrintWriter(System.out)) { MongoClientURI mongoClientUri = new MongoClientURI(uri); writer.println("" + "host=" + mongoClientUri.getHosts() + ",username=" + mongoClientUri.getUsername() + ",database=" + mongoClientUri.getDatabase() + ",collection=" + mongoClientUri.getCollection() + ""); writer.println();//from w w w .j a v a2 s . com writer.println(); writer.println("# MongoClient"); writer.println(); MongoClient mongoClient = new MongoClient(mongoClientUri); writer.println("" + mongoClient + ""); writer.println(); writer.println(); writer.println("# Databases"); writer.println(); try { List<String> databaseNames = mongoClient.getDatabaseNames(); for (String databaseName : databaseNames) { writer.println("* " + databaseName + (databaseName.equals(mongoClientUri.getDatabase()) ? " - default database" : "")); } } catch (Exception e) { writer.println("Could not list the databases of the MongoDB instance: '" + e.getMessage() + "'"); } writer.println(); writer.println(); writer.println("# Database"); writer.println(); DB db = mongoClient.getDB(mongoClientUri.getDatabase()); writer.println("DB: " + db.getName() + ""); writer.println(); writer.println(); writer.println("## Collections"); writer.println(); Set<String> myCollections = db.getCollectionNames(); if (myCollections.isEmpty()) { writer.println("NO COLLECTIONS!"); } else { for (String collection : myCollections) { DBCollection dbCollection = db.getCollection(collection); writer.println("* " + dbCollection.getName() + " - " + dbCollection.getCount() + " entries"); } } } }