下面列出了怎么用com.mongodb.MongoClient的API类实例代码及写法,或者点击链接到github查看源代码。
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)));
}
@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.");
}
@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
}
}
@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);
}
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);
}
@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());
}
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);
}
}
@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));
}
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();
}
/**
* 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;
}
}
@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);
}
@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);
}
@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);
}
}
public MongoClient build() {
MongoClientOptions.Builder options = MongoClientOptions.builder();
options.connectionsPerHost(connections);
options.threadsAllowedToBlockForConnectionMultiplier(
(int) Math.ceil((double) MAX_DB_REQUEST_CONCURRENCY / connections));
return new MongoClient(new ServerAddress(host, port), options.build());
}
@Bean
@ConditionalOnMissingBean(type = { "com.mongodb.MongoClient",
"com.mongodb.client.MongoClient" })
public MongoClient mongo() {
this.mongo = this.factory.createMongoClient(this.options);
return this.mongo;
}
@Test
void shouldNotConfigureCompressorListWhenClientServerCompressionIsDisabled() {
//given
final MongoProperties props = new MongoProperties();
//when
props.setClientServerCompressionEnabled(false);
MongoClientOptions mongoClientOptions = props.toMongoClientOptions(MongoClient.getDefaultCodecRegistry(), Collections.singletonList(MongoCompressor.createZlibCompressor()));
//then
assertThat(mongoClientOptions.getCompressorList(), is(Collections.emptyList()));
}
@Activate
public void activate(ComponentContext componentContext) {
config = componentContext.getProperties();
String uri = getValue(config, URI_PROPERTY, URI_DEFAULT);
String database = getValue(config, DATABASE_PROPERTY, DATABASE_DEFAULT);
String collection = getValue(config, COLLECTION_PROPERTY, COLLECTION_DEFAULT);
mongoClient = new MongoClient(new MongoClientURI(uri));
mongoDatabase = mongoClient.getDatabase(database);
mongoCollection = mongoDatabase.getCollection(collection);
}
@Test
void shouldConfigureCompressorListWhenClientServerCompressionIsEnabled() {
//given
final MongoProperties props = new MongoProperties();
//when
props.setClientServerCompressionEnabled(true);
MongoClientOptions mongoClientOptions = props.toMongoClientOptions(MongoClient.getDefaultCodecRegistry(), Collections.singletonList(MongoCompressor.createZlibCompressor()));
//then
assertThat(mongoClientOptions.getCompressorList(), is(Collections.singletonList(MongoCompressor.createZlibCompressor())));
}
@BeforeEach
void setup() {
registry = new SimpleMeterRegistry();
clusterId = new AtomicReference<>();
MongoClientOptions options = MongoClientOptions.builder()
.addCommandListener(new MongoMetricsCommandListener(registry))
.addClusterListener(new ClusterListenerAdapter() {
@Override
public void clusterOpening(ClusterOpeningEvent event) {
clusterId.set(event.getClusterId().getValue());
}
}).build();
mongo = new MongoClient(new ServerAddress(HOST, port), options);
}
private void initializeReplicaSet(final List<IMongodConfig> mongodConfigList) throws UnknownHostException, InterruptedException {
Thread.sleep(1000);
final MongoClientOptions mo = MongoClientOptions.builder().connectTimeout(10).build();
final ServerAddress arbitrerAddress = new ServerAddress(mongodConfigList.get(0).net().getServerAddress().getHostName(),
mongodConfigList.get(0).net().getPort());
try (MongoClient mongo = new MongoClient(arbitrerAddress, mo)) {
final MongoDatabase mongoAdminDB = mongo.getDatabase("admin");
Document cr = mongoAdminDB.runCommand(new Document("isMaster", 1));
LOGGER.info("isMaster: {}", cr);
// Build replica set configuration settings
final Document rsConfiguration = buildReplicaSetConfiguration(mongodConfigList);
LOGGER.info("replSetSettings: {}", rsConfiguration);
// Initialize replica set
cr = mongoAdminDB.runCommand(new Document("replSetInitiate", rsConfiguration));
LOGGER.info("replSetInitiate: {}", cr);
// Check replica set status before to proceed
int maxWaitRounds = 10;
do {
LOGGER.info("Waiting for 1 second...");
Thread.sleep(1000);
cr = mongoAdminDB.runCommand(new Document("replSetGetStatus", 1));
LOGGER.info("replSetGetStatus: {}", cr);
maxWaitRounds--;
} while (!isReplicaSetStarted(cr) || maxWaitRounds != 0);
if (!isReplicaSetStarted(cr) && maxWaitRounds == 0) {
throw new RuntimeException("Could not initialize replica set");
}
}
}
@BeforeClass
public static void setUp() {
Morphia morphia = new Morphia();
morphia.mapPackage("com.baeldung.morphia");
datastore = morphia.createDatastore(new MongoClient(), "library");
datastore.ensureIndexes();
}
/**
* Creates a new PCJ Table in Accumulo and populates it by scanning an
* instance of Rya for historic matches.
* <p>
* If any portion of this operation fails along the way, the partially
* create PCJ table will be left in Accumulo.
*
* @param ryaConn - Connects to the Rya that will be scanned. (not null)
* @param mongoClient - Connects to the mongoDB that hosts the PCJ results. (not null)
* @param pcjName - The name of the PCJ table that will be created. (not null)
* @param sparql - The SPARQL query whose results will be loaded into the table. (not null)
* @throws PcjException The PCJ table could not be create or the values from Rya were
* not able to be loaded into it.
*/
public static void createAndPopulatePcj(final RepositoryConnection ryaConn, final MongoClient mongoClient, final String pcjName, final String instanceName, final String sparql) throws PcjException {
checkNotNull(ryaConn);
checkNotNull(mongoClient);
checkNotNull(pcjName);
checkNotNull(instanceName);
checkNotNull(sparql);
final MongoPcjDocuments pcj = new MongoPcjDocuments(mongoClient, instanceName);
pcj.createPcj(pcjName, sparql);
// Load historic matches from Rya into the PCJ table.
populatePcj(pcj, pcjName, ryaConn);
}
private void loadMongoClient(String id) {
String uri = MongoConf.getConf(id, MongoClientConf.P_uri, "");
if ("".equals(uri)) {
LOG.warn("Not found {}'s uri", id);
return;
}
MongoClient mongoClient = new MongoClient(new MongoClientURI(uri));
clients.put(id, mongoClient);
}
/** 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");
}
public MongoService(String host, String dbName) {
try {
mFS = new GridFS(mDB = new MongoClient(host).getDB(dbName));
System.out.println(JSON.serialize(getCollectionNames()));
System.out.println(System.getProperty("user.dir"));
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
/**
* Builds a Mongo {@code DB} object from connection and db info set in a configuration file.
* @param env The dropwizard environment.
* @return A Mongo Java API {@code DB} object.
* @throws {@link UnknownHostException} Thrown if the server can not be found.
* @throws {@link com.eeb.dropwizardmongo.exceptions.NullDBNameException} Throw in the db name is null.
*/
public DB buildDB(Environment env) throws UnknownHostException, NullDBNameException {
if(this.dbName == null)
throw new NullDBNameException();
final MongoClient client = buildClient(env);
return client.getDB(this.dbName);
}
public boolean ping() {
MongoClient client = fastClient();
DBObject command = new BasicDBObject("ping", "1");
final DB db = client.getDB("admin");
try {
CommandResult status = db.command(command);
return status.ok();
} catch (MongoException e) {
LOG.warn("Pinging server {} failed with {}", address.getHost(), e);
} finally {
client.close();
}
return false;
}
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;
}
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 );
}
}
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());
}