Java Code Examples for com.mongodb.Mongo#getDB()

The following examples show how to use com.mongodb.Mongo#getDB() . 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: SparkCache.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private SparkCache() {
	sparkMap = DBMaker.newTempTreeMap();
	dataMap = DBMaker.newTempTreeMap();
	
	// If we're running in a cluster, where the API is load balanced, we actually
	// need to store the spark bytes in a DB. In memory cache wouldn't work.
	Mongo mongo;
	try {
		mongo = Configuration.getInstance().getMongoConnection();
	} catch (UnknownHostException e) {
		e.printStackTrace();
		return;
	}
	DB db = mongo.getDB("scava");
	DBCollection col = db.getCollection("sparks");
	col.ensureIndex("sparkid");
	col.ensureIndex(new BasicDBObject("created_at", 1), new BasicDBObject("expireAfterSeconds", 3600));
}
 
Example 2
Source File: SparkCache.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
public synchronized byte[] getSpark(String sparkId) {
//		return sparkMap.get(sparkId);
		byte[] spark = null;
		Mongo mongo;
		try {
			mongo = Configuration.getInstance().getMongoConnection();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return null;
		}
		
		DB db = mongo.getDB("scava");
		DBCollection col = db.getCollection("sparks");
		
		DBObject obj = col.findOne(new BasicDBObject("sparkid", sparkId));
		if (obj != null) {
			spark = (byte[])obj.get("bytes");
		}
		return spark;
	}
 
Example 3
Source File: SparkCache.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
public synchronized void putSpark(String sparkId, byte[] img) {
//		sparkMap.put(sparkId, img);
		Mongo mongo;
		try {
			mongo = Configuration.getInstance().getMongoConnection();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return;
		}
		DB db = mongo.getDB("scava");
		DBCollection col = db.getCollection("sparks");
		
		BasicDBObject obj = new BasicDBObject();
		obj.put("sparkid", sparkId);
		obj.put("bytes", img);
		obj.put("created_at", new Date());
		
		col.insert(obj);
	}
 
Example 4
Source File: RascalMetricProvider.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
public IValue getMetricResult(Project project, IMetricProvider provider, RascalManager man) {
	Type type = provider instanceof RascalMetricProvider ? ((RascalMetricProvider) provider).getReturnType() : ((RascalMetricHistoryWrapper) provider).getValueType();
	if (context == null) {
		return null;
	}
	// FIXME: For some reason, the following code
	// returns "This database has been closed" after
	// some time.
	// Quick and very dirty fix: re-open the DB from
	// scratch.
	//DB db = context.getProjectDB(project);
	Mongo mongo;
	try {
//		mongo = new Mongo();
		mongo = Configuration.getInstance().getMongoConnection();
		DB db = mongo.getDB(project.getShortName());
		RascalMetrics rascalMetrics = new RascalMetrics(db, provider.getIdentifier());
		return PongoToRascal.toValue(rascalMetrics, type, provider instanceof RascalMetricHistoryWrapper);
	} catch (UnknownHostException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return null;
	}
}
 
Example 5
Source File: AppLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
    // Creating Mongodbruntime instance
    MongoDBRuntime runtime = MongoDBRuntime.getDefaultInstance();

    // Creating MongodbExecutable
    mongodExe = runtime.prepare(new MongodConfig(Version.V2_0_1, 12345, Network.localhostIsIPv6()));

    // Starting Mongodb
    mongod = mongodExe.start();
    mongo = new Mongo("localhost", 12345);

    // Creating DB
    db = mongo.getDB(DB_NAME);

    // Creating collection Object and adding values
    collection = db.getCollection("customers");
}
 
Example 6
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 7
Source File: CsvCombine.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public CsvCombine() {
    try {
        mongo = new Mongo();
        db = mongo.getDB("StagingDB");
    } catch (Exception e) {
    }
}
 
Example 8
Source File: CocomoFactoid.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public static void main(String[] args)  throws Exception {
	Mongo mongo = new Mongo();
	DB db = mongo.getDB("Xtext");
	
	CocomoFactoid f = new CocomoFactoid();
	f.adapt(db);
	f.measure(null, null, new Factoids(db));
	
	System.out.println(FactoidCategory.valueOf("asdasdasdd"));
}
 
