Java Code Examples for com.mongodb.MongoClient
The following examples show how to use
com.mongodb.MongoClient. These examples are extracted from open source projects.
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 Project: clouditor Source File: PersistenceManager.java License: Apache License 2.0 | 6 votes |
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 2
Source Project: beihu-boot Source File: BeihuMongoDataAutoConfiguration.java License: Apache License 2.0 | 6 votes |
@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 3
Source Project: medical-data-android Source File: ProfileActivity.java License: GNU General Public License v3.0 | 6 votes |
@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 4
Source Project: tomcat-mongo-access-log Source File: MongoLogBenchmark.java License: Apache License 2.0 | 6 votes |
@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 5
Source Project: journaldev Source File: EditPersonServlet.java License: MIT License | 6 votes |
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 6
Source Project: mongobee Source File: ChangeEntryDaoTest.java License: Apache License 2.0 | 6 votes |
@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 7
Source Project: sql-to-mongo-db-query-converter Source File: Main.java License: Apache License 2.0 | 6 votes |
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 8
Source Project: mongobee Source File: ChangeEntryDaoTest.java License: Apache License 2.0 | 6 votes |
@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 9
Source Project: elepy Source File: Main.java License: Apache License 2.0 | 6 votes |
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 10
Source Project: jelectrum Source File: MongoDB.java License: MIT License | 6 votes |
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 11
Source Project: beam Source File: MongoDbIO.java License: Apache License 2.0 | 6 votes |
/** * 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 12
Source Project: tutorials Source File: BsonToJsonLiveTest.java License: MIT License | 6 votes |
@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 13
Source Project: mongobee Source File: ChangeEntryDaoTest.java License: Apache License 2.0 | 6 votes |
@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 14
Source Project: ClusterDeviceControlPlatform Source File: KyMongoConfig.java License: MIT License | 5 votes |
@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); } }
Example 15
Source Project: FrameworkBenchmarks Source File: MongoClientFactory.java License: BSD 3-Clause "New" or "Revised" License | 5 votes |
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()); }
Example 16
Source Project: beihu-boot Source File: BeihuMongoAutoConfiguration.java License: Apache License 2.0 | 5 votes |
@Bean @ConditionalOnMissingBean(type = { "com.mongodb.MongoClient", "com.mongodb.client.MongoClient" }) public MongoClient mongo() { this.mongo = this.factory.createMongoClient(this.options); return this.mongo; }
Example 17
Source Project: edison-microservice Source File: MongoPropertiesTest.java License: Apache License 2.0 | 5 votes |
@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())); }
Example 18
Source Project: karaf-decanter Source File: MongoDbAppender.java License: Apache License 2.0 | 5 votes |
@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); }
Example 19
Source Project: edison-microservice Source File: MongoPropertiesTest.java License: Apache License 2.0 | 5 votes |
@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()))); }
Example 20
Source Project: micrometer Source File: MongoMetricsCommandListenerTest.java License: Apache License 2.0 | 5 votes |
@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); }
Example 21
Source Project: jpa-unit Source File: MongodManager.java License: Apache License 2.0 | 5 votes |
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"); } } }
Example 22
Source Project: tutorials Source File: MorphiaIntegrationTest.java License: MIT License | 5 votes |
@BeforeClass public static void setUp() { Morphia morphia = new Morphia(); morphia.mapPackage("com.baeldung.morphia"); datastore = morphia.createDatastore(new MongoClient(), "library"); datastore.ensureIndexes(); }
Example 23
Source Project: rya Source File: PcjIntegrationTestingUtil.java License: Apache License 2.0 | 5 votes |
/** * 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); }
Example 24
Source Project: jframe Source File: MongoClientServiceImpl.java License: Apache License 2.0 | 5 votes |
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); }
Example 25
Source Project: sample-acmegifts Source File: GroupResourceTest.java License: Eclipse Public License 1.0 | 5 votes |
/** 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 26
Source Project: BLELocalization Source File: MongoService.java License: MIT License | 5 votes |
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(); } }
Example 27
Source Project: dropwizard-mongo Source File: MongoFactory.java License: Apache License 2.0 | 5 votes |
/** * 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); }
Example 28
Source Project: brooklyn-library Source File: MongoDBClientSupport.java License: Apache License 2.0 | 5 votes |
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; }
Example 29
Source Project: light-task-scheduler Source File: DataStoreProvider.java License: Apache License 2.0 | 5 votes |
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 30
Source Project: birt Source File: MDbConnection.java License: Eclipse Public License 1.0 | 5 votes |
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 ); } }