Java Code Examples for com.mongodb.DB#getCollectionNames()

The following examples show how to use com.mongodb.DB#getCollectionNames() . 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: MongoUtil.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
	 * Refresh all database collections in given Mongo instance.
	 * @param mongoHost
	 * @param mongo
	 */
	private static void refreshMongoDatabase(Mongo mongo) {
		List<String> databaseNames = mongo.getDatabaseNames();
		for ( String database : databaseNames ) {
			DB db = mongo.getDB(database);
			Set<String> collSet = db.getCollectionNames();
			for ( String coll : collSet ) {
				String key = StringUtil.concat(database, Constant.DOT, coll);
				if ( !mongoMap.containsKey(key) ) {
					//Put it into our cache
					mongoMap.put(key, mongo);
					logger.debug("Put the mongo key: {} for server: {}", key);
				} else {
//					logger.warn("Key:{} is duplicate in mongo database");
				}
			}
		}
	}
 
Example 2
Source File: DbIndexValidator.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
protected static Set<MongoIndex> loadIndexInfoFromDB(DB database) {
    Set<MongoIndex> dbIndexes = new HashSet<MongoIndex>();

    Set<String> collectionNames = database.getCollectionNames();

    for (String collectionName : collectionNames) {
        DBCollection collection = database.getCollection(collectionName);
        List<DBObject> indexList = collection.getIndexInfo();
        for (DBObject dbObject : indexList) {
            DBObject keyObj = (DBObject) dbObject.get("key");
            Object uniqueField = dbObject.get("unique");
            Object sparseField = dbObject.get("sparse");
            boolean unique = false;
            boolean sparse = false;
            if (sparseField != null) {
            	sparse = Boolean.parseBoolean(sparseField.toString());
            }
            if (uniqueField != null) {
                unique = Boolean.parseBoolean(uniqueField.toString());
            }
            dbIndexes.add(new MongoIndex(collectionName, unique, keyObj, sparse));
        }
    }
    return dbIndexes;
}
 
Example 3
Source File: IndexingTaskTest.java    From hvdf with Apache License 2.0 5 votes vote down vote up
@Test
  public void shouldIndexAllCollections() throws Exception {

  	String feedName = "feed1";
  	String channelName = "channel1";
  	String configPath = "plugin_config/indexing_task_all_channels.json";

  	
  	Channel channel = getConfiguredChannel(configPath, feedName, channelName);
  	pushDataToChannel(channel, "v", 5000, 1, TimeUnit.SECONDS);

  	// Wait for the task to complete
  	Thread.sleep(2000);
  	
  	// Get the collections for the feed
  	DB feedDB = this.testClient.getDB(feedName);
  	Set<String> collNames = feedDB.getCollectionNames();
assertEquals("Should have 5 data collections + system.indexes", 6, collNames.size());
  	for(String collName : collNames){
  		if(collName.equals("system.indexes") == false){
  			DBCollection coll = feedDB.getCollection(collName);
  			List<DBObject> indexes = coll.getIndexInfo();
  			assertEquals("Should have _id index plus one additional", 2, indexes.size());
  			assertEquals("Should have data.v_1 index", indexes.get(1).get("name"), "data.v_1");
  		}
  	}
  }
 
Example 4
Source File: IndexingTaskTest.java    From hvdf with Apache License 2.0 5 votes vote down vote up
@Test
  public void shouldIndexSomeCollections() throws Exception {

  	String feedName = "feed2";
  	String channelName = "channel1";
  	String configPath = "plugin_config/indexing_task_skip_channels.json";

  	
  	Channel channel = getConfiguredChannel(configPath, feedName, channelName);
  	pushDataToChannel(channel, "v", 5000, 1, TimeUnit.SECONDS);

  	// Wait for the task to complete
  	Thread.sleep(2000);
  	
  	// Get the collections for the feed
  	DB feedDB = this.testClient.getDB(feedName);
  	Set<String> collNames = feedDB.getCollectionNames();
assertEquals("Should have 5 data collections + system.indexes", 6, collNames.size());

int indexedCount = 0;
  	for(String collName : collNames){
  		if(collName.equals("system.indexes") == false){
  			DBCollection coll = feedDB.getCollection(collName);
  			List<DBObject> indexes = coll.getIndexInfo();
  			if(indexes.size() == 2){
  				assertEquals("Should have data.v_1 index", indexes.get(1).get("name"), "data.v_1");
  				indexedCount++;
  			}
  		}
  	}
  	
assertEquals("Should 3 indexed collections", 3, indexedCount);    	
  }
 
