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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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: BingoChess   File: BingoChessChallenge.java   Source Code and License 7 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 6
Project: digital-display-garden-iteration-4-dorfner-v2   File: TestPlantComment.java   Source Code and License 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 7
Project: QDrill   File: MongoTestSuit.java   Source Code and License 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 8
Project: uavstack   File: TestRestService.java   Source Code and License 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 9
Project: polymorphia   File: ExternalIdCodecProviderTest.java   Source Code and License 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 10
Project: OkraSync   File: IndexCreator.java   Source Code and License 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 11
Project: MongoSyphon   File: MongoConnection.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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());
}
 
Example 41
Project: logregator   File: MongoTransporterConfig.java   Source Code and License 5 votes vote down vote up
public MongoTransporterConfig(Config config) {
    try {
        MongoClientOptions.Builder builder = MongoClientOptions.builder().connectTimeout(5000).socketTimeout(5000).serverSelectionTimeout(3000);
        client = new MongoClient(new ServerAddress(config.getConfigString("host"), config.getConfigInt("port")), builder.build());
        client.getAddress();
        database = client.getDatabase(config.getConfigString("database"));
        collection = database.getCollection(config.getConfigString("collection"));
    } catch (MongoTimeoutException e) {
        client.close();
        log.error("MongoClient initial failed", e);
        throw new LogregatorException();
    }
}
 
Example 42
Project: nifi-nars   File: StoreInMongoIT.java   Source Code and License 5 votes vote down vote up
@Test
public void emptySecondaryIndexTest() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new StoreInMongo());

    addMongoService(runner);
    runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME);
    runner.setProperty(MongoProps.COLLECTION, "index_test");
    // runner.setProperty(MongoProps.INDEX, "[{\"a\": 1}]");

    runner.run();

    // Connect to mongo to inspect indexes
    MongoClient client = mongo.getMongoClient();
    ListIndexesIterable<Document> indexes = client.getDatabase(MONGO_DATABASE_NAME).getCollection("index_test").listIndexes();

    List<Document> indexesArray = new ArrayList<>();
    indexesArray = indexes.into(indexesArray);

    // Check for compound index
    boolean hasCompound = false;
    for (Document doc : indexesArray) {
        if (doc.get("name").toString().equals("t_1_s_1")) {
            hasCompound = true;
        }
    }
    assertFalse("Should not have compound index", hasCompound);
}
 
Example 43
Project: KernelHive   File: DataManager.java   Source Code and License 5 votes vote down vote up
public GridFS connectToDatabase(ServerAddress server) {
	MongoCredential credential = MongoCredential.createMongoCRCredential("hive-dataserver", "admin", "hive-dataserver".toCharArray());
	MongoClient mongoClient = new MongoClient(server, Arrays.asList(credential));
	logger.info("got client");
	DB db = mongoClient.getDB("hive-dataserver");
	logger.info("Got DB");
	return new GridFS(db);
}
 
Example 44
Project: j1st-mqtt   File: MongoStorage.java   Source Code and License 5 votes vote down vote up
public void init(AbstractConfiguration config) {
    // MongoClient
    List<ServerAddress> addresses = parseAddresses(config.getString("mongo.address"));
    List<MongoCredential> credentials = parseCredentials(
            config.getString("mongo.userName"),
            "admin",
            config.getString("mongo.password"));
    if (addresses.size() == 1) {
        this.client = new MongoClient(addresses.get(0), credentials);
    } else {
        this.client = new MongoClient(addresses, credentials);
    }
    this.database = this.client.getDatabase(config.getString("mongo.database"));
}
 
Example 45
Project: Saber-Bot   File: Driver.java   Source Code and License 5 votes vote down vote up
public void init()
{
    MongoClient mongoClient = new MongoClient(new MongoClientURI(Main.getBotSettingsManager().getMongoURI()));
    db = mongoClient.getDatabase("saberDB");

    // schedule a thread to prune disconnected guild, schedules, and events from the database
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    executor.scheduleAtFixedRate(new Pruner(), 12*60*60, 12*60*60, TimeUnit.SECONDS);
}
 
Example 46
Project: nifi-nars   File: UpdateMongoIT.java   Source Code and License 5 votes vote down vote up
@After
public void tearDown() throws Exception {
    if (null != mongo) {
        MongoClient client = mongo.getMongoClient();
        MongoDatabase db = client.getDatabase(MONGO_DATABASE_NAME);
        if (db != null) {
            db.drop();
        }
        client.close();
    }
}
 
