List of usage examples for com.mongodb MongoClientOptions builder
public static Builder builder()
From source file:example.MongoCredentialsExample.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { String server = args[0];/* w w w.ja v a 2s . c om*/ String user = args[1]; String password = args[2]; String databaseName = args[3]; System.out.println("server: " + server); System.out.println("user: " + user); System.out.println("database: " + databaseName); System.out.println(); MongoClient mongoClient = new MongoClient(new ServerAddress(server), asList(MongoCredential.createMongoCRCredential(user, "test", password.toCharArray())), new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build()); DB testDB = mongoClient.getDB(databaseName); System.out.println("Count: " + testDB.getCollection("test").count()); System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject())); }
From source file:example.ScramSha1CredentialsExample.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { String server = args[0];// w w w. ja v a2s . c o m String user = args[1]; String password = args[2]; String source = args[3]; System.out.println("server: " + server); System.out.println("user: " + user); System.out.println("source: " + source); System.out.println(); MongoClient mongoClient = new MongoClient(new ServerAddress(server), Arrays.asList(MongoCredential.createScramSha1Credential(user, source, password.toCharArray())), new MongoClientOptions.Builder().build()); DB testDB = mongoClient.getDB("test"); System.out.println("Count: " + testDB.getCollection("test").count()); System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject())); }
From source file:example.springdata.mongodb.util.MongosSystemForTestFactory.java
License:Apache License
private void initializeReplicaSet(Entry<String, List<IMongodConfig>> entry) throws Exception { String replicaName = entry.getKey(); List<IMongodConfig> mongoConfigList = entry.getValue(); if (mongoConfigList.size() < 3) { throw new Exception("A replica set must contain at least 3 members."); }/*from w ww .j a v a2 s .c o m*/ // Create 3 mongod processes for (IMongodConfig mongoConfig : mongoConfigList) { if (!mongoConfig.replication().getReplSetName().equals(replicaName)) { throw new Exception("Replica set name must match in mongo configuration"); } IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaultsWithLogger(Command.MongoD, logger) .processOutput(outputFunction.apply(Command.MongoD)).build(); MongodStarter starter = MongodStarter.getInstance(runtimeConfig); MongodExecutable mongodExe = starter.prepare(mongoConfig); MongodProcess process = mongodExe.start(); mongodProcessList.add(process); } Thread.sleep(1000); MongoClientOptions mo = MongoClientOptions.builder().connectTimeout(10).build(); MongoClient mongo = new MongoClient( new ServerAddress(mongoConfigList.get(0).net().getServerAddress().getHostName(), mongoConfigList.get(0).net().getPort()), mo); DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME); CommandResult cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1)); logger.info("isMaster: {}", cr); // Build BSON object replica set settings DBObject replicaSetSetting = new BasicDBObject(); replicaSetSetting.put("_id", replicaName); BasicDBList members = new BasicDBList(); int i = 0; for (IMongodConfig mongoConfig : mongoConfigList) { DBObject host = new BasicDBObject(); host.put("_id", i++); host.put("host", mongoConfig.net().getServerAddress().getHostName() + ":" + mongoConfig.net().getPort()); members.add(host); } replicaSetSetting.put("members", members); logger.info(replicaSetSetting.toString()); // Initialize replica set cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate", replicaSetSetting)); logger.info("replSetInitiate: {}", cr); Thread.sleep(5000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.info("replSetGetStatus: {}", cr); // Check replica set status before to proceed while (!isReplicaSetStarted(cr)) { logger.info("Waiting for 3 seconds..."); Thread.sleep(1000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.info("replSetGetStatus: {}", cr); } mongo.close(); mongo = null; }
From source file:example.springdata.mongodb.util.MongosSystemForTestFactory.java
License:Apache License
private void configureMongos() throws Exception { CommandResult cr;/*ww w.ja v a 2 s . co m*/ MongoClientOptions options = MongoClientOptions.builder().connectTimeout(10).build(); try (MongoClient mongo = new MongoClient( new ServerAddress(this.config.net().getServerAddress().getHostName(), this.config.net().getPort()), options)) { DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME); // Add shard from the replica set list for (Entry<String, List<IMongodConfig>> entry : this.replicaSets.entrySet()) { String replicaName = entry.getKey(); String command = ""; for (IMongodConfig mongodConfig : entry.getValue()) { if (command.isEmpty()) { command = replicaName + "/"; } else { command += ","; } command += mongodConfig.net().getServerAddress().getHostName() + ":" + mongodConfig.net().getPort(); } logger.info("Execute add shard command: {}", command); cr = mongoAdminDB.command(new BasicDBObject("addShard", command)); logger.info(cr.toString()); } logger.info("Execute list shards."); cr = mongoAdminDB.command(new BasicDBObject("listShards", 1)); logger.info(cr.toString()); // Enabled sharding at database level logger.info("Enabled sharding at database level"); cr = mongoAdminDB.command(new BasicDBObject("enableSharding", this.shardDatabase)); logger.info(cr.toString()); // Create index in sharded collection logger.info("Create index in sharded collection"); DB db = mongo.getDB(this.shardDatabase); db.getCollection(this.shardCollection).createIndex(this.shardKey); // Shard the collection logger.info("Shard the collection: {}.{}", this.shardDatabase, this.shardCollection); DBObject cmd = new BasicDBObject(); cmd.put("shardCollection", this.shardDatabase + "." + this.shardCollection); cmd.put("key", new BasicDBObject(this.shardKey, 1)); cr = mongoAdminDB.command(cmd); logger.info(cr.toString()); logger.info("Get info from config/shards"); DBCursor cursor = mongo.getDB("config").getCollection("shards").find(); while (cursor.hasNext()) { DBObject item = cursor.next(); logger.info(item.toString()); } } }
From source file:example.X509CredentialsExample.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { String server = args[0];//w ww . ja v a 2 s .co m String user = "CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US"; System.out.println("server: " + server); System.out.println("user: " + user); System.out.println(); MongoClient mongoClient = new MongoClient(new ServerAddress(server), Arrays.asList(MongoCredential.createMongoX509Credential(user)), new MongoClientOptions.Builder().socketFactory(SSLSocketFactory.getDefault()).build()); DB testDB = mongoClient.getDB("test"); System.out.println("Count: " + testDB.getCollection("test").count()); System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject())); }
From source file:ezbakehelpers.mongoutils.MongoHelper.java
License:Apache License
public MongoClientOptions getMongoClientOptions() { MongoClientOptions.Builder builder = MongoClientOptions.builder(); if (mongoConfigurationHelper.useMongoDBSSL()) { try {/*from w w w. j a va 2 s.c o m*/ builder.socketFactory(sslConfigurationHelper.getSystemSSLContext().getSocketFactory()); } catch (IOException | SSLContextException e) { logger.warn("Mongo configured with SSL, but failed to load the system SSL context", e); } } return builder.build(); }
From source file:fr.eolya.utils.nosql.mongodb.MongoDBConnection.java
License:Apache License
/** * @param hostName The MongoDB server host name * @param hostPort The MongoDB server host port * @return// w w w. jav a2 s .c o m * @throws UnknownHostException */ public MongoDBConnection(String hostName, int hostPort, String userName, String userPassword) throws UnknownHostException { MongoClientOptions.Builder builder = new MongoClientOptions.Builder(); builder.autoConnectRetry(true); builder.socketKeepAlive(true); builder.writeConcern(WriteConcern.SAFE); if ("".equals(hostName)) hostName = "localhost"; if (hostPort > 0) { ServerAddress addr = new ServerAddress(hostName, hostPort); m = new MongoClient(addr, builder.build()); } else { m = new MongoClient(hostName, builder.build()); } this.hostName = hostName; this.hostPort = hostPort; }
From source file:fr.gouv.vitam.mdbes.MainErazeData.java
License:Open Source License
/** * Will save to a File and to ElasticSearch, then to MongoDB * * @param args//from ww w .j ava 2 s . c o m * logfile eraze/noeraze host database escluster unicast start nbload file fileout limitdepth nbThread mongoimport * stopindex/xx * * <ol> * <li>logfile = Log4J configuration log file</li> * <li>eraze/noeraze = eraze will delete all data in DB (!), else nothing is done</li> * <li>host = MongoDB host</li> * <li>database = MongoDB database name as VitamLinks</li> * <li>escluster = ElasticSearch cluster name</li> * <li>unicast = ElasticSearch unicast servers list (as in "mdb001, mdb002, mdb003")</li> * </ol> */ public static void main(final String[] args) throws Exception { if (args.length < 6) { System.err.println("need: logfile eraze/noeraze host database escluster unicast"); return; } final String log4j = args[0]; PropertyConfigurator.configure(log4j); VitamLoggerFactory.setDefaultFactory(new LogbackLoggerFactory(VitamLogLevel.WARN)); LOGGER = VitamLoggerFactory.getInstance(MainErazeData.class); MongoDbAccess dbvitam = null; try { if (args.length > 1) { eraze = args[1].equals("eraze"); } if (simulate) { eraze = false; } final String networkHost = "192.168.56.102"; GlobalDatas.localNetworkAddress = networkHost; // connect to the local database server if (args.length > 2) { host = args[2]; } if (args.length > 3) { database = args[3]; } if (args.length > 4) { esbase = args[4]; } if (args.length > 5) { unicast = args[5]; } LOGGER.debug("Start with " + eraze + ":" + host + ":" + database + ":" + esbase + ":" + unicast); MAXTHREAD += nbThread; final MongoClientOptions options = new MongoClientOptions.Builder().connectionsPerHost(MAXTHREAD) .build(); mongoClient = new MongoClient(host, options); mongoClient.setReadPreference(ReadPreference.primaryPreferred()); dbvitam = new MongoDbAccess(mongoClient, database, esbase, unicast, eraze); // get a list of the collections in this database and print them out LOGGER.debug(dbvitam.toString()); if (eraze) { reinit(dbvitam); LOGGER.warn(dbvitam.toString()); return; } return; } catch (Exception e) { LOGGER.error(e); } finally { // release resources final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2); final ToClean toclean = new ToClean(dbvitam); scheduler.schedule(toclean, 1, TimeUnit.MILLISECONDS); final ToShutdown toShutdown = new ToShutdown(); scheduler.schedule(toShutdown, 5000, TimeUnit.MILLISECONDS); scheduler.awaitTermination(7000, TimeUnit.MILLISECONDS); System.exit(0); } }
From source file:fr.gouv.vitam.mdbes.MainIngestESFromFile.java
License:Open Source License
/** * @param args/*from www . j av a 2 s .co m*/ */ public static void main(final String[] args) throws Exception { if (args.length < 6) { System.err.println("need: logfile host escluster unicast indextype files"); return; } final String log4j = args[0]; PropertyConfigurator.configure(log4j); final String networkHost = "192.168.56.102"; GlobalDatas.localNetworkAddress = networkHost; // connect to the local database server if (args.length > 1) { host = args[1]; } if (args.length > 2) { esbase = args[2]; } if (args.length > 3) { unicast = args[3]; } if (args.length > 4) { model = args[4]; } MongoDbAccess dbvitam = null; try { final MongoClientOptions options = new MongoClientOptions.Builder().connectionsPerHost(4).build(); mongoClient = new MongoClient(host, options); mongoClient.setReadPreference(ReadPreference.primaryPreferred()); dbvitam = new MongoDbAccess(mongoClient, "VitamLinks", esbase, unicast, false); dbvitam.updateEsIndex(model); MainIngestESFromFile.loadt = new AtomicLong(0); MainIngestFile.cptMaip.set(0); for (int i = 5; i < args.length - 1; i++) { System.out.println("Load " + args[i]); runOnce(dbvitam, args[i], true); } int i = args.length - 1; System.out.println("Load " + args[i]); runOnce(dbvitam, args[i], false); } catch (final Exception e) { System.err.println("ERROR: " + e.getMessage()); e.printStackTrace(); } finally { // release resources final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2); final ToClean toclean = new ToClean(dbvitam); scheduler.schedule(toclean, 1, TimeUnit.MILLISECONDS); final ToShutdown toShutdown = new ToShutdown(); scheduler.schedule(toShutdown, 5000, TimeUnit.MILLISECONDS); scheduler.awaitTermination(7000, TimeUnit.MILLISECONDS); System.exit(0); } }
From source file:fr.gouv.vitam.mdbes.MainIngestFile.java
License:Open Source License
/** * Will save to a File and to ElasticSearch, then to MongoDB * * @param args/*from www . j ava2s . c om*/ * logfile eraze/noeraze host database escluster unicast start nbload file fileout limitdepth nbThread mongoimport * stopindex/xx * * <ol> * <li>logfile = Log4J configuration log file</li> * <li>noeraze/index = index will (re)create index, else nothing is done</li> * <li>host = MongoDB host</li> * <li>database = MongoDB database name as VitamLinks</li> * <li>escluster = ElasticSearch cluster name</li> * <li>unicast = ElasticSearch unicast servers list (as in "mdb001, mdb002, mdb003")</li> * <li>start = start index in the bench (will be for instance between 1-1000 start from 100)</li> * <li>nbload = number of iteration from start</li> * <li>file = ingest file</li> * <li>fileout = output saved</li> * <li>limitdepth = from which level the output is saved to the file and not to MongoDB</li> * <li>nbThread = number of thread (default 1)</li> * <li>mongoimport = optional command for import</li> * <li>stopindex/xx = shall we stop index during import in MongoDB</li> * </ol> */ public static void main(final String[] args) throws Exception { if (args.length < 6) { System.err.println( "need: logfile noeraze/index host database escluster unicast start nbload file fileout limitdepth mongoimport stopindex/xx nbThread"); // System.err.println("before was need: logfile nbload files eraze/noeraze start host escluster unicast fileout limitdepth mongoimport 0/1 (1=stop index)"); return; } final String log4j = args[0]; PropertyConfigurator.configure(log4j); VitamLoggerFactory.setDefaultFactory(new LogbackLoggerFactory(VitamLogLevel.WARN)); LOGGER = VitamLoggerFactory.getInstance(MainIngestFile.class); boolean reindex = false; if (args.length > 1) { reindex = args[1].equals("index"); } if (simulate) { reindex = false; } final String networkHost = "192.168.56.102"; GlobalDatas.localNetworkAddress = networkHost; // connect to the local database server if (args.length > 2) { host = args[2]; } if (args.length > 3) { database = args[3]; } if (args.length > 4) { esbase = args[4]; } if (args.length > 5) { unicast = args[5]; } int realnb = -1; if (args.length > 6) { startFrom = Integer.parseInt(args[6]); } if (args.length > 7) { realnb = Integer.parseInt(args[7]); } if (args.length > 8) { ingest = FileUtil.readFile(args[8]); } if (args.length > 9) { fileout = args[9]; } if (args.length > 10) { final int stoplevel = Integer.parseInt(args[10]); minleveltofile = stoplevel; } if (args.length > 11) { nbThread = Integer.parseInt(args[11]); } if (args.length > 12) { commandMongo = args[12]; } boolean stopindex = false; if (args.length > 13) { stopindex = args[13].equalsIgnoreCase("stopindex"); } LOGGER.debug("Start with " + reindex + ":" + host + ":" + database + ":" + esbase + ":" + unicast); if (args.length > 6) { LOGGER.debug("and " + startFrom + ":" + realnb + ":" + ingest + ":" + fileout + ":" + minleveltofile + ":" + nbThread + ":" + commandMongo + ":" + stopindex); } MongoDbAccess dbvitam = null; try { MAXTHREAD += nbThread; final MongoClientOptions options = new MongoClientOptions.Builder().connectionsPerHost(MAXTHREAD) .build(); mongoClient = new MongoClient(host, options); mongoClient.setReadPreference(ReadPreference.primaryPreferred()); dbvitam = new MongoDbAccess(mongoClient, database, esbase, unicast, reindex); // get a list of the collections in this database and print them out LOGGER.debug(dbvitam.toString()); if (realnb < 0) { return; } // drop all the data in it final ParserIngest parser = new ParserIngest(true); parser.parse(ingest); model = parser.getModel(); if (reindex) { LOGGER.debug("ensureIndex"); dbvitam.ensureIndex(); if (model != null) { LOGGER.debug("updateEsIndex"); dbvitam.updateEsIndex(model); } LOGGER.debug("end Index"); } LOGGER.warn(dbvitam.toString()); final int stepnb = realnb; nb = stepnb; loadt = new AtomicLong(0); cptMaip.set(0); runOnce(dbvitam); // Continue with MongoDB Loading if setup if (commandMongo != null) { System.out.println("Launch MongoImport"); runOnceMongo(dbvitam, stopindex); } } catch (Exception e) { LOGGER.error(e); } finally { // release resources final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2); final ToClean toclean = new ToClean(dbvitam); scheduler.schedule(toclean, 1, TimeUnit.MILLISECONDS); final ToShutdown toShutdown = new ToShutdown(); scheduler.schedule(toShutdown, 5000, TimeUnit.MILLISECONDS); scheduler.awaitTermination(7000, TimeUnit.MILLISECONDS); System.exit(0); } }