com.mongodb.MongoClient Java Examples

The following examples show how to use com.mongodb.MongoClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Main.java    From elepy with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    MongoServer mongoServer = new MongoServer(new MemoryBackend());

    InetSocketAddress serverAddress = mongoServer.bind();

    MongoClient client = new MongoClient(new ServerAddress(serverAddress));

    final var elepyInstance = new Elepy()
            .addConfiguration(MongoConfiguration.of(client, "example", "bucket"))
            .withPort(7331)
            .addModelPackage("com.elepy.tests.devfrontend")
            .addExtension((http, elepy) -> {
                http.before(context -> {
                    context.response().header("Access-Control-Allow-Headers", "*");
                    context.request().addPermissions(Permissions.SUPER_USER);
                });
            })
            .addExtension(new FrontendLoader());
    elepyInstance.start();

}
 
Example #2
Source File: MongoDbIO.java    From beam with Apache License 2.0 6 votes vote down vote up
/**
 * Returns number of Documents in a collection.
 *
 * @return Positive number of Documents in a collection or -1 on error.
 */
long getDocumentCount() {
  try (MongoClient mongoClient =
      new MongoClient(
          new MongoClientURI(
              spec.uri(),
              getOptions(
                  spec.maxConnectionIdleTime(),
                  spec.sslEnabled(),
                  spec.sslInvalidHostNameAllowed(),
                  spec.ignoreSSLCertificate())))) {
    return getDocumentCount(mongoClient, spec.database(), spec.collection());
  } catch (Exception e) {
    return -1;
  }
}
 
Example #3
Source File: ChangeEntryDaoTest.java    From mongobee with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotCreateChangeIdAuthorIndexIfFound() throws MongobeeConfigurationException {

  // given
  MongoClient mongoClient = mock(MongoClient.class);
  MongoDatabase db = new Fongo(TEST_SERVER).getDatabase(DB_NAME);
  when(mongoClient.getDatabase(anyString())).thenReturn(db);

  ChangeEntryDao dao = new ChangeEntryDao(CHANGELOG_COLLECTION_NAME, LOCK_COLLECTION_NAME, WAIT_FOR_LOCK,
      CHANGE_LOG_LOCK_WAIT_TIME, CHANGE_LOG_LOCK_POLL_RATE, THROW_EXCEPTION_IF_CANNOT_OBTAIN_LOCK);
  ChangeEntryIndexDao indexDaoMock = mock(ChangeEntryIndexDao.class);
  when(indexDaoMock.findRequiredChangeAndAuthorIndex(db)).thenReturn(new Document());
  when(indexDaoMock.isUnique(any(Document.class))).thenReturn(true);
  dao.setIndexDao(indexDaoMock);

  // when
  dao.connectMongoDb(mongoClient, DB_NAME);

  //then
  verify(indexDaoMock, times(0)).createRequiredUniqueIndex(db.getCollection(CHANGELOG_COLLECTION_NAME));
  // and not
  verify(indexDaoMock, times(0)).dropIndex(db.getCollection(CHANGELOG_COLLECTION_NAME), new Document());
}
 
Example #4
Source File: EditPersonServlet.java    From journaldev with MIT License 6 votes vote down vote up
protected void doGet(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	String id = request.getParameter("id");
	if (id == null || "".equals(id)) {
		throw new ServletException("id missing for edit operation");
	}
	System.out.println("Person edit requested with id=" + id);
	MongoClient mongo = (MongoClient) request.getServletContext()
			.getAttribute("MONGO_CLIENT");
	MongoDBPersonDAO personDAO = new MongoDBPersonDAO(mongo);
	Person p = new Person();
	p.setId(id);
	p = personDAO.readPerson(p);
	request.setAttribute("person", p);
	List<Person> persons = personDAO.readAllPerson();
	request.setAttribute("persons", persons);

	RequestDispatcher rd = getServletContext().getRequestDispatcher(
			"/persons.jsp");
	rd.forward(request, response);
}
 
