public EmbeddedMongo() throws IOException { // the following logging setup makes the logging a lot less // verbose // TODO: figure out how to control it further Logger logger = Logger.getLogger(getClass().getName()); IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaultsWithLogger(Command.MongoD, logger).build(); MongodStarter starter = MongodStarter.getInstance(runtimeConfig); // use instead of logging code above // MongodStarter starter = MongodStarter.getDefaultInstance(); IMongodConfig mongodConfig = new MongodConfigBuilder() .version(Version.Main.PRODUCTION) .net(new Net(PORT, Network.localhostIsIPv6())) .build(); _mongodExecutable = starter.prepare(mongodConfig); MongodProcess mongod = _mongodExecutable.start(); /* MongoClient mongo = new MongoClient("localhost", port); DB db = mongo.getDB("test"); DBCollection col = db.createCollection("testCol", new BasicDBObject()); col.save(new BasicDBObject("testDoc", new Date())); */ }
@BeforeClass public static void startMongoDB() throws UnknownHostException, IOException { MongodStarter starter = MongodStarter.getDefaultInstance(); IMongodConfig mongodConfig = new MongodConfigBuilder() .version(Version.Main.PRODUCTION) .net(new Net(PORT, Network.localhostIsIPv6())) .build(); mongodExecutable = null; try { mongodExecutable = starter.prepare(mongodConfig); MongodProcess mongod = mongodExecutable.start(); } catch (Exception e) { if (mongodExecutable != null) mongodExecutable.stop(); } }
// ### Usage - custom mongod process output // #### ... to console with line prefix public void testCustomOutputToConsolePrefix() { RuntimeConfig runtimeConfig = new RuntimeConfig(); runtimeConfig.setProcessOutput( new ProcessOutput( Processors.namedConsole("[mongod>]"), Processors.namedConsole("[MONGOD>]"), Processors.namedConsole("[console>]"))); MongodStarter runtime = MongodStarter.getInstance(runtimeConfig); }
@BeforeClass public static void initializeDB() throws IOException { /* * IStreamProcessor stream = new NullProcessor(); MongodStarter runtime * = MongodStarter.getInstance(new RuntimeConfigBuilder() * .defaults(Command.MongoD) .processOutput(new ProcessOutput(stream, * stream, stream)) .artifactStore(new ArtifactStoreBuilder() * .defaults(Command.MongoD) .executableNaming(new UserTempNaming()) * .build()) .build()); mongodExecutable = runtime.prepare(new * MongodConfigBuilder() .version(Version.Main.PRODUCTION) .net(new * Net(MONGO_TEST_PORT, Network.localhostIsIPv6())) .build()); */ MongodStarter runtime = MongodStarter.getDefaultInstance(); MongodConfig mongodConfig = new MongodConfig(Version.V2_4_1, 27017, Network.localhostIsIPv6()); mongodExecutable = runtime.prepare(mongodConfig); mongodProcess = mongodExecutable.start(); }
@BeforeClass public static void startMongo() throws Exception { IMongodConfig config = new MongodConfigBuilder() .version(Version.Main.PRODUCTION) .net(new Net(27018, Network.localhostIsIPv6())) .build(); mongoDb = MongodStarter.getDefaultInstance().prepare(config); mongoDb.start(); }
// ### Usage public void testStandard() throws UnknownHostException, IOException { int port = 12345; MongodConfig mongodConfig = new MongodConfig(Version.Main.V2_0, port, Network.localhostIsIPv6()); MongodStarter runtime = MongodStarter.getDefaultInstance(); MongodExecutable mongodExecutable = null; try { mongodExecutable = runtime.prepare(mongodConfig); MongodProcess mongod = mongodExecutable.start(); Mongo mongo = new Mongo("localhost", port); DB db = mongo.getDB("test"); DBCollection col = db.createCollection("testCol", new BasicDBObject()); col.save(new BasicDBObject("testDoc", new Date())); } finally { if (mongodExecutable != null) mongodExecutable.stop(); } }
// #### ... to file public void testCustomOutputToFile() throws FileNotFoundException, IOException { RuntimeConfig runtimeConfig = new RuntimeConfig(); IStreamProcessor mongodOutput = Processors.named( "[mongod>]", new FileStreamProcessor(File.createTempFile("mongod", "log"))); IStreamProcessor mongodError = new FileStreamProcessor(File.createTempFile("mongod-error", "log")); IStreamProcessor commandsOutput = Processors.namedConsole("[console>]"); runtimeConfig.setProcessOutput(new ProcessOutput(mongodOutput, mongodError, commandsOutput)); MongodStarter runtime = MongodStarter.getInstance(runtimeConfig); }
@Override public void before() throws Throwable { int port = Network.getFreeServerPort(); String portProp = System.getProperty(MONGO_PORT_PROP); if (portProp != null && !portProp.isEmpty()) { port = Integer.valueOf(portProp); } IMongodConfig conf = new MongodConfigBuilder() .version(Version.Main.PRODUCTION) .net(new Net(port, Network.localhostIsIPv6())) .build(); Command command = Command.MongoD; IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder() .defaultsWithLogger(command, LOGGER) .artifactStore( new ArtifactStoreBuilder() .defaults(command) .download( new DownloadConfigBuilder() .defaultsForCommand(command) .proxyFactory(new SystemProxy()))) .build(); MongodStarter runtime = MongodStarter.getInstance(runtimeConfig); mongoExec = runtime.prepare(conf); mongoProc = mongoExec.start(); client = new MongoClient(new ServerAddress(conf.net().getServerAddress(), conf.net().getPort())); // set the property for our config... System.setProperty("dbhost", conf.net().getServerAddress().getHostAddress()); System.setProperty("dbport", Integer.toString(conf.net().getPort())); }
// ### ... automagic public void testFreeServerPortAuto() throws UnknownHostException, IOException { MongodConfig mongodConfig = new MongodConfig(Version.Main.V2_0); MongodStarter runtime = MongodStarter.getDefaultInstance(); MongodExecutable mongodExecutable = null; try { mongodExecutable = runtime.prepare(mongodConfig); MongodProcess mongod = mongodExecutable.start(); Mongo mongo = new Mongo( new ServerAddress( mongodConfig.net().getServerAddress(), mongodConfig.net().getPort())); DB db = mongo.getDB("test"); DBCollection col = db.createCollection("testCol", new BasicDBObject()); col.save(new BasicDBObject("testDoc", new Date())); } finally { if (mongodExecutable != null) mongodExecutable.stop(); } }
// ### Customize Artifact Storage public void testCustomizeArtifactStorage() throws IOException { MongodConfig mongodConfig = new MongodConfig(Version.Main.V2_0, 12345, Network.localhostIsIPv6()); /// - 8<- - - - IDirectory artifactStorePath = new FixedPath(System.getProperty("user.home") + "/.embeddedMongodbCustomPath"); ITempNaming executableNaming = new UUIDTempNaming(); RuntimeConfig runtimeConfig = new RuntimeConfig(); runtimeConfig.getDownloadConfig().setArtifactStorePathNaming(artifactStorePath); runtimeConfig.setExecutableNaming(executableNaming); MongodStarter runtime = MongodStarter.getInstance(runtimeConfig); MongodExecutable mongodExe = runtime.prepare(mongodConfig); /// - >8- - - - MongodProcess mongod = mongodExe.start(); mongod.stop(); mongodExe.stop(); }
public static void main(String[] args) { try { int port = 12345; MongodProcess mongod = null; MongodConfig mongodConfig = new MongodConfig(Version.Main.V2_2, port, Network.localhostIsIPv6()); MongodStarter runtime = MongodStarter.getDefaultInstance(); MongodExecutable mongodExecutable = runtime.prepare(mongodConfig); mongod = mongodExecutable.start(); Mongo mongo = new Mongo("localhost", port); DB db = mongo.getDB("test"); DBCollection col = db.createCollection("testCol", new BasicDBObject()); col.save(new BasicDBObject("testDoc", new Date())); Thread.sleep(5000); mongod.stop(); } catch (Exception e) { } }
// #### ... to java logging public void testCustomOutputToLogging() throws FileNotFoundException, IOException { Logger logger = Logger.getLogger(getClass().getName()); RuntimeConfig runtimeConfig = new RuntimeConfig(); runtimeConfig.setProcessOutput( new ProcessOutput( Processors.logTo(logger, Level.INFO), Processors.logTo(logger, Level.SEVERE), Processors.named("[console>]", Processors.logTo(logger, Level.FINE)))); runtimeConfig .getDownloadConfig() .setProgressListener(new LoggingProgressListener(logger, Level.FINE)); MongodStarter runtime = MongodStarter.getInstance(runtimeConfig); }
public static void init() throws Exception { ezConfiguration = new EzConfiguration(new ClasspathConfigurationLoader()).getProperties(); ezConfiguration.setProperty(EzBakePropertyConstants.MONGODB_HOST_NAME, "localhost"); ezConfiguration.setProperty(EzBakePropertyConstants.MONGODB_PORT, Integer.toString(port)); MongodStarter starter = MongodStarter.getDefaultInstance(); IMongodConfig mongodConfig = new MongodConfigBuilder() .version(Version.Main.PRODUCTION) .net(new Net(port, Network.localhostIsIPv6())) .build(); mongod = starter.prepare(mongodConfig).start(); MongoConfigurationHelper mc = new MongoConfigurationHelper( ezConfiguration, new SystemConfigurationHelper(ezConfiguration).getTextCryptoProvider()); MongoClient mongoClient = new MongoClient("localhost", port); DB db = mongoClient.getDB(mc.getMongoDBDatabaseName()); db.addUser(mc.getMongoDBUserName(), mc.getMongoDBPassword().toCharArray()); }
public void start() { if (!this.active) { try { this.mongodProcess = MongodStarter.getDefaultInstance() .prepare( new MongodConfigBuilder() .version(Version.Main.V3_0) .net(new Net(this.mongoHost, this.mongoPort, this.mongoIPv6)) .build()) .start(); LoggerFactory.getLogger(EmbeddedMongo.class) .info("Successfully started EmbeddedMongoDB @ {}:{}", this.mongoHost, this.mongoPort); this.active = true; } catch (IOException e) { LoggerFactory.getLogger(EmbeddedMongo.class).error("Failed to start EmbeddedMongoDB", e); } } }
// #### ... to default java logging (the easy way) public void testDefaultOutputToLogging() throws FileNotFoundException, IOException { Logger logger = Logger.getLogger(getClass().getName()); RuntimeConfig runtimeConfig = RuntimeConfig.getInstance(logger); MongodStarter runtime = MongodStarter.getInstance(runtimeConfig); }
private void initMongoInstances() throws Exception { logger.debug("*** initMongoInstances ***"); CommandResult cr; // Create 3 mongod processes mongodConfig1 = new MongodConfig( new GenericVersion(mongoVersion), new Net(mongoPort1, Network.localhostIsIPv6()), new Storage(null, REPLICA_SET_NAME, 20), new Timeout()); MongodStarter starter = MongodStarter.getDefaultInstance(); mongodExe1 = starter.prepare(mongodConfig1); mongod1 = mongodExe1.start(); mongodConfig2 = new MongodConfig( new GenericVersion(mongoVersion), new Net(mongoPort2, Network.localhostIsIPv6()), new Storage(null, REPLICA_SET_NAME, 20), new Timeout()); mongodExe2 = starter.prepare(mongodConfig2); mongod2 = mongodExe2.start(); mongodConfig3 = new MongodConfig( new GenericVersion(mongoVersion), new Net(mongoPort3, Network.localhostIsIPv6()), new Storage(null, REPLICA_SET_NAME, 20), new Timeout()); mongodExe3 = starter.prepare(mongodConfig3); mongod3 = mongodExe3.start(); String server1 = Network.getLocalHost().getHostName() + ":" + mongodConfig1.net().getPort(); String server2 = Network.getLocalHost().getHostName() + ":" + mongodConfig2.net().getPort(); String server3 = Network.getLocalHost().getHostName() + ":" + mongodConfig3.net().getPort(); logger.debug("Server #1: {}", server1); logger.debug("Server #2: {}", server2); logger.debug("Server #3: {}", server3); Thread.sleep(2000); MongoClientOptions mco = MongoClientOptions.builder() .autoConnectRetry(true) .connectTimeout(15000) .socketTimeout(60000) .build(); mongo = new MongoClient( new ServerAddress(Network.getLocalHost().getHostName(), mongodConfig1.net().getPort()), mco); mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME); cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1)); logger.debug("isMaster: " + cr); // Initialize replica set cr = mongoAdminDB.command( new BasicDBObject( "replSetInitiate", (DBObject) JSON.parse( "{'_id': '" + REPLICA_SET_NAME + "', 'members': [{'_id': 0, 'host': '" + server1 + "'}, {'_id': 1, 'host': '" + server2 + "'}, {'_id': 2, 'host': '" + server3 + "', 'arbiterOnly' : true}]} }"))); logger.debug("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.debug("Waiting for 3 seconds..."); Thread.sleep(3000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.debug("replSetGetStatus: " + cr); } mongo.close(); mongo = null; // Initialize a new client using all instances. List<ServerAddress> mongoServers = new ArrayList<ServerAddress>(); mongoServers.add( new ServerAddress(Network.getLocalHost().getHostName(), mongodConfig1.net().getPort())); mongoServers.add( new ServerAddress(Network.getLocalHost().getHostName(), mongodConfig2.net().getPort())); mongoServers.add( new ServerAddress(Network.getLocalHost().getHostName(), mongodConfig3.net().getPort())); mongo = new MongoClient(mongoServers, mco); Assert.assertNotNull(mongo); mongo.setReadPreference(ReadPreference.secondaryPreferred()); mongo.setWriteConcern(WriteConcern.REPLICAS_SAFE); }