Example 47
Project: Backend   File: MongoDBManager.java   Source Code and License 5 votes vote down vote up
public void run()
{
    System.out.println("Starting MongoDB Manager...");
    // Es wird ein neuer MongoClient mit den Parametern host, database, user und password erstellt
    MongoClientURI uri = new MongoClientURI("mongodb://" + user + ":" + password + "@" + host + "/" + database); //
    client = new MongoClient(uri);

    // Es wird die Datenbank mit dem Wert der Variable
    db = client.getDatabase(database);
    if(db.getCollection("ratings") == null) db.createCollection("ratings");
}
 
Example 48
Project: OkraSync   File: OkraSyncImpl.java   Source Code and License 5 votes vote down vote up
public OkraSyncImpl(final MongoClient client, final String database,
                    final String collection, final Class<T> scheduleItemClass,
                    final long defaultHeartbeatExpiration,
                    final TimeUnit defaultHeartbeatExpirationUnit) {
    super(database, collection);
    this.client = client;
    this.scheduleItemClass = scheduleItemClass;
    this.defaultHeartbeatExpirationMillis = defaultHeartbeatExpirationUnit.toMillis(defaultHeartbeatExpiration);
    this.serializer = new DocumentSerializer();
    setup();
}
 
Example 49
Project: media_information_service   File: MongoDBInterface.java   Source Code and License 5 votes vote down vote up
private static void connect(String URI){
    //Change MongoDB's logger settings
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    rootLogger = loggerContext.getLogger("org.mongodb.driver");
    rootLogger.setLevel(Level.INFO);

    //Setup Connection
    MongoClientURI connectionString = new MongoClientURI(URI);
    MongoClient mongoClient = new MongoClient(connectionString);
    MongoDatabase database = mongoClient.getDatabase("media_information_service_db");
    collection = database.getCollection("messages");

}
 
Example 50
Project: cas-server-4.2.1   File: MongoAuthenticationHandler.java   Source Code and License 5 votes vote down vote up
@Override
protected Authenticator getAuthenticator(final Credential credential) {
    final MongoClientURI uri = new MongoClientURI(this.mongoHostUri);
    final MongoClient client = new MongoClient(uri);
    LOGGER.info("Connected to MongoDb instance @ {} using database [{}]",
            uri.getHosts(), uri.getDatabase());

    final MongoAuthenticator mongoAuthenticator = new MongoAuthenticator(client, this.attributes);
    mongoAuthenticator.setUsersCollection(this.collectionName);
    mongoAuthenticator.setUsersDatabase(uri.getDatabase());
    mongoAuthenticator.setUsernameAttribute(this.usernameAttribute);
    mongoAuthenticator.setPasswordAttribute(this.passwordAttribute);
    mongoAuthenticator.setPasswordEncoder(this.mongoPasswordEncoder);
    return mongoAuthenticator;
}
 
Example 51
Project: polymorphia   File: NoDiscriminatorForPolymorphicLeafClassesTest.java   Source Code and License 5 votes vote down vote up
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder()
                            .register(NoDiscriminatorForPolymorphicLeafClassesTest.class)
                            .build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
 
Example 52
Project: sample-acmegifts   File: MongoAccess.java   Source Code and License 5 votes vote down vote up
/** Get a connection to Mongo. */
public synchronized DB getMongoDB() {
  if (database == null) {
    try {
      MongoClient client = new MongoClient(mongoHostname, mongoPort);
      database = client.getDB("gifts-user");
    } catch (UnknownHostException uhe) {
      throw new RuntimeException(uhe);
    }
  }

  return database;
}
 
Example 53
Project: digital-display-garden-iteration-2-spraguesanborn   File: ExcelParser.java   Source Code and License 5 votes vote down vote up
private static void createBeds(String[][] plants) {
    String[] keys = getKeys(plants);
    int bedCol = 1;
    for (int i = 0; i < keys.length; i++){
        if (keys[i].equals("gardenLocation")){
            bedCol = i;
            break;
        }
    }

    MongoClient mongoClient = new MongoClient();
    MongoDatabase ddg = mongoClient.getDatabase("ddg");
    MongoCollection beds = ddg.getCollection("beds");
    beds.drop();

    for (int i = 4; i < plants.length; i++){
        String currentBed = plants[i][bedCol];

        Bson filter = new Document("gardenLocation", currentBed);


        if (beds.count(filter) == 0 && !currentBed.equals("")) {
            Document doc = new Document("gardenLocation", currentBed);

            beds.insertOne(doc);
        }
    }
}
 