Example #5
Source File: MongoDB.java    From jelectrum with MIT License 6 votes vote down vote up
public MongoDB(Config config)
  throws Exception
{
  super(config);

  conf.require("mongo_db_host");
  conf.require("mongo_db_name");
  conf.require("mongo_db_connections_per_host");

  MongoClientOptions.Builder opts = MongoClientOptions.builder();
  opts.connectionsPerHost(conf.getInt("mongo_db_connections_per_host"));
  opts.threadsAllowedToBlockForConnectionMultiplier(100);
  opts.socketTimeout(3600000);


  mc = new MongoClient(new ServerAddress(conf.get("mongo_db_host")), opts.build());

  db = mc.getDB(conf.get("mongo_db_name"));


  open();
}
 
Example #6
Source File: MongoLogBenchmark.java    From tomcat-mongo-access-log with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUpValve(Tomcat tomcat) throws UnknownHostException {
  // remove AccessLogValve
  for (Valve vl : tomcat.getHost().getPipeline().getValves()) {
    if (vl.getClass().equals(AccessLogValve.class)) {
      tomcat.getHost().getPipeline().removeValve(vl);
    }
  }
  
  mongoClient = new MongoClient(new MongoClientURI(url));
  db = mongoClient.getDB(dbName);
  
  MongoAccessLogValve mavl = new MongoAccessLogValve();
  mavl.setUri(url);
  mavl.setDbName(dbName);
  mavl.setCollName(collName);
  mavl.setPattern(pattern);
  
  tomcat.getHost().getPipeline().addValve(mavl);
}
 
Example #7
Source File: ProfileActivity.java    From medical-data-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Integer doInBackground(User... params) {
    try {
        MongoClientURI mongoClientURI = new MongoClientURI(Variables.mongo_uri);
        MongoClient mongoClient = new MongoClient(mongoClientURI);
        MongoDatabase dbMongo = mongoClient.getDatabase(mongoClientURI.getDatabase());
        MongoCollection<Document> coll = dbMongo.getCollection("users");
        User local_user = params[0];
        if (!local_user.getEmail().equals(original_email)) {
            Document user = coll.find(eq("email", local_user.getEmail())).first();
            if (user != null) {
                return 1; // Repeated email
            }
        }

        Document search = new Document("_id", new ObjectId(local_user.getId()));
        Document replacement = new Document("$set", local_user.getRegisterDocument());
        // We update some fields of the documents without affecting the rest
        coll.updateOne(search, replacement);
        mongoClient.close();
        return 0; //Successfully saved
    } catch (Exception e) {
        return 2; // Error
    }
}
 
Example #8
Source File: BeihuMongoDataAutoConfiguration.java    From beihu-boot with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(MongoDbFactory.class)
public MongoDbFactorySupport<?> mongoDbFactory(ObjectProvider<MongoClient> mongo,
		ObjectProvider<com.mongodb.client.MongoClient> mongoClient) {
	MongoClient preferredClient = mongo.getIfAvailable();
	if (preferredClient != null) {
		return new SimpleMongoDbFactory(preferredClient,
				this.beihuMongoProperties.getMongoClientDatabase());
	}
	com.mongodb.client.MongoClient fallbackClient = mongoClient.getIfAvailable();
	if (fallbackClient != null) {
		return new SimpleMongoClientDbFactory(fallbackClient,
				this.beihuMongoProperties.getMongoClientDatabase());
	}
	throw new IllegalStateException("Expected to find at least one MongoDB client.");
}
 
Example #9
Source File: Main.java    From sql-to-mongo-db-query-converter with Apache License 2.0 6 votes vote down vote up
private static MongoClient getMongoClient(String[] hosts, String authdb, String username, String password) {
    final Pattern hostAndPort = Pattern.compile("^(.[^:]*){1}([:]){0,1}(\\d+){0,1}$");
    List<ServerAddress> serverAddresses = Lists.transform(Arrays.asList(hosts), new Function<String, ServerAddress>() {
        @Override
        public ServerAddress apply(@Nonnull String string) {
            Matcher matcher = hostAndPort.matcher(string.trim());
            if (matcher.matches()) {
                String hostname = matcher.group(1);
                String port = matcher.group(3);
                return new ServerAddress(hostname,port!=null ? Integer.parseInt(port) : Integer.parseInt(DEFAULT_MONGO_PORT));

            } else {
                throw new IllegalArgumentException(string + " doesn't appear to be a hostname.");
            }
        }
    });
    if (username!=null && password!=null) {
        return new MongoClient(serverAddresses,Arrays.asList(MongoCredential.createCredential(username,authdb,password.toCharArray())));
    } else {
        return new MongoClient(serverAddresses);
    }
}
 
