Java Code Examples for com.mongodb.MongoClient

The following are top voted examples for showing how to use com.mongodb.MongoClient. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: polymorphia   File: CodecResolverTest.java   View source code 8 votes vote down vote up
@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());
}
 
Example 2
Project: digital-display-garden-iteration-4-dorfner-v2   File: TestPlantComment.java   View source code 7 votes vote down vote up
@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());
    }
}
 
Example 3
Project: athena   File: FeatureDatabaseMgmtManager.java   View source code 7 votes vote down vote up
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;
    }
}
 
Example 4
Project: polymorphia   File: Tutorial.java   View source code 7 votes vote down vote up
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);
}
 
Example 5
Project: digital-display-garden-iteration-4-dorfner-v2   File: TestPlantComment.java   View source code 7 votes vote down vote up
@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"));
  }
 
Example 6
Project: QDrill   File: MongoTestSuit.java   View source code 7 votes vote down vote up
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");
}
 
Example 7
Project: uavstack   File: TestRestService.java   View source code 6 votes vote down vote up
@POST
@Path("testMongo1")
public void testMongo1(String jsonString) {

    MongoClient client = new MongoClient();
    client.listDatabaseNames().first();
    MongoDatabase db = client.getDatabase("apphubDataStore");
    db.listCollectionNames().first();
    MongoCollection<Document> collection = db.getCollection("test");
    collection.listIndexes().first();
    Document doc = new Document("name", "Amarcord Pizzeria")
            .append("contact",
                    new Document("phone", "264-555-0193").append("email", "[email protected]")
                            .append("location", Arrays.asList(-73.88502, 40.749556)))
            .append("stars", 2).append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));
    collection.insertOne(doc);
    collection.find().first();

    MongoClient client2 = new MongoClient("localhost:27017");
    db = client2.getDatabase("apphubDataStore");
    db.listCollectionNames().first();
    collection = db.getCollection("test");
    collection.listIndexes().first();

    client.close();
    client2.close();
}
 
Example 8
Project: polymorphia   File: ExternalIdCodecProviderTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 9
Project: OkraSync   File: IndexCreator.java   View source code 6 votes vote down vote up
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));
}
 
Example 10
Project: BingoChess   File: BingoChessChallenge.java   View source code 6 votes vote down vote up
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");
}
 
Example 11
Project: MongoSyphon   File: MongoConnection.java   View source code 6 votes vote down vote up
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;
}
 
Example 12
Project: digital-display-garden-iteration-3-sixguysburgers-fries   File: FlowerRating.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 13
Project: nifi-nars   File: StandardMongoClientServiceIT.java   View source code 6 votes vote down vote up
@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();
}
 
Example 14
Project: nifi-nars   File: UpdateMongoIT.java   View source code 5 votes vote down vote up
@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());
    }
}
 
Example 15
Project: Indra   File: MongoIndraDriverIT.java   View source code 5 votes vote down vote up
@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);
}
 
Example 16
Project: GoGo   File: TrajectoryPlanner.java   View source code 5 votes vote down vote up
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");
}
 
Example 17
Project: polymorphia   File: PreSaveHookTest.java   View source code 5 votes vote down vote up
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder().register(PreSaveHookTest.class).build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
 
Example 18
Project: environment.monitor   File: MongoConnector.java   View source code 5 votes vote down vote up
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);

}
 
Example 19
Project: digital-display-garden-iteration-4-dorfner-v2   File: ExcelParser.java   View source code 5 votes vote down vote up
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));
    }
 
Example 20
Project: digital-display-garden-iteration-2-spraguesanborn   File: FlowerControllerSpec.java   View source code 5 votes vote down vote up
@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());
}
 
Example 21
Project: osm-processor   File: MongoStore.java   View source code 5 votes vote down vote up
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);
}
 
Example 22
Project: digital-display-garden-iteration-2-spraguesanborn   File: UserController.java   View source code 5 votes vote down vote up
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");
}
 
Example 23
Project: digital-display-garden-iteration-4-dorfner-v2   File: PlantController.java   View source code 5 votes vote down vote up
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");
}
 
Example 24
Project: nifi-nars   File: UpdateMongoIT.java   View source code 5 votes vote down vote up
@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());
    }
}
 
Example 25
Project: polymorphia   File: ExternalIdCodecProviderTest.java   View source code 5 votes vote down vote up
@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());
}
 
Example 26
Project: polymorphia   File: ListTypeCodecTest.java   View source code 5 votes vote down vote up
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder().register(ListTypeCodecTest.class).build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
 
Example 27
Project: helper   File: MongoWrapper.java   View source code 5 votes vote down vote up
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());
}
 
Example 28
Project: mongodb-rdbms-sync   File: MngOpLogReader.java   View source code 5 votes vote down vote up
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;
}
 
Example 29
Project: cereebro   File: MongoDbRelationshipDetectorTest.java   View source code 5 votes vote down vote up
@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;
}
 
Example 30
Project: resource-verifier   File: MongoResourceVerifier.java   View source code 5 votes vote down vote up
@Override
boolean doVerify() throws Exception {
    final MongoClient client = new MongoClient(new ServerAddress(getHost(), getPort()),
            MongoClientOptions.builder().serverSelectionTimeout(3000).build());
    client.getAddress();
    return true;
}
 
Example 31
Project: wechat-mall   File: MongoV3.java   View source code 5 votes vote down vote up
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);
}
 
Example 32
Project: StickyChunk   File: MongodbDatabase.java   View source code 5 votes vote down vote up
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);
}
 
Example 33
Project: testcontainers-hazelcast   File: MongoMapStore.java   View source code 5 votes vote down vote up
@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);
}
 
Example 34
Project: london   File: MqttHandler.java   View source code 5 votes vote down vote up
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);
}
 
Example 35
Project: springboot-start   File: MongoAppender.java   View source code 5 votes vote down vote up
@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());
}
 
Example 36
Project: polymer-101-backend   File: CommentRepository.java   View source code 5 votes vote down vote up
@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());
}
 
Example 37
Project: CodeBroker   File: JongoDBService.java   View source code 5 votes vote down vote up
@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();
}
 
Example 38
Project: elastest-instrumentation-manager   File: AgentConfigurationRepository.java   View source code 5 votes vote down vote up
public AgentConfigurationRepository(){
	MongoClient mongoClient = new MongoClient( 
			Properties.getValue(Dictionary.PROPERTY_MONGODB_HOST), 
			27017);
	DB db = mongoClient.getDB("eim");
	collection = db.getCollection("agentConfiguration");
}
 
Example 39
Project: database-transform-tool   File: MongoDBFactory.java   View source code 5 votes vote down vote up
/**
 * @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);
	}
}
 
Example 40
Project: polymorphia   File: ExternalIdCodecProviderTest.java   View source code 5 votes vote down vote up
@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());
}