Example 54
Project: sample-acmegifts   File: MongoAccess.java   Source Code and License 5 votes vote down vote up
/** Get a connection to Mongo */
public synchronized DB getMongoDB() {
  if (database == null) {
    try {
      MongoClient client = new MongoClient(mongoHostname, mongoPort);
      database = client.getDB("gifts-occasion");
    } catch (UnknownHostException uhe) {
      throw new RuntimeException(uhe);
    }
  }

  return database;
}
 
Example 55
Project: sample-acmegifts   File: OccasionResourceTest.java   Source Code and License 5 votes vote down vote up
/** Connect to the Occasions database and set the collection */
@BeforeClass
public static void beforeClass() throws UnknownHostException {
  String method = "beforeClass";
  logger.entering(clazz, method);
  mongoClient = new MongoClient(mongoHostname, mongoPort);
  db = mongoClient.getDB("gifts-occasion");
  collection = db.getCollection("occasions");
  logger.exiting(clazz, method);
}
 
Example 56
Project: sample-acmegifts   File: MongoAccess.java   Source Code and License 5 votes vote down vote up
/** Get a connection to Mongo */
public synchronized DB getMongoDB() {
  if (database == null) {
    try {
      MongoClient client = new MongoClient(mongoHostname, mongoPort);
      database = client.getDB("gifts-group");
    } catch (UnknownHostException uhe) {
      throw new RuntimeException(uhe);
    }
  }

  return database;
}
 
Example 57
Project: sample-acmegifts   File: GroupResourceTest.java   Source Code and License 5 votes vote down vote up
/** Connect to the Mongo database "groups" */
@BeforeClass
public static void setup() throws UnknownHostException {
  int mongoPort = Integer.parseInt(System.getProperty("mongo.test.port"));
  String mongoHostname = System.getProperty("mongo.test.hostname");
  mongo = new MongoClient(mongoHostname, mongoPort);
  db = mongo.getDB("gifts-group");
}
 
Example 58
Project: MongoSyphon   File: MongoBulkWriter.java   Source Code and License 5 votes vote down vote up
public MongoBulkWriter(String URI, String namespace)
{
	logger = LoggerFactory.getLogger(MongoBulkWriter.class);
	logger.info("Connecting to " + URI );
	mongoClient = new MongoClient(new MongoClientURI(URI));
	String[] parts = namespace.split("\\.");
	db = mongoClient.getDatabase(parts[0]);
	collection = db.getCollection(parts[1]);
	
	ops = new ArrayList<WriteModel<Document>>();
}
 
Example 59
Project: mongo-trek   File: MongoTrek.java   Source Code and License 5 votes vote down vote up
/**
 * Create a new MongoTrek instance that will connect to the provided connection string.
 *
 * @param migrationsFile The YAML or JSON file containing your MongoDB migrations.
 * @param uri The Mongo instance connection string
 * @see [MongoDB Connection String](https://docs.mongodb.com/manual/reference/connection-string/)
 */
public MongoTrek(String migrationsFile, String uri) {
    this.migrationsFile = migrationsFile;
    MongoClientURI clientURI = new MongoClientURI(uri);
    this.mongo = new MongoClient(clientURI);
    this.database = this.mongo.getDatabase(clientURI.getDatabase());
    this.providedDatabase = false;
    this.schemaVersionCollection = DEFAULT_SCHEMA_VERSION_COLLECTION;
}
 
Example 60
Project: polymorphia   File: PolymorphicReflectionCodecTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testFieldNameLikeDiscriminatorKey() {
    PojoCodecProvider pojoCodecProvider = PojoCodecProvider.builder().
            register(Shape.class).
            register(ClassWithReservedFieldName.class).
            build();

    assertNotNull(pojoCodecProvider);
    CodecRegistry pojoCodecRegistry = fromRegistries(fromProviders(pojoCodecProvider), MongoClient.getDefaultCodecRegistry());
    MongoCollection<Shape> documents = mongoClient.getDatabase(DB_NAME)
            .getCollection("documents")
            .withCodecRegistry(pojoCodecRegistry)
            .withDocumentClass(Shape.class);
    documents.insertOne(new ClassWithReservedFieldName());
}