Example #10
Source File: ChangeEntryDaoTest.java    From mongobee with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReleaseLockFromLockDao() throws Exception {

  // given
  MongoClient mongoClient = mock(MongoClient.class);
  MongoDatabase db = new Fongo(TEST_SERVER).getDatabase(DB_NAME);
  when(mongoClient.getDatabase(anyString())).thenReturn(db);

  ChangeEntryDao dao = new ChangeEntryDao(CHANGELOG_COLLECTION_NAME, LOCK_COLLECTION_NAME, WAIT_FOR_LOCK,
      CHANGE_LOG_LOCK_WAIT_TIME, CHANGE_LOG_LOCK_POLL_RATE, THROW_EXCEPTION_IF_CANNOT_OBTAIN_LOCK);

  LockDao lockDao = mock(LockDao.class);
  dao.setLockDao(lockDao);

  dao.connectMongoDb(mongoClient, DB_NAME);

  // when
  dao.releaseProcessLock();

  // then
  verify(lockDao).releaseLock(any(MongoDatabase.class));
}
 
Example #11
Source File: BsonToJsonLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() {

    String json = null;
    try (MongoClient mongoClient = new MongoClient()) {
        MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
        Document bson = mongoDatabase.getCollection("Books").find().first();
        json = bson.toJson(JsonWriterSettings
            .builder()
            .dateTimeConverter(new JsonDateTimeConverter())
            .build());
    }

    String expectedJson = "{\"_id\": \"isbn\", " + 
        "\"className\": \"com.baeldung.bsontojson.Book\", " + 
        "\"title\": \"title\", " + 
        "\"author\": \"author\", " + 
        "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + 
        "\"name\": \"publisher\"}, " + 
        "\"price\": 3.95, " + 
        "\"publishDate\": \"2020-01-01T17:13:32Z\"}";

    assertEquals(expectedJson, json);

}
 
Example #12
Source File: ChangeEntryDaoTest.java    From mongobee with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInitiateLock() throws MongobeeConfigurationException {

  // given
  MongoClient mongoClient = mock(MongoClient.class);
  MongoDatabase db = new Fongo(TEST_SERVER).getDatabase(DB_NAME);
  when(mongoClient.getDatabase(anyString())).thenReturn(db);

  ChangeEntryDao dao = new ChangeEntryDao(CHANGELOG_COLLECTION_NAME, LOCK_COLLECTION_NAME, WAIT_FOR_LOCK,
      CHANGE_LOG_LOCK_WAIT_TIME, CHANGE_LOG_LOCK_POLL_RATE, THROW_EXCEPTION_IF_CANNOT_OBTAIN_LOCK);
  ChangeEntryIndexDao indexDaoMock = mock(ChangeEntryIndexDao.class);
  dao.setIndexDao(indexDaoMock);

  LockDao lockDao = mock(LockDao.class);
  dao.setLockDao(lockDao);

  // when
  dao.connectMongoDb(mongoClient, DB_NAME);

  // then
  verify(lockDao).intitializeLock(db);

}
 
Example #13
Source File: PersistenceManager.java    From clouditor with Apache License 2.0 6 votes vote down vote up
private PersistenceManager() {
  var factory = new BsonFactory();

  var module = new SimpleModule();
  // the default Jackson Java 8 time (de)serializer are not compatible with MongoDB
  module.addSerializer(Instant.class, new BsonInstantSerializer());
  module.addDeserializer(Instant.class, new BsonInstantDeserializer());

  var mapper = new ObjectMapper(factory);
  ObjectMapperResolver.configureObjectMapper(mapper);

  mapper.registerModule(module);

  this.codecRegistry =
      CodecRegistries.fromRegistries(
          MongoClient.getDefaultCodecRegistry(), fromProviders(new JacksonCodecProvider(mapper)));
}
 
Example #14
Source File: MongoDBSourceIT.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private void insertDocsWithDateField(String collectionName) throws Exception
{
  MongoClient mongo = new MongoClient(mongoContainerIp, mongoContainerMappedPort);
  MongoDatabase db = mongo.getDatabase(DATABASE_NAME);

  MongoCollection<Document> collection = db.getCollection(collectionName);
  collection.insertOne(new Document("date", dateFormatter.parse("2015-06-01 00:00:00")));
  collection.insertOne(new Document("date", dateFormatter.parse("2015-06-02 00:00:00")));
  collection.insertOne(new Document("date", dateFormatter.parse("2015-06-03 00:00:00")));

  mongo.close();
}
 