Example 9
Source File: IdByNameLookup.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * getAssessmentId - Look up an assessment ID given the assessments identification code ID.
 *
 * @param assmtIDCode - ID code to look up
 * @return assessment identifier
 * @throws UnknownHostException
 */
public static String getAssessmentId(String assmtIDCode) throws UnknownHostException {

    // TODO - parameterize these values.
    Mongo m = new Mongo("localhost");
    DB db = m.getDB("sli");
    DBCollection assessments = db.getCollection("assessment");
    DBObject assmt = assessments.findOne(new BasicDBObject("body.assessmentIdentificationCode.ID", assmtIDCode));
    String assmtId = (String) assmt.get("_id");
    return assmtId;
}
 
Example 10
Source File: MongoConnection.java    From bluima with Apache License 2.0 5 votes vote down vote up
/**
 * @param db_connection
 *            an array {host, dbName, collectionName, user, pw}. Leave user
 *            and pw empty ("") to skip authentication
 */
public MongoConnection(String[] db_connection, boolean safe)
		throws UnknownHostException, MongoException {

	checkArgument(db_connection.length == 5,
			"Should be: host, dbname, collectionname, user, pw but lengh = "
					+ db_connection.length);

	host = db_connection[0];
	dbName = db_connection[1];
	collectionName = db_connection[2];
	user = db_connection[3];
	pw = db_connection[4];

	checkNotNull(host, "host is NULL");
	checkNotNull(dbName, "dbName is NULL");
	checkNotNull(collectionName, "collectionName is NULL");
	checkNotNull(user, "user is NULL");
	checkNotNull(pw, "pw is NULL");

	m = new Mongo(host, 27017);
	if (safe)
		m.setWriteConcern(WriteConcern.SAFE);
	m.getDatabaseNames();// to test connection
	db = m.getDB(dbName);
	if (user.length() > 0) {
		if (!db.authenticate(user, pw.toCharArray())) {
			throw new MongoException(-1, "cannot login with user " + user);
		}
	}
	coll = db.getCollection(collectionName);
}
 
Example 11
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
		if ( args.length < 4 ) {
			System.out.println("MongoBenchmark <host> <port> <db> <max>");
			System.exit(-1);
		}
		String host = args[0];
		int port = StringUtil.toInt(args[1], 27017);
		String database = args[2];
		int max = StringUtil.toInt(args[3], 1);
		
		System.out.println("Connect to " + host + ":" + port + " db: " + database + ", max: " + max);
		Mongo mongo = new Mongo(host, port);
		System.out.println("First compare Mongo native ObjectId, our customized ObjectId and String Id");
		
		DB db = null;
		
//		db = mongo.getDB(database+1);
//		db.dropDatabase();
//		testMongoUserId(max, db);
//		
//		db = mongo.getDB(database+2);
//		db.dropDatabase();
//		testMyUserId(max, db);
//		
//		db = mongo.getDB(database+3);
//		db.dropDatabase();
//		testStringUserId(max, db);
		
		System.out.println("Second: compare Mongo BasicDBObject and our MapDBObject");
		
		db = mongo.getDB(database+4);
		db.dropDatabase();
		testBasicBson(max, db);
		
		db = mongo.getDB(database+5);
		db.dropDatabase();
		testMapDBObject(max, db);
	}
 
Example 12
Source File: TestProjectResource.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testPostInsert() throws Exception {
	Request request = new Request(Method.POST, "http://localhost:8182/projects/");

	ObjectMapper mapper = new ObjectMapper();
	
	ObjectNode p = mapper.createObjectNode();
	p.put("name", "test");
	p.put("shortName", "test-short");
	p.put("description", "this is a description");

	request.setEntity(p.toString(), MediaType.APPLICATION_JSON);
	
	Client client = new Client(Protocol.HTTP);
	Response response = client.handle(request);
	
	System.out.println(response.getEntity().getText() + " " + response.isEntityAvailable());
	
	validateResponse(response, 201);
	
	// Now try again, it should fail
	response = client.handle(request);
	validateResponse(response, 409);
	
	// Clean up
	Mongo mongo = new Mongo();
	DB db = mongo.getDB("scava");
	DBCollection col = db.getCollection("projects");
	BasicDBObject query = new BasicDBObject("name", "test");
	col.remove(query);

	mongo.close();
}
 
