public boolean connectToDatabaseCluster(final List<String> seeds) { try { List<ServerAddress> seedList = new ArrayList<>(); for (String ip : seeds) { seedList.add(new ServerAddress(ip, MONGO_PORT)); } mongoClient = new MongoClient(seedList); mongoDatabase = mongoClient.getDatabase("featureStore"); dbCollectionList = getCollectionList(mongoDatabase); log.info("Connect to database cluster successfully!!"); return true; } catch (Exception e) { log.warn(e.getMessage()); return false; } }
@Bean() public static CodecRegistry getCodecRegistry() { return CodecRegistries.fromRegistries( CodecRegistries.fromProviders( new EnumCodecProvider(), PojoCodecProvider.builder() .register(CodecResolverTest.class) .registerCodecResolver((CodecResolver) (type, typeCodecRegistry, codecConfiguration) -> { if (TypeUtils.isAssignable(type, Base.class)) { return new DocumentCodec((Class<? extends Base>) type, typeCodecRegistry, codecConfiguration); } return null; }) .build() ), MongoClient.getDefaultCodecRegistry()); }
private static void setup() throws UnknownHostException, IOException { IMongoCmdOptions cmdOptions = new MongoCmdOptionsBuilder().verbose(false) .enableAuth(authEnabled).build(); IMongodConfig mongodConfig = new MongodConfigBuilder() .version(Version.Main.PRODUCTION) .net(new Net(LOCALHOST, MONGOS_PORT, Network.localhostIsIPv6())) .cmdOptions(cmdOptions).build(); IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaults( Command.MongoD).build(); mongodExecutable = MongodStarter.getInstance(runtimeConfig).prepare( mongodConfig); mongod = mongodExecutable.start(); mongoClient = new MongoClient(new ServerAddress(LOCALHOST, MONGOS_PORT)); createDbAndCollections(EMPLOYEE_DB, EMPINFO_COLLECTION, "employee_id"); createDbAndCollections(EMPLOYEE_DB, SCHEMA_CHANGE_COLLECTION, "field_2"); }
@Test public void failedInputOfComment() throws IOException { String json = "{ plantId: \"58d1c36efb0cac4e15afd27\", comment : \"Here is our comment for this test\" }"; assertFalse(plantController.addComment(json, "second uploadId")); MongoClient mongoClient = new MongoClient(); MongoDatabase db = mongoClient.getDatabase(databaseName); MongoCollection<Document> plants = db.getCollection("plants"); FindIterable findIterable = plants.find(); Iterator iterator = findIterable.iterator(); while(iterator.hasNext()){ Document plant = (Document) iterator.next(); List<Document> plantComments = (List<Document>) ((Document) plant.get("metadata")).get("comments"); assertEquals(0,plantComments.size()); } }
public static void main(String[] args) { MongoClientOptions mongoClientOptions = new MongoClientOptions.Builder().codecRegistry(getCodecRegistry()).build(); MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), mongoClientOptions); MongoDatabase database = mongoClient.getDatabase("tutorial"); MongoCollection<PolymorphicPojo> collection = database.getCollection("entities").withDocumentClass(PolymorphicPojo.class); // create some pojo Pojo pojo = new Pojo(); pojo.setName("A nice name"); pojo.setPojos(Arrays.asList(new SubPojo(42), new SubPojo(48))); // insert into db collection.insertOne(pojo); // read from db PolymorphicPojo foundPojo = collection.find(Filters.eq("_id", pojo.getId())).first(); // output LOGGER.debug("Found pojo {}", foundPojo); }
@Bean() public static CodecRegistry getCodecRegistry() { return CodecRegistries.fromRegistries( CodecRegistries.fromProviders( new EnumCodecProvider(), PojoCodecProvider.builder() .register(Pojo.class.getPackage().getName()) .registerCodecResolver((CodecResolver) (type, typeCodecRegistry, codecConfiguration) -> { if (TypeUtils.isAssignable(type, CustomId.class)) { return new CustomIdCodec((Class<CustomId>)type, typeCodecRegistry, codecConfiguration); } return null; }).build() ), MongoClient.getDefaultCodecRegistry()); }
public static <T extends OkraItem> void ensureIndexes(final Okra<T> okra, final MongoClient mongo, final String database, final String collection) { okra.getIndexDefs() .stream() .map(indexDef -> { final boolean ascending = indexDef.getOrdering() == null || indexDef.getOrdering().equals(Ordering.ASC); final Bson ordering = ascending ? Indexes.ascending(indexDef.getAttrs()) : Indexes.descending(indexDef.getAttrs()); return mongo .getDatabase(database) .getCollection(collection) .createIndex(ordering); }) .forEach(indexName -> LOGGER.info("Done. Index name: {}", indexName)); }
public BingoChessChallenge(String[] args) { announcer = new Chatter(args[0]); lichs = new HashMap<String,Lichesser>(); chessplayers = new HashMap<String,ChessPlayer>(); chessgames = new HashMap<String,LichessGame>(); BingoPlayer.SQUARE_BAG = new Vector<Dimension>(); for (int x=0;x<8;x++) for (int y=0;y<8;y++) BingoPlayer.SQUARE_BAG.add(new Dimension(x,y)); initIRC(args[0], args[1], args[2], args[3]); loadAdmins("res/admins.txt"); serv = new BingoServ(Integer.parseInt(args[4]),this); serv.startSrv(); bingoURL = args[5]; MongoClientURI connStr = new MongoClientURI("mongodb://bingobot:" + args[6] + "@localhost:27017/BingoBase"); MongoClient mongoClient = new MongoClient(connStr); MongoDatabase bingoBase = mongoClient.getDatabase("BingoBase"); playData = bingoBase.getCollection("players"); }
@Test public void successfulInputOfComment() throws IOException { String json = "{ plantId: \"58d1c36efb0cac4e15afd278\", comment : \"Here is our comment for this test\" }"; assertTrue(plantController.addComment(json, "second uploadId")); MongoClient mongoClient = new MongoClient(); MongoDatabase db = mongoClient.getDatabase(databaseName); MongoCollection<Document> plants = db.getCollection("plants"); Document filterDoc = new Document(); filterDoc.append("_id", new ObjectId("58d1c36efb0cac4e15afd278")); filterDoc.append("uploadID", "second uploadId"); Iterator<Document> iter = plants.find(filterDoc).iterator(); Document plant = iter.next(); List<Document> plantComments = (List<Document>) ((Document) plant.get("metadata")).get("comments"); long comments = plantComments.size(); assertEquals(1, comments); assertEquals("Here is our comment for this test", plantComments.get(0).getString("comment")); assertNotNull(plantComments.get(0).getObjectId("_id")); }
public void Connect(String user, String pass) { try { logger.info("Connecting to " + connectionString); // Authaenticate // MongoCredential credential = // MongoCredential.createCredential(user, // "admin", // pass); //Only users on admin as that will be mandatory in 3.6 mongoClient = new MongoClient(new MongoClientURI(connectionString)); mongoClient.getDatabase("admin") .runCommand(new Document("ping", 1)); } catch (Exception e) { logger.error("Unable to connect to MongoDB"); logger.error(e.getMessage()); System.exit(1); } this.user = user; this.pass = pass; }
@Test public void AddFlowerRatingReturnsTrueWithValidJsonInput() throws IOException{ String json = "{like: true, id: \"58d1c36efb0cac4e15afd202\"}"; assertTrue(plantController.addFlowerRating(json, "first uploadId")); MongoClient mongoClient = new MongoClient(); MongoDatabase db = mongoClient.getDatabase(databaseName); MongoCollection plants = db.getCollection("plants"); FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202"))); Iterator iterator = doc.iterator(); Document result = (Document) iterator.next(); List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings"); assertEquals(1, ratings.size()); Document rating = ratings.get(0); assertTrue(rating.getBoolean("like")); assertEquals(new ObjectId("58d1c36efb0cac4e15afd202"),rating.get("ratingOnObjectOfId")); }
@Test public void test_mongoservice_not_enabled() throws InitializationException { final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class); final StandardMongoClientService service = new StandardMongoClientService(); runner.addControllerService("test-mongo-closed", service); runner.enableControllerService(service); // Close MongoClient MongoClient client = service.getMongoClient(); // NOTE: This test requires mongo to be running assertEquals("localhost:27017", client.getConnectPoint()); // Close the mongo connection client.close(); // Now, this should throw an illegal state exception thrown.expect(IllegalStateException.class); client.getConnectPoint(); }
@Test public void testUpsertTrue() throws Exception { final TestRunner runner = TestRunners.newTestRunner(new UpdateMongo()); addMongoService(runner); runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME); runner.setProperty(MongoProps.COLLECTION, "upsert_test"); runner.setProperty(MongoProps.UPDATE_QUERY_KEYS, "d.id"); runner.setProperty(MongoProps.UPDATE_KEYS, "d.g"); runner.setProperty(MongoProps.UPDATE_OPERATOR, "$unset"); runner.setProperty(MongoProps.UPSERT, "true"); String contents = FileUtils.readFileToString(Paths.get("src/test/resources/update_payload.json").toFile()); runner.enqueue(contents.getBytes()); runner.run(); runner.assertTransferCount(AbstractMongoProcessor.REL_FAILURE, 0); runner.assertTransferCount(AbstractMongoProcessor.REL_SUCCESS, 1); // Verify that document wasn't inserted MongoClient client = mongo.getMongoClient(); MongoDatabase db = client.getDatabase(MONGO_DATABASE_NAME); if (db != null) { MongoCollection<Document> collection = db.getCollection("upsert_test"); assertEquals(1, collection.count()); } }
@BeforeTest private void configure() { final String mongoURI = System.getProperty("indra.mongoURI"); if (mongoURI == null) { Assert.fail("System.getProperty(\"indra.mongoURI\") is null. Provide a mongoURI to execute the integration test."); } MongoClientOptions builder = MongoClientOptions.builder().serverSelectionTimeout(5000).build(); MongoClient mongoClient = new MongoClient(mongoURI, builder); vectorSpaceFactory = new MongoVectorSpaceFactory(mongoClient); translatorFactory = new MongoTranslatorFactory(mongoClient); }
public TrajectoryPlanner(MongoClient mongoClient) { this.mongoClient = mongoClient; database = this.mongoClient.getDatabase("migi-database"); collectionBus = database.getCollection("bus"); collectionRoute1a = database.getCollection("route1a"); collectionRoute1b = database.getCollection("route1b"); }
@Bean() public static CodecRegistry getCodecRegistry() { return CodecRegistries.fromRegistries( CodecRegistries.fromProviders( new EnumCodecProvider(), PojoCodecProvider.builder().register(PreSaveHookTest.class).build() ), MongoClient.getDefaultCodecRegistry()); }
private MongoConnector(String connectURIStr) throws DiagnosticException { MongoClientURI clientURI = new MongoClientURI(connectURIStr); client = new MongoClient(clientURI); String dbName = clientURI.getDatabase() == null ? MONITOR_DB : clientURI.getDatabase(); db = client.getDatabase(dbName); }
public void setLiveUploadID(String uploadID){ MongoClient mongoClient = new MongoClient(); MongoDatabase test = mongoClient.getDatabase(databaseName); MongoCollection configCollection = test.getCollection("config"); configCollection.deleteMany(exists("liveUploadID")); configCollection.insertOne(new Document().append("liveUploadID", uploadID)); }
@Test public void testUploadFile() { String filePath = "/IDPH_STD_Illinois_By_County_By_Sex.xlsx"; Object object = new Object(); InputStream excelFile = object.getClass().getResourceAsStream(filePath); flowerController.uploadFile(excelFile); MongoClient mongoClient = new MongoClient(); MongoDatabase ddg = mongoClient.getDatabase("ddg"); MongoCollection flowers = ddg.getCollection("flowers"); assertEquals(1664, flowers.count()); }
public MongoStore(MongoConfig config) { super(); // Sanity checks if (config == null) { throw new IllegalArgumentException("MongoStore :: config, should not be blank"); } // client this.client = new MongoClient(config.getHost(), config.getPort()); this.database = client.getDatabase(config.getDatabase()); LOGGER.info("Successfully initiated the Mongo Connection with config : {}", config); }
public UserController(String dbName) throws IOException { // Set up our server address // (Default host: 'localhost', default port: 27017) // ServerAddress testAddress = new ServerAddress(); // Try connecting to the server //MongoClient mongoClient = new MongoClient(testAddress, credentials); MongoClient mongoClient = new MongoClient(); // Defaults! // Try connecting to a database MongoDatabase db = mongoClient.getDatabase(dbName); userCollection = db.getCollection("users"); }
public PlantController(String databaseName) throws IOException { // Set up our server address // (Default host: 'localhost', default port: 27017) // ServerAddress testAddress = new ServerAddress(); // Try connecting to the server //MongoClient mongoClient = new MongoClient(testAddress, credentials); MongoClient mongoClient = new MongoClient(); // Defaults! // Try connecting to a database MongoDatabase db = mongoClient.getDatabase(databaseName); plantCollection = db.getCollection("plants"); configCollection = db.getCollection("config"); }
@Test public void testUpsertFalse() throws Exception { final TestRunner runner = TestRunners.newTestRunner(new UpdateMongo()); addMongoService(runner); runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME); runner.setProperty(MongoProps.COLLECTION, "upsert_test"); runner.setProperty(MongoProps.UPDATE_QUERY_KEYS, "d.id"); runner.setProperty(MongoProps.UPDATE_KEYS, "d.g"); runner.setProperty(MongoProps.UPDATE_OPERATOR, "$unset"); runner.setProperty(MongoProps.UPSERT, "false"); String contents = FileUtils.readFileToString(Paths.get("src/test/resources/update_payload.json").toFile()); runner.enqueue(contents.getBytes()); runner.run(); runner.assertTransferCount(AbstractMongoProcessor.REL_FAILURE, 0); runner.assertTransferCount(AbstractMongoProcessor.REL_SUCCESS, 1); // Verify that document wasn't inserted MongoClient client = mongo.getMongoClient(); MongoDatabase db = client.getDatabase(MONGO_DATABASE_NAME); if (db != null) { MongoCollection<Document> collection = db.getCollection("upsert_test"); assertEquals(0, collection.count()); } }
@Bean() public static CodecRegistry getCodecRegistry() { return CodecRegistries.fromRegistries( CodecRegistries.fromProviders( new EnumCodecProvider(), new CustomIdCodecProvider(), PojoCodecProvider.builder() .register(Pojo.class.getPackage().getName()) .ignoreTypesAnnotatedWith(IgnoreAnnotation.class) .build() ), MongoClient.getDefaultCodecRegistry()); }
@Bean() public static CodecRegistry getCodecRegistry() { return CodecRegistries.fromRegistries( CodecRegistries.fromProviders( new EnumCodecProvider(), PojoCodecProvider.builder().register(ListTypeCodecTest.class).build() ), MongoClient.getDefaultCodecRegistry()); }
public MongoWrapper(@Nonnull MongoDatabaseCredentials credentials) { MongoCredential mongoCredential = MongoCredential.createCredential( credentials.getUsername(), credentials.getDatabase(), credentials.getPassword().toCharArray() ); client = new MongoClient( new ServerAddress(credentials.getAddress(), credentials.getPort()), Collections.singletonList(mongoCredential) ); database = client.getDatabase(credentials.getDatabase()); morphia = new Morphia(); morphiaDatastore = morphia.createDatastore(client, credentials.getDatabase()); }
private FindIterable<Document> getCursor(){ MongoClient client = DBCacheManager.INSTANCE.getCachedMongoPool(mongoDbName, mongoUserName); //MongoClient client = DBCacheManager.INSTANCE.getCachedMongoPool(mongoDbName, "ccwOplRO"); client.setReadPreference(ReadPreference.secondary()); MongoCollection<Document> collection =client.getDatabase(localDb).getCollection(oplogRs); FindIterable<Document> it = collection.find(Filters.and(Filters.eq(NS, ns),Filters.gt(TS, lastReadTime))) .cursorType(CursorType.TailableAwait).noCursorTimeout(true).maxAwaitTime(30, TimeUnit.MINUTES); return it; }
@Bean @SuppressWarnings("unchecked") public MongoClient mongoClient() { MongoClient result = Mockito.mock(MongoClient.class); MongoIterable<String> iterableMock = Mockito.mock(MongoIterable.class); MongoCursor<String> iteratorMock = Mockito.mock(MongoCursor.class); Mockito.when(iterableMock.iterator()).thenReturn(iteratorMock); Mockito.when(iteratorMock.hasNext()).thenReturn(true).thenReturn(false); Mockito.when(iteratorMock.next()).thenReturn("local"); Mockito.when(result.listDatabaseNames()).thenReturn(iterableMock); return result; }
@Override boolean doVerify() throws Exception { final MongoClient client = new MongoClient(new ServerAddress(getHost(), getPort()), MongoClientOptions.builder().serverSelectionTimeout(3000).build()); client.getAddress(); return true; }
public MongoV3(List<ServerAddress> servers, List<MongoCredential> authors) { Builder options = new MongoClientOptions.Builder(); options.connectionsPerHost(50);// 连接池设置为300个连接,默认为100 options.connectTimeout(15000);// 连接超时,推荐>3000毫秒 options.maxWaitTime(5000); // options.socketTimeout(500); options.writeConcern(WriteConcern.W2); con = new MongoClient(servers, authors, options.build()); setMongoConnect(this); }
public MongodbDatabase() { config = StickyChunk.getInstance().getConfig().database.mongo; databaseName = config.databaseName; host = config.host; port = config.port; MongoClientURI connectionString = new MongoClientURI(String.format("mongodb://%s:%s", host, port)); MongoClient client = new MongoClient(connectionString); database = client.getDatabase(databaseName); }
@Override public void init(HazelcastInstance hazelcastInstance, Properties properties, String mapName) { String mongoUrl = (String) properties.get("mongo.url"); String dbName = (String) properties.get("mongo.db"); String collectionName = (String) properties.get("mongo.collection"); this.mongoClient = new MongoClient(new MongoClientURI(mongoUrl)); this.collection = mongoClient.getDatabase(dbName).getCollection(collectionName); }
public MqttHandler(DataSource postgres, Dispatcher dispatcher, MongoClient mongo, OnlineState state) { this.dispatcher = dispatcher; this.state = state; msgTable = new Messages(mongo); topicTable = new Topics(postgres, msgTable); subTable = new Subscribes(postgres); }
@Override protected void append(LoggingEvent loggingEvent) { if (mongoDatabase == null) { MongoClientURI connectionString = new MongoClientURI(connectionUrl); mongoClient = new MongoClient(connectionString); mongoDatabase = mongoClient.getDatabase(databaseName); logsCollection = mongoDatabase.getCollection(collectionName, BasicDBObject.class); } logsCollection.insertOne((BasicDBObject) loggingEvent.getMessage()); }
@Inject public CommentRepository(@Named("dbName") String dbName, MongoClient mongoClient) { DB mongoDb = mongoClient.getDB(dbName); jongo = new Jongo(mongoDb, new JacksonMapper.Builder() .registerModule(new Jdk8Module()) .registerModule(new JavaTimeModule()) .build()); }
@SuppressWarnings("deprecation") @Override public void init(Object obj) { super.init(obj); PropertiesWrapper configPropertieWrapper = (PropertiesWrapper) obj; String mongodbHost = configPropertieWrapper.getProperty("mongodb.host"); int mongodbPort = configPropertieWrapper.getIntProperty("mongodb.port", 27017); String mongodbDbName = configPropertieWrapper.getProperty("mongodb.dbname"); client = new MongoClient(mongodbHost, mongodbPort); db = client.getDB(mongodbDbName); jongo = new Jongo(db); setName("JongoDBService"); super.setActive(); }
public AgentConfigurationRepository(){ MongoClient mongoClient = new MongoClient( Properties.getValue(Dictionary.PROPERTY_MONGODB_HOST), 27017); DB db = mongoClient.getDB("eim"); collection = db.getCollection("agentConfiguration"); }
/** * @decription 初始化配置 * @author yi.zhang * @time 2017年6月2日 下午2:15:57 */ public void init(String servers,String database,String schema,String username,String password) { try { List<ServerAddress> saddress = new ArrayList<ServerAddress>(); if (servers != null && !"".equals(servers)) { for (String server : servers.split(",")) { String[] address = server.split(":"); String ip = address[0]; int port = 27017; if (address != null && address.length > 1) { port = Integer.valueOf(address[1]); } saddress.add(new ServerAddress(ip, port)); } } MongoCredential credential = MongoCredential.createScramSha1Credential(username, database,password.toCharArray()); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(credential); Builder builder = new MongoClientOptions.Builder(); builder.maxWaitTime(MAX_WAIT_TIME); // 通过连接认证获取MongoDB连接 MongoClient client = new MongoClient(saddress, credentials, builder.build()); // 连接到数据库 session = client.getDatabase(schema); } catch (Exception e) { logger.error("-----MongoDB Config init Error-----", e); } }
@Bean() public static CodecRegistry getCodecRegistry() { return CodecRegistries.fromRegistries( CodecRegistries.fromProviders( new EnumCodecProvider(), new CustomIdCodecProvider(), PojoCodecProvider.builder() .register(Pojo.class.getPackage().getName()) .ignoreTypesAnnotatedWith(IgnoreType.class) .build() ), MongoClient.getDefaultCodecRegistry()); }