Example 5
Source File: MongoDataLoadRule.java    From DotCi with MIT License 4 votes vote down vote up
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            if (Jenkins.getInstance() == null
                || SetupConfig.get().getInjector() == null
                || SetupConfig.get().getInjector().getInstance(Datastore.class) == null) {
                throw new IllegalStateException("Requires configured Jenkins and Mongo configurations");
            }

            DB db = SetupConfig.get().getInjector().getInstance(Datastore.class).getDB();

            //Load mongo data
            File homedir = Jenkins.getInstance().getRootDir();

            for (File fileOfData : homedir.listFiles()) {
                if (!fileOfData.getName().endsWith(".json")) continue;

                String collectionName = fileOfData.getName().replaceAll("\\.json$", "");
                DBCollection collection = db.createCollection(collectionName, new BasicDBObject());

                String data = FileUtils.readFileToString(fileOfData);
                Object bsonObject = JSON.parse(data);
                if (bsonObject instanceof BasicDBList) {
                    BasicDBList basicDBList = (BasicDBList) bsonObject;
                    collection.insert(basicDBList.toArray(new DBObject[0]));
                } else {
                    collection.insert((DBObject) bsonObject);
                }

            }

            for (OrganizationContainer container : Jenkins.getInstance().getAllItems(OrganizationContainer.class)) {
                container.reloadItems();
            }

            base.evaluate();

            // Clean up mongo data
            for (String collectioName : db.getCollectionNames()) {
                db.getCollection(collectioName).drop();
            }
        }
    };
}
 
Example 6
Source File: MongoQueryTest.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Test
public void stringEqual() throws Exception {

    UUID appId = emf.lookupApplication( "test-organization/test-app" );
    EntityManager em = emf.getEntityManager( appId );

    Map<String, Object> properties = new LinkedHashMap<String, Object>();
    properties.put( "name", "Kings of Leon" );
    properties.put( "genre", "Southern Rock" );
    properties.put( "founded", 2000 );
    em.create( "stringequal", properties );

    properties = new LinkedHashMap<String, Object>();
    properties.put( "name", "Stone Temple Pilots" );
    properties.put( "genre", "Rock" );
    properties.put( "founded", 1986 );
    em.create( "stringequal", properties );

    properties = new LinkedHashMap<String, Object>();
    properties.put( "name", "Journey" );
    properties.put( "genre", "Classic Rock" );
    properties.put( "founded", 1973 );
    em.create( "stringequal", properties );

    // See http://www.mongodb.org/display/DOCS/Java+Tutorial

    Mongo m = new Mongo( "localhost", 27017 );

    DB db = m.getDB( "test-organization/test-app" );
    db.authenticate( "test", "test".toCharArray() );

    Set<String> colls = db.getCollectionNames();

    assertTrue( colls.contains( "stringequals" ) );

    DBCollection coll = db.getCollection( "stringequals" );
    DBCursor cur = coll.find();
    int count = 0;

    while ( cur.hasNext() ) {
        cur.next();
        count++;
    }

    assertEquals( 3, count );

    BasicDBObject query = new BasicDBObject();
    query.put( "genre", "Southern Rock" );
    cur = coll.find( query );

    assertTrue( cur.hasNext() );

    DBObject result = cur.next();
    assertEquals( "Kings of Leon", result.get( "name" ) );
    assertEquals( "Southern Rock", result.get( "genre" ) );

    assertFalse( cur.hasNext() );
}