Example 13
Source File: MigrationIssueMaracasTransMetricProvider.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private RascalMetrics getMaracasDB(Project project, IMetricProvider iMetricProvider)
{
	Mongo mongo;
	RascalMetrics rascalMetrics=null;
	try {
		mongo = Configuration.getInstance().getMongoConnection();
		DB db = mongo.getDB(project.getShortName());
		rascalMetrics = new RascalMetrics(db, iMetricProvider.getIdentifier());
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
	return rascalMetrics;
}
 
Example 14
Source File: MongoDbGridFSIO.java    From beam with Apache License 2.0 4 votes vote down vote up
GridFS setupGridFS(Mongo mongo) {
  DB db = database() == null ? mongo.getDB("gridfs") : mongo.getDB(database());
  return bucket() == null ? new GridFS(db) : new GridFS(db, bucket());
}
 
Example 15
Source File: MongoQueryTest.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Test
public void lessThanEqual() 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( "lessthanequal", properties );

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

    properties = new LinkedHashMap<String, Object>();
    properties.put( "name", "Journey" );
    properties.put( "genre", "Classic Rock" );
    properties.put( "founded", 1973 );
    em.create( "lessthanequal", 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() );

    BasicDBObject query = new BasicDBObject();
    query.put( "founded", new BasicDBObject( "$lte", 2000 ) );

    DBCollection coll = db.getCollection( "lessthanequals" );
    DBCursor cur = coll.find( query );

    assertTrue( cur.hasNext() );

    DBObject result = cur.next();
    assertEquals( "Journey", result.get( "name" ) );
    assertEquals( "Classic Rock", result.get( "genre" ) );

    result = cur.next();
    assertEquals( "Stone Temple Pilots", result.get( "name" ) );
    assertEquals( "Rock", result.get( "genre" ) );

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

    assertFalse( cur.hasNext() );
}
 
Example 16
Source File: ChartUtil.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
public static DBCollection getCollection(Mongo mongo, String dbName, String collectionName) {
	DB db = mongo.getDB(dbName);
	DBCollection collection = db.getCollection(collectionName);
	return collection;
}
 
Example 17
Source File: MongoQueryTest.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Test
public void withFieldSelector() 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( "withfieldselector", properties );

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


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

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

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

    BasicDBObject queryName = new BasicDBObject();
    queryName.put( "name", "Journey" );

    BasicDBObject limitName = new BasicDBObject();
    limitName.put( "name", 1 );

    //query.put();
    DBCollection coll = db.getCollection( "withfieldselectors" );

    DBCursor cur = coll.find( queryName, limitName );

    assertTrue( cur.hasNext() );
}
 
