Java 类com.mongodb.client.MongoIterable 实例源码
项目:database-transform-tool
文件:MongoDBFactory.java
/**
* @decription 查询数据库表名
* @author yi.zhang
* @time 2017年6月30日 下午2:16:02
* @param table 表名
* @return
*/
public List<String> queryTables(){
try {
if(session==null){
init(servers, database, schema, username, password);
}
MongoIterable<String> collection = session.listCollectionNames();
if (collection == null) {
return null;
}
List<String> tables = new ArrayList<String>();
MongoCursor<String> cursor = collection.iterator();
while(cursor.hasNext()){
String table = cursor.next();
tables.add(table);
}
return tables;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
项目:jpa-unit
文件:MongoDbFeatureExecutorTest.java
@SuppressWarnings("unchecked")
@Test
public void testVerifyDataAfterFeatureExecution() throws DbFeatureException {
// GIVEN
final MongoIterable<String> collectionIterable = mock(MongoIterable.class);
final MongoCursor<String> iterator = mock(MongoCursor.class);
when(expectedDataSets.strict()).thenReturn(Boolean.FALSE);
when(expectedDataSets.value()).thenReturn(new String[] {});
when(expectedDataSets.orderBy()).thenReturn(new String[] {});
when(expectedDataSets.excludeColumns()).thenReturn(new String[] {});
when(connection.listCollectionNames()).thenReturn(collectionIterable);
when(collectionIterable.iterator()).thenReturn(iterator);
when(iterator.hasNext()).thenReturn(Boolean.FALSE);
// WHEN
final DbFeature<MongoDatabase> feature = featureExecutor.createVerifyDataAfterFeature(expectedDataSets);
assertThat(feature, notNullValue());
feature.execute(connection);
// THEN
verify(connection).listCollectionNames();
verifyNoMoreInteractions(connection);
}
项目:para-dao-mongodb
文件:MongoDBUtils.java
/**
* Checks if the main table exists in the database.
* @param appid name of the {@link com.erudika.para.core.App}
* @return true if the table exists
*/
public static boolean existsTable(String appid) {
if (StringUtils.isBlank(appid)) {
return false;
}
try {
appid = getTableNameForAppid(appid);
MongoIterable<String> collectionNames = getClient().listCollectionNames();
for (final String name : collectionNames) {
if (name.equalsIgnoreCase(appid)) {
return true;
}
}
return false;
} catch (Exception e) {
return false;
}
}
项目:df_data_service
文件:MongoAdminClient.java
public boolean collectionExists(String collectionName) {
if (this.database == null) {
return false;
}
final MongoIterable<String> iterable = database.listCollectionNames();
try (final MongoCursor<String> it = iterable.iterator()) {
while (it.hasNext()) {
if (it.next().equalsIgnoreCase(collectionName)) {
return true;
}
}
}
return false;
}
项目:Mache
文件:MongoConnector.java
@Test
@IgnoreIf(condition = NoRunningMongoDbForTests.class)
public void connectsToTheCluster() throws Exception {
MongoClient mongoClient = new MongoClient(new NoRunningMongoDbForTests().getHost(), 27017);
MongoIterable<String> strings = mongoClient.listDatabaseNames();
MongoCursor<String> iterator = strings.iterator();
while (iterator.hasNext()) {
LOG.info("Database: {}", iterator.next());
}
MongoDatabase db = mongoClient.getDatabase(strings.iterator().next());
String name = db.getName();
LOG.info("Got: {}", name);
mongoClient.close();
}
项目:lumongo
文件:LumongoIndexManager.java
public List<String> getIndexNames() {
globalLock.writeLock().lock();
try {
ArrayList<String> indexNames = new ArrayList<>();
log.info("Searching database <" + mongoConfig.getDatabaseName() + "> for indexes");
MongoDatabase db = mongo.getDatabase(mongoConfig.getDatabaseName());
MongoIterable<String> allCollections = db.listCollectionNames();
for (String collection : allCollections) {
if (collection.endsWith(LumongoIndex.CONFIG_SUFFIX)) {
String indexName = collection.substring(0, collection.length() - LumongoIndex.CONFIG_SUFFIX.length());
indexNames.add(indexName);
}
}
return indexNames;
}
finally {
globalLock.writeLock().unlock();
}
}
项目:birt
文件:MDbOperation.java
private void applyPropertiesToCursor( MongoIterable<Document> mongoIterable, QueryProperties queryProps,
boolean includeMetaDataSearchLimit, boolean includeSortExpr )
{
if( includeMetaDataSearchLimit )
{
Integer searchLimit = getModel().getEffectiveMDSearchLimit( queryProps );
if( searchLimit > 0 )
{
// Apply to FindIterable or MapReduceIterable
if ( mongoIterable instanceof FindIterable )
{
FindIterable<Document> findIterable = (FindIterable<Document>) mongoIterable;
findIterable.limit( searchLimit.intValue( ) );
}
else if ( mongoIterable instanceof MapReduceIterable )
{
MapReduceIterable<Document> mapReduceIterable = (MapReduceIterable<Document>) mongoIterable;
mapReduceIterable.limit( searchLimit.intValue( ) );
}
}
}
applyPropertiesToCursor( mongoIterable, queryProps, includeSortExpr );
}
项目:alfresco-benchmark
文件:Mongo3Helper.java
/**
* Checks if the collection exists
*
* @param db
* (MongoDatabase, mandatory)
* @param collectionName
* (String, mandatory) name of the collection
*
* @return (boolean)
*/
public static boolean collectionExists(MongoDatabase db, String collectionName)
{
ArgumentCheck.checkMandatoryObject(db, "db");
ArgumentCheck.checkMandatoryString(collectionName, "collectionName");
MongoIterable<String> collectionNames = db.listCollectionNames();
for (final String name : collectionNames)
{
if (name.equalsIgnoreCase(collectionName))
{
return true;
}
}
return false;
}
项目:cereebro
文件:MongoDbRelationshipDetectorTest.java
@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;
}
项目:otus_java_2017_06
文件:MongoMain.java
private void listDatabaseNames() {
MongoIterable<String> dbs = mongoClient.listDatabaseNames();
System.out.println("\nDatabase names:");
for (String db : dbs) {
System.out.println(db);
}
}
项目:Saber-Bot
文件:EntryManager.java
/**
* Retrieves all entries associated with a guild
* @param guildId snowflake ID of guild
* @return all active entries
*/
public Collection<ScheduleEntry> getEntriesFromGuild(String guildId)
{
MongoIterable<ScheduleEntry> entries = Main.getDBDriver().getEventCollection()
.find(eq("guildId", guildId)).map(ScheduleEntry::new);
return entries.into(new ArrayList<>());
}
项目:Saber-Bot
文件:EntryManager.java
/**
* Retrieves all entries on a channel
* @param channelId snowflake ID of channel
* @return all active entries
*/
public Collection<ScheduleEntry> getEntriesFromChannel(String channelId)
{
MongoIterable<ScheduleEntry> entries = Main.getDBDriver().getEventCollection()
.find(eq("channelId", channelId)).map(ScheduleEntry::new);
return entries.into(new ArrayList<>());
}
项目:btm-DropwizardHealthChecks
文件:MongoDbHealthCheck.java
@Override
protected Result check() throws Exception {
MongoClient mongoClient = null;
String databaseList = null;
String databaseStats = null;
try {
mongoClient = createMongoClient();
MongoIterable<String> dbList = mongoClient.listDatabaseNames();
databaseList = StringUtils.join(dbList, ',');
CommandResult resultSet = mongoClient.getDB(databaseName).getStats();
databaseStats = resultSet.toString();
logger.debug("connectionUrl={} databaseList={} stats={}", connectionUrl, databaseList, databaseStats);
Integer nbrCollections = (Integer) resultSet.get("collections");
if (nbrCollections == 0) {
throw new RuntimeException("Database has nothing in it.");
}
} catch (Exception e) {
ContextedRuntimeException wrappedException = wrapException(e);
wrappedException.addContextValue("databaseList", databaseList);
wrappedException.addContextValue("databaseStats", databaseStats);
logger.error("MongoDB Healthcheck Failure", wrappedException);
return Result.unhealthy(wrappedException);
} finally {
closeQuietly(mongoClient);
}
return Result.healthy();
}
项目:giiwa
文件:MongoHelper.java
public static Set<String> getCollections(String dbname) {
MongoDatabase d = mongo.get(dbname);
if (d != null) {
MongoIterable<String> it = d.listCollectionNames();
MongoCursor<String> ii = it.iterator();
Set<String> r = new TreeSet<String>();
while (ii.hasNext()) {
r.add(ii.next());
}
return r;
}
return null;
}
项目:ibm-performance-monitor
文件:ProfiledMapMongotIterable.java
public ProfiledMapMongotIterable(MongoIterable<U> map, Function<TResult, U> mapper, ProfiledCursorCreator creator)
{
super();
this.mongoIterable = map;
this.mapper = mapper;
this.creator = creator;
}
项目:ibm-performance-monitor
文件:ProfiledMongoClientTest.java
public MongoIterable<String> createMap()
{
return coll.find(Filters.eq("name", "Alto")).map(new Function<Document, String>()
{
@Override
public String apply(Document t)
{
return t.getString("name");
}
});
}
项目:ibm-performance-monitor
文件:ProfiledMongoClientTest.java
public static <U> List<U> toDocumentList(MongoIterable<U> iterable)
{
List<U> retVal = new ArrayList<U>();
iterable.into(retVal);
// for (U document : iterable)
// {
// retVal.add(document);
// }
return retVal;
}
项目:Camel
文件:MongoDbOutputTypeTest.java
@Test
public void testFindAllDBCursor() {
// Test that the collection has 0 documents in it
assertEquals(0, testCollection.count());
pumpDataIntoTestCollection();
// Repeat ten times, obtain 10 batches of 100 results each time
int numToSkip = 0;
final int limit = 100;
for (int i = 0; i < 10; i++) {
Map<String, Object> headers = new HashMap<String, Object>();
headers.put(MongoDbConstants.NUM_TO_SKIP, numToSkip);
headers.put(MongoDbConstants.LIMIT, 100);
Object result = template.requestBodyAndHeaders("direct:findAllDBCursor", (Object) null, headers);
assertTrue("Result is not of type DBCursor", result instanceof MongoIterable);
MongoIterable<BasicDBObject> resultCursor = (MongoIterable<BasicDBObject>) result;
// Ensure that all returned documents contain all fields
for (DBObject dbObject : resultCursor) {
assertNotNull("DBObject in returned list should contain all fields", dbObject.get("_id"));
assertNotNull("DBObject in returned list should contain all fields", dbObject.get("scientist"));
assertNotNull("DBObject in returned list should contain all fields", dbObject.get("fixedField"));
}
numToSkip = numToSkip + limit;
}
}
项目:ymate-platform-v2
文件:ResultSetHelper.java
public static <T extends IEntity> List<T> toEntities(Class<T> entity, MongoIterable<Document> iterable) throws Exception {
MongoCursor<Document> _documentIt = iterable.iterator();
List<T> _resultSet = new ArrayList<T>();
while (_documentIt.hasNext()) {
_resultSet.add(toEntity(entity, _documentIt.next()));
}
return _resultSet;
}
项目:core-ng-project
文件:MongoCollectionImpl.java
private int apply(MongoIterable<T> mongoQuery, Consumer<T> consumer) {
int total = 0;
try (MongoCursor<T> cursor = mongoQuery.iterator()) {
while (cursor.hasNext()) {
T result = cursor.next();
total++;
consumer.accept(result);
}
}
return total;
}
项目:core-ng-project
文件:MongoCollectionImpl.java
private <V> void fetch(MongoIterable<V> iterable, List<V> results) {
try (MongoCursor<V> cursor = iterable.iterator()) {
while (cursor.hasNext()) {
results.add(cursor.next());
}
}
}
项目:mongo-utils
文件:MongoConverterImplementation.java
@Override
public <T> T firstEntityFrom(MongoIterable<Document> iterable, Class<T> entityClass) {
if (iterable == null || entityClass == null) {
return null;
}
Document document = iterable.first();
return entityFrom(document, entityClass);
}
项目:MongoExplorer
文件:MongoHelper.java
public static List<MongoCollectionRef> getCollectionNames(boolean includeSystemPrefs) {
MongoIterable<String> names = Database.listCollectionNames();
ArrayList<MongoCollectionRef> list = new ArrayList<>();
for (String str : names)
if (includeSystemPrefs || !str.startsWith("system."))
list.add(new MongoCollectionRef(str));
return list;
}
项目:sweng15
文件:DatabaseAdapter.java
/**
* Delete all data in the database
*/
public void deleteDatabase() {
MongoIterable<String> collectionNames = this.database.listCollectionNames();
//check if MOVIES_COLLECTION exists
for(String name:collectionNames){
if(name.equals(MOVIES_COLLECTION)){
//drop if exists
MongoCollection<Document> collection = database.getCollection(MOVIES_COLLECTION);
collection.drop();
}
}
this.database.getCollection(MOVIES_COLLECTION).drop();
}
项目:birt
文件:MDbConnection.java
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 );
}
}
项目:mongodb-slow-operations-profiler
文件:CmdIdxAccessStats.java
private TableDto getIndexStats(MongoDbAccessor mongoDbAccessor, String dbsLabel, String dbName){
final TableDto result = new TableDto();
final MongoIterable<String> collNames = mongoDbAccessor.getMongoDatabase(dbName).listCollectionNames();
if(collNames != null){
for(String collName : collNames){
final TableDto collStats = getIndexStats(mongoDbAccessor, dbsLabel, dbName, collName);
result.addRows(collStats);
}
}
return result;
}
项目:mongodb-slow-operations-profiler
文件:CmdIdxAccessStats.java
private TableDto getIndexStats(MongoDbAccessor mongoDbAccessor, String dbsLabel, String dbName, String collName){
final TableDto result = new TableDto();
final MongoIterable<Document> stats = mongoDbAccessor.getMongoDatabase(dbName).getCollection(collName)
.aggregate(Arrays.asList(
new Document("$indexStats", new Document()),
new Document("$project", new Document("name", 1)
.append("accesses.ops", 1)
.append("accesses.since", 1)
.append("host", 1)
),
new Document("$sort", new Document("accesses.ops", 1))
));
if(stats != null){
for(Document doc : stats){
LOG.info("db: {} col: {}", dbName, collName);
LOG.info("doc: {}", JSON.serialize(doc));
final ArrayList<Object> row = new ArrayList<Object>();
row.add(dbsLabel);
row.add(dbName);
row.add(collName);
row.add(doc.getString("name"));
final Object accesses = doc.get("accesses");
if(accesses != null && accesses instanceof Document){
final Document accDoc = (Document) accesses;
row.add(accDoc.getLong("ops"));
final Date date = accDoc.getDate("since");
final LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
row.add(localDateTime.format(DATE_TIME_FORMATTER));
}else{
row.add(0L);
row.add("");
}
row.add(doc.getString("host"));
result.addRow(row);
}
}
return result;
}
项目:mongodb-slow-operations-profiler
文件:CmdListDbCollections.java
private ArrayList<String> getCollectionNames(MongoDbAccessor mongoDbAccessor, String dbName){
final ArrayList<String> result = new ArrayList<String>();
final MongoIterable<String> collNames = mongoDbAccessor.getMongoDatabase(dbName).listCollectionNames();
if(collNames != null){
for(String collName : collNames){
result.add(collName);
}
}
return result;
}
项目:metamodel
文件:MongoDbDataContext.java
/**
* Performs an analysis of the available collections in a Mongo {@link DB} instance and tries to detect the table's
* structure based on the first 1000 documents in each collection.
*
* @param mongoDb the mongo db to inspect
* @return a mutable schema instance, useful for further fine tuning by the user.
* @see #detectTable(MongoDatabase, String)
*/
public static SimpleTableDef[] detectSchema(MongoDatabase mongoDb) {
MongoIterable<String> collectionNames = mongoDb.listCollectionNames();
List<SimpleTableDef> result = new ArrayList<>();
for (String collectionName : collectionNames) {
SimpleTableDef table = detectTable(mongoDb, collectionName);
result.add(table);
}
return result.toArray(new SimpleTableDef[0]);
}
项目:btm-DropwizardHealthChecks
文件:MongoDbHealthCheckTest.java
@Override
public MongoIterable<String> listDatabaseNames() {
return mongoIterable;
}
项目:ibm-performance-monitor
文件:ProfiledFindIterable.java
@Override
public MongoIterable<TResult> getMongoIterable()
{
return findIterable;
}
项目:ibm-performance-monitor
文件:ProfiledMongoDatabase.java
@Override
public MongoIterable<String> listCollectionNames()
{
return database.listCollectionNames();
}
项目:ibm-performance-monitor
文件:ProfiledMapMongotIterable.java
@Override
public MongoIterable<U> getMongoIterable()
{
return mongoIterable;
}
项目:ibm-performance-monitor
文件:ProfiledDistinctIterable.java
@Override
public MongoIterable<TResult> getMongoIterable()
{
return distinctIterable;
}
项目:ibm-performance-monitor
文件:ProfiledMapReduceIterable.java
@Override
public MongoIterable<TResult> getMongoIterable()
{
return mapReduceIterable;
}
项目:AbacusUtil
文件:MongoDBExecutor.java
public static DataSet extractData(final MongoIterable<?> findIterable) {
return extractData(Map.class, findIterable);
}
项目:para-dao-mongodb
文件:MongoDBUtils.java
/**
* Lists all table names for this account.
* @return a list of MongoDB tables
*/
public static MongoIterable<String> listAllTables() {
MongoIterable<String> collectionNames = getClient().listCollectionNames();
return collectionNames;
}
项目:respiro
文件:MongoDBExchangesPlugin.java
@Override
public MongoIterable<String> listCollectionNames() {
return null;
}
项目:eds-starter6-mongodb
文件:QueryUtil.java
public static <T> List<T> toList(MongoIterable<T> iterable) {
return StreamSupport.stream(iterable.spliterator(), false)
.collect(Collectors.toList());
}
项目:eds-starter6-mongodb
文件:QueryUtil.java
public static <T> Stream<T> stream(MongoIterable<T> iterable) {
return StreamSupport.stream(iterable.spliterator(), false);
}