Example #15
Source File: DataStoreProvider.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
public static Datastore getDataStore(Config config) {

        String[] addresses = config.getParameter(ExtConfig.MONGO_ADDRESSES, new String[]{"127.0.0.1:27017"});
        String database = config.getParameter(ExtConfig.MONGO_DATABASE, "lts");
        String username = config.getParameter(ExtConfig.MONGO_USERNAME);
        String pwd = config.getParameter(ExtConfig.MONGO_PASSWORD);

        String cachedKey = StringUtils.concat(StringUtils.concat(addresses), database, username, pwd);

        Datastore datastore = DATA_STORE_MAP.get(cachedKey);
        if (datastore == null) {
            try {
                synchronized (lock) {
                    datastore = DATA_STORE_MAP.get(cachedKey);
                    if (datastore != null) {
                        return datastore;
                    }
                    Morphia morphia = new Morphia();
                    MongoFactoryBean mongoFactoryBean = new MongoFactoryBean(addresses, username, database, pwd);
                    MongoClient mongo = mongoFactoryBean.createInstance();
                    datastore = morphia.createDatastore(mongo, database);
                    DATA_STORE_MAP.put(cachedKey, datastore);
                }
            } catch (Exception e) {
                throw new IllegalStateException(
                        StringUtils.format("connect mongo failed! addresses: {}, database: {}",
                                addresses, database), e);
            }
        }
        return datastore;
    }
 
Example #16
Source File: MongoReader.java    From deep-spark with Apache License 2.0 5 votes vote down vote up
/**
 * Init void.
 *
 * @param partition the partition
 */
public void init(Partition partition) {
    try {

        List<ServerAddress> addressList = new ArrayList<>();

        for (String s : (List<String>) ((DeepPartition) partition).splitWrapper().getReplicas()) {
            addressList.add(new ServerAddress(s));
        }

        //Credentials
        List<MongoCredential> mongoCredentials = new ArrayList<>();

        if (mongoDeepJobConfig.getUsername() != null && mongoDeepJobConfig.getPassword() != null) {
            MongoCredential credential = MongoCredential.createMongoCRCredential(mongoDeepJobConfig.getUsername(),
                    mongoDeepJobConfig.getDatabase(),
                    mongoDeepJobConfig.getPassword().toCharArray());
            mongoCredentials.add(credential);

        }

        mongoClient = new MongoClient(addressList, mongoCredentials);
        mongoClient.setReadPreference(ReadPreference.valueOf(mongoDeepJobConfig.getReadPreference()));
        db = mongoClient.getDB(mongoDeepJobConfig.getDatabase());
        collection = db.getCollection(mongoDeepJobConfig.getCollection());

        dbCursor = collection.find(generateFilterQuery((MongoPartition) partition),
                mongoDeepJobConfig.getDBFields());

    } catch (UnknownHostException e) {
        throw new DeepExtractorInitializationException(e);
    }
}
 
Example #17
Source File: MongoDBFactory.java    From database-transform-tool with Apache License 2.0 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 #18
Source File: TransformationQueryTestInternal.java    From epcis with Apache License 2.0 5 votes vote down vote up
public void test() throws IOException, InterruptedException {

		File file = new File(fileBaseLoc + this.getClass().getSimpleName() + "-cache-bfs");
		file.createNewFile();
		FileWriter fw = new FileWriter(file);
		BufferedWriter bw = new BufferedWriter(fw);

		String baseEPC = "urn:epc:id:sgtin:0000001.000001.";

		MongoClient client = new MongoClient();
		MongoDatabase db = client.getDatabase("test1");
		db.getCollection("edges").drop();
		db.getCollection("vertices").drop();
		db.getCollection("edges").createIndex(new BsonDocument("_outV", new BsonInt32(1))
				.append("_label", new BsonInt32(1)).append("_t", new BsonInt32(1)).append("_inV", new BsonInt32(1)));
		client.close();

		ChronoGraph g = new ChronoGraph("test1");

		for (int i = 0; i < transferCount; i++) {

			long cTime = System.currentTimeMillis();
			g.addTimestampEdgeProperties(baseEPC + i, baseEPC + (2 * i + 1), "transformTo", cTime, new BsonDocument());
			g.addTimestampEdgeProperties(baseEPC + i, baseEPC + (2 * i + 2), "transformTo", cTime, new BsonDocument());

			Thread.sleep(2000);

			double avg = doTransformationQuery(g);

			System.out.println(i + "\t" + avg);
			bw.write(i + "\t" + avg + "\n");
			bw.flush();
		}
		bw.close();
	}
 