Example 18
Source File: NNTPDownloader.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
public void downloadMessages(NntpNewsGroup newsgroup) throws Exception {
	final long startTime = System.currentTimeMillis();
	long previousTime = startTime;
	previousTime = printTimeMessage(startTime, previousTime, "Download started");

	NNTPClient nntpClient = NntpUtil.connectToNntpServer(newsgroup);
	
	NewsgroupInfo newsgroupInfo = NntpUtil.selectNewsgroup(nntpClient, newsgroup);
	
	long lastArticleChecked = newsgroupInfo.getFirstArticleLong();
	previousTime = printTimeMessage(startTime, previousTime,
			"First message in newsgroup:\t" + lastArticleChecked);
	
	long lastArticle = newsgroupInfo.getLastArticleLong();
	previousTime = printTimeMessage(startTime, previousTime,
			"Last message in newsgroup:\t" + lastArticle);
	
	previousTime = printTimeMessage(startTime, previousTime,
			"Articles in newsgroup:\t" + newsgroupInfo.getArticleCountLong());
	System.err.println();
	
	Mongo mongo = Configuration.getInstance().getMongoConnection();
	DB db = mongo.getDB(newsgroup.getName() + "LocalStorage");
	Messages dbMessages = new Messages(db);
		
	NewsgroupData newsgroupData = dbMessages.getNewsgroup().findOneByName(newsgroup.getName());
	if (newsgroupData != null) {
		int newsgroupLastArticleChecked = Integer.parseInt(newsgroupData.getLastArticleChecked());
		if (newsgroupLastArticleChecked > lastArticleChecked) {
			lastArticleChecked = newsgroupLastArticleChecked;
		}
		previousTime = printTimeMessage(startTime, previousTime,
				"Last article checked set to:\t" + lastArticleChecked);
	} else {
		newsgroupData = new NewsgroupData();
		newsgroupData.setName(newsgroup.getName());
		newsgroupData.setUrl(newsgroup.getUrl());
		newsgroupData.setAuthenticationRequired(newsgroup.getAuthenticationRequired());
		newsgroupData.setUsername(newsgroup.getUsername());
		newsgroupData.setPassword(newsgroup.getPassword());
		newsgroupData.setPort(newsgroup.getPort());
		newsgroupData.setInterval(newsgroup.getInterval());
		newsgroupData.setFirstArticle(lastArticleChecked+"");
		dbMessages.getNewsgroup().add(newsgroupData);
	}

	long retrievalStep = RETRIEVAL_STEP;
	while (lastArticleChecked < lastArticle) {
		if (lastArticleChecked + retrievalStep > lastArticle) {
			retrievalStep = lastArticle - lastArticleChecked;
		}
		Article[] articles = NntpUtil.getArticleInfo(nntpClient, 
					lastArticleChecked + 1, lastArticleChecked + retrievalStep);
		if (articles.length > 0) {
			Article lastArticleRetrieved = articles[articles.length-1];
			lastArticleChecked = lastArticleRetrieved.getArticleNumberLong();
			newsgroupData.setLastArticleChecked(lastArticleChecked+"");
		}
		previousTime = printTimeMessage(startTime, previousTime,
				"downloaded:\t"+ articles.length + " nntp articles");
		previousTime = printTimeMessage(startTime, previousTime,
				"downloading contents\t");
		
		for (Article article: articles) {
			ArticleData articleData = new ArticleData();
			articleData.setUrl(newsgroup.getUrl());
			articleData.setArticleNumber(article.getArticleNumberLong());
			articleData.setArticleId(article.getArticleId());
			articleData.setDate(article.getDate());
			articleData.setFrom(article.getFrom());
			articleData.setSubject(article.getSubject());
			for (String referenceId: article.getReferences())
				articleData.getReferences().add(referenceId);
			articleData.setBody(NntpUtil.getArticleBody(nntpClient, article.getArticleNumberLong()));
			dbMessages.getArticles().add(articleData);
		}
		dbMessages.sync();
		previousTime = printTimeMessage(startTime, previousTime,
				"stored:\t"+ dbMessages.getArticles().size() + 
				" / " + newsgroupInfo.getArticleCount() + " nntp articles sofar");
		System.err.println();
	}
	nntpClient.disconnect(); 
	dbMessages.sync();
	previousTime = printTimeMessage(startTime, previousTime,
			"stored:\t"+ dbMessages.getArticles().size() + 
			" / " + newsgroupInfo.getArticleCount() + " nntp articles");
}
 
Example 19
Source File: MongoQueryTest.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Test
public void greaterThan() 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( "greaterthan", properties );

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

    properties = new LinkedHashMap<String, Object>();
    properties.put( "name", "Journey" );
    properties.put( "genre", "Classic Rock" );
    properties.put( "founded", 1973 );
    em.create( "greaterthan", 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() );

    BasicDBObject query = new BasicDBObject();
    query.put( "founded", new BasicDBObject( "$gt", 1973 ) );

    DBCollection coll = db.getCollection( "greaterthans" );
    DBCursor cur = coll.find( query );

    assertTrue( cur.hasNext() );

    DBObject result = cur.next();
    assertEquals( "Stone Temple Pilots", result.get( "name" ) );
    assertEquals( "Rock", result.get( "genre" ) );

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

    assertFalse( cur.hasNext() );
}
 
Example 20
Source File: SchoolProficiencyMapper.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
public SchoolProficiencyMapper() throws UnknownHostException, MongoException {
    mongo = new Mongo("localhost");
    db = mongo.getDB("sli");
    ssa = db.getCollection("studentSchoolAssociation");
    studentColl = db.getCollection("student");
}