Example #19
Source File: MongoMasterConnector.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private MongoCursor<Document> getReplicaCursor(MongoClient client, Document query) {
  MongoDatabase db = client.getDatabase(LOCAL);
  MongoCollection<Document> coll = db.getCollection(OPLOG_RS);

  return coll.find(query)
      .cursorType(CursorType.TailableAwait)
      .oplogReplay(true)
      .iterator();
}
 
Example #20
Source File: MongoSinkUpdateInsteadReplaceTest.java    From ingestion with Apache License 2.0 5 votes vote down vote up
private void injectFongo(MongoSink mongoSink) {
    try {
        MongoClient mongoClient = fongo.getMongo();
        DB mongoDefaultDb = mongoClient.getDB("test");
        DBCollection mongoDefaultCollection = mongoDefaultDb.getCollection("test");
        setField(mongoSink, "mongoClient", mongoClient);
        setField(mongoSink, "mongoDefaultDb", mongoDefaultDb);
        setField(mongoSink, "mongoDefaultCollection", mongoDefaultCollection);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #21
Source File: MongoClientDecoratorTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Before
public void prepareTest() throws Exception {
    whenNew(ConfigurationRegistry.class).withAnyArguments().thenReturn(configRegistry);
    whenNew(MongoClient.class).withAnyArguments().thenReturn(mongoClient);

    when(ctx.getData(eq(Constants.KEY_MONGO_CLIENT))).thenReturn(mongoClient);
    when(configRegistry.getConfiguration(any(PersistenceUnitDescriptor.class))).thenReturn(configuration);
    when(invocation.getContext()).thenReturn(ctx);

    decorator = new MongoClientDecorator();
}
 
Example #22
Source File: CustomMongoHealthIndicator.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
static Cluster getCluster(MongoClient mongoClient) {
    try {
        Method privateMethod = Mongo.class.getDeclaredMethod("getCluster", null);
        privateMethod.setAccessible(true);
        return (Cluster) privateMethod.invoke(mongoClient);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}
 
Example #23
Source File: ExecutionApp.java    From android-kubernetes-blockchain with Apache License 2.0 5 votes vote down vote up
private static void enrollUsers(int number) {
	MongoClient mongo = getConnection();
	if (mongo == null) {
		System.exit(0);
	}
	for (int i = 0; i < number; i++) {
		count++;
		// executorService.execute(new
		// ExecutionTask("type=enroll&queue=user_queue&params={}",
		// executionURL, dbName));
		executeRequest("type=enroll&queue=user_queue&params={}", mongo);
	}
	closeConnection(mongo);
}
 
Example #24
Source File: StatementStoreFactory.java    From rya with Apache License 2.0 5 votes vote down vote up
private MongoRyaStatementStore getBaseMongoStore(final String hostname, final int port, final String ryaInstanceName) throws RyaDAOException {
    final MongoClient client = new MongoClient(hostname, port);
    final MongoDBRyaDAO dao = new MongoDBRyaDAO();
    dao.setConf(new StatefulMongoDBRdfConfiguration(MergeConfigHadoopAdapter.getMongoConfiguration(configuration), client));
    dao.init();
    return new MongoRyaStatementStore(client, ryaInstanceName, dao);
}
 
Example #25
Source File: MongoExtension.java    From jphp with Apache License 2.0 5 votes vote down vote up
@Override
public void onRegister(CompileScope scope) {
    MemoryOperation.register(new BasicDBObjectMemoryOperation());
    MemoryOperation.register(new DocumentMemoryOperation());
    MemoryOperation.register(new IndexOptionsMemoryOperation());
    MemoryOperation.register(new CountOptionsMemoryOperation());
    MemoryOperation.register(new ObjectIdMemoryOperation());

    registerWrapperClass(scope, ObjectId.class, WrapObjectId.class);
    registerWrapperClass(scope, MongoIterable.class, WrapMongoIterable.class);
    registerWrapperClass(scope, MongoCollection.class, WrapMongoCollection.class);
    registerWrapperClass(scope, MongoDatabase.class, WrapMongoDatabase.class);
    registerWrapperClass(scope, MongoClient.class, WrapMongoClient.class);
    // register classes ...
}
 
Example #26
Source File: MongoDBDriver.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private static ConcurrentMap<ServerNodeKey, MongoClient> getMongoServerNodes()
{
    // different from Mongo.Holder (which uses MongoURI as key), 
    // this uses cached key based on a
    // MongoURI plus supported options not definable in MongoURI
    if( sm_mongoServerNodes == null )
    {
        synchronized( MongoDBDriver.class )
        {
            if( sm_mongoServerNodes == null )
                sm_mongoServerNodes = new ConcurrentHashMap<ServerNodeKey, MongoClient>();
        }
    }
    return sm_mongoServerNodes;
}
 
Example #27
Source File: DeviceManagerController.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public DeviceManagerController() {
	contextBrokerAddress = "http://" + HeritProperties.getProperty("Globals.fiwareServerHost") + ":" + HeritProperties.getProperty("Globals.fiwareServerPort");
	fiwareService = HeritProperties.getProperty("Globals.fiwareService");
	fiwareServicePath = HeritProperties.getProperty("Globals.fiwareServicePath");
	fiwareAgentAccessKey = HeritProperties.getProperty("Globals.fiwareAgentAccessKey");
	fiwareAgentUrl = HeritProperties.getProperty("Globals.fiwareAgentUrl");
	
	// added in 2017-09-18
	mongoClient = new MongoClient(HeritProperties.getProperty("Globals.MongoDB.Host"), Integer.parseInt( HeritProperties.getProperty("Globals.MongoDB.Port") ) );
	//db = mongoClient.getDatabase(HeritProperties.getProperty("Globals.MongoDB.DBName"));
	db = mongoClient.getDB(HeritProperties.getProperty("Globals.MongoDB.DBName"));

	
}
 
Example #28
Source File: MongoDbDataProviderEngine.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
private MongoCollection<Document> getCollection(N2oMongoDbDataProvider invocation) {
    String connUrl = invocation.getConnectionUrl() != null ? invocation.getConnectionUrl() : connectionUrl;
    String dbName = invocation.getDatabaseName() != null ? invocation.getDatabaseName() : databaseName;

    if (connUrl == null)
        throw new N2oException("Need to define n2o.engine.mongodb.connection_url property");

    mongoClient = new MongoClient(new MongoClientURI(connUrl));

    return mongoClient
            .getDatabase(dbName)
            .getCollection(invocation.getCollectionName());
}
 
Example #29
Source File: MDbConnection.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private static Boolean existsDatabase( MongoClient mongoClient,
           String dbName, Properties connProps ) 
       throws OdaException
   {
       if ( dbName == null )
	{
		return false;
	}
	try
	{
		MongoIterable<String> databaseNameIterable = mongoClient
				.listDatabaseNames( );
		for ( String databaseName : databaseNameIterable )
		{
			if ( dbName.equals( databaseName ) )
			{
				return true;
			}
		}
		return false;
	}
	catch ( MongoException ex )
	{
		MongoDBDriver.getLogger( ).log( Level.SEVERE,
				"Unable to connect host",
				ex ); // unable
						// to
						// get
						// db
						// names
		// user may not have permission for listDatabaseName, return true,
		// let the getDatabase() handle it.
		throw new OdaException( ex );
	}
}
 
Example #30
Source File: KyMongoConfig.java    From ClusterDeviceControlPlatform with MIT License 5 votes vote down vote up
@Bean
public com.mongodb.reactivestreams.client.MongoClient reactiveMongoClient() {
    if (DbSetting.AUTHENTICATION_STATUS) {
        return MongoClients.create("mongodb://" + DbSetting.DATABASE_USERNAME + ":" + DbSetting.DATABASE_PASSWORD + "@" + DbSetting.MONGODB_HOST + ":" + DbSetting.MONGODB_PORT + "/" + DbSetting.DATABASE);
    } else {
        return MongoClients.create("mongodb://" + DbSetting.MONGODB_HOST + ":" + DbSetting.MONGODB_PORT);
    }
}