Java Code Examples for com.mongodb.DB

The following examples show how to use com.mongodb.DB. 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
@Test
public void testMongodbLocalServer() throws Exception {
    MongoClient mongo = new MongoClient(mongodbLocalServer.getIp(), mongodbLocalServer.getPort());

    DB db = mongo.getDB(propertyParser.getProperty(ConfigVars.MONGO_DATABASE_NAME_KEY));
    DBCollection col = db.createCollection(propertyParser.getProperty(ConfigVars.MONGO_COLLECTION_NAME_KEY),
            new BasicDBObject());
    
    col.save(new BasicDBObject("testDoc", new Date()));
    LOG.info("MONGODB: Number of items in collection: {}", col.count());
    assertEquals(1, col.count());
    
    DBCursor cursor = col.find();
    while(cursor.hasNext()) {
        LOG.info("MONGODB: Document output: {}", cursor.next());
    }
    cursor.close();
}
 
Example 2
Source Project: act   Source File: FreemarkerRenderer.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void init(String dbHost, Integer dbPort, String dbName, String dnaCollection, String pathwayCollection) throws IOException {
  cfg = new Configuration(Configuration.VERSION_2_3_23);

  cfg.setClassLoaderForTemplateLoading(
      this.getClass().getClassLoader(), "/act/installer/reachablesexplorer/templates");
  cfg.setDefaultEncoding("UTF-8");

  cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
  cfg.setLogTemplateExceptions(true);

  reachableTemplate = cfg.getTemplate(reachableTemplateName);
  pathwayTemplate = cfg.getTemplate(pathwayTemplateName);

  // TODO: move this elsewhere.
  MongoClient client = new MongoClient(new ServerAddress(dbHost, dbPort));
  DB db = client.getDB(dbName);

  dnaDesignCollection = JacksonDBCollection.wrap(db.getCollection(dnaCollection), DNADesign.class, String.class);
  Cascade.setCollectionName(pathwayCollection);
}
 
Example 3
Source Project: scava   Source File: SourceForgeManager.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public CommunicationChannelDelta getDelta(DB db, Discussion discussion, Date date) throws Exception {

	java.util.Date day = date.toJavaDate();

	Cache<SourceForgeArticle, String> articleCache = articleCaches.getCache(discussion, true);
	Iterable<SourceForgeArticle> articles = articleCache.getItemsAfterDate(day);

	SourceForgeCommunicationChannelDelta delta = new SourceForgeCommunicationChannelDelta();
	delta.setNewsgroup(discussion);
	for (SourceForgeArticle article : articles) {
		java.util.Date articleDate = article.getDate();
		if (article.getUpdateDate() != null)
			articleDate = article.getUpdateDate();
		if (DateUtils.isSameDay(articleDate, day)) {
			article.setText(getContents(db, discussion, article));
			delta.getArticles().add(article);
		}
	}
	System.err.println("Delta for date " + date + " contains " + delta.getArticles().size());
	return delta;
}
 
Example 4
Source Project: scava   Source File: BugzillaManager.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
	public BugTrackingSystemDelta getDelta(DB db, Bugzilla bugzilla, Date date) throws Exception {
		
		System.err.println("Date: " + date.toString());
		BugzillaSession session = new BugzillaSession(bugzilla.getUrl());
		
		BugTrackingSystemDelta delta = new BugTrackingSystemDelta();
		delta.setBugTrackingSystem(bugzilla);
		// Get bugs started on date
		List<Bug> bugs = getBugs(bugzilla, delta, session, date);
		// Get the comments of bugs that were started before date
//		PROBLEM: NOW WE SEARCH ONLY THE COMMENTS 
		getUpdatedBugsComments(bugzilla, delta, session, date);
		// Get the comments of bugs that were started on date
		getComments(bugzilla, delta, session, bugs, date);
		getUpdatedBugsAttachments(bugzilla, delta, session, date);
		return delta;
	}
 
Example 5
@Override
public Date getFirstDate(DB db, CommunicationChannel communicationChannel)
		throws Exception {
	for (ICommunicationChannelManager communicationChannelManager : getCommunicationChannelManagers()) {
		if (communicationChannelManager.appliesTo(communicationChannel)) {
			ManagerAnalysis mAnal = ManagerAnalysis.create(communicationChannelManager.toString(), 
					"getFirstDate",
					communicationChannel.getUrl(),
					null,
					new java.util.Date());
			platform.getProjectRepositoryManager().getProjectRepository().getManagerAnalysis().add(mAnal);
			long start = System.currentTimeMillis();
			
			Date firstDate = communicationChannelManager.getFirstDate(db, communicationChannel);
			
			mAnal.setMillisTaken(System.currentTimeMillis() - start);
			platform.getProjectRepositoryManager().getProjectRepository().getManagerAnalysis().sync();

			return firstDate;
		}
	}
	return null;
}
 
Example 6
@Override
public Date getFirstDate(DB db, BugTrackingSystem bugTrackingSystem)
		throws Exception {
	IBugTrackingSystemManager bugTrackingSystemManager = getBugTrackingSystemManager(bugTrackingSystem);
	if (bugTrackingSystemManager != null) {
		ManagerAnalysis mAnal = ManagerAnalysis.create(bugTrackingSystemManager.toString(), 
				"getFirstDate",
				bugTrackingSystem.getUrl(),
				null,
				new java.util.Date());
		platform.getProjectRepositoryManager().getProjectRepository().getManagerAnalysis().add(mAnal);
		long start = System.currentTimeMillis();
		
		Date firstDate = bugTrackingSystemManager.getFirstDate(db, bugTrackingSystem);
		
		mAnal.setMillisTaken(System.currentTimeMillis() - start);
		platform.getProjectRepositoryManager().getProjectRepository().getManagerAnalysis().sync();

		return firstDate;
	}
	
	return null;
}
 
Example 7
@Override
public String getContents(DB db, BugTrackingSystem bugTrackingSystem, BugTrackingSystemBug bug) throws Exception {
	String cache = getContentsCache().getCachedContents(bug);
	if (cache != null) {
		System.err.println("BugTrackingSystemBug CACHE HIT!");
		return cache;
	}

	IBugTrackingSystemManager bugTrackingSystemManager =
	getBugTrackingSystemManager((bug.getBugTrackingSystem()));
	
	if (bugTrackingSystemManager != null) {
		String contents = bugTrackingSystemManager.getContents(db, bugTrackingSystem, bug);
		getContentsCache().putContents(bug, contents);
		return contents;
	}
	return null;
}
 
Example 8
private MongoCollection getProfilingCollection() {
        CollectorServerDto serverDto = ConfigReader.getCollectorServer();
;
        try{
            MongoDbAccessor mongo = new MongoDbAccessor(60000, -1, true, serverDto.getAdminUser(), serverDto.getAdminPw(), serverDto.getSsl(), serverDto.getHosts());
            DB db = mongo.getMongoDB(serverDto.getDb());
            Jongo jongo = new Jongo(db);
            MongoCollection result =  jongo.getCollection(serverDto.getCollection());

            if(result == null) {
                throw new IllegalArgumentException("Can't continue without profile collection for " + serverDto.getHosts());
            }

            return result;
        } catch (MongoException e) {
            LOG.error("Exception while connecting to: {}", serverDto.getHosts(), e);
        }
        return null;
    }
 
Example 9
Source Project: scava   Source File: RascalMetricProvider.java    License: 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 10
Source Project: gameserver   Source File: MongoDBUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get the proper DB object by given database and collection.
 * @param databaseName
 * @param namespace
 * @param collection
 * @return
 */
public static final DB getDB(String databaseName,
		String namespace, String collection) {
	String key = null;
	if ( namespace == null ) {
		key = StringUtil.concat(collection);
	} else {
		key = StringUtil.concat(namespace, DOT, collection);
	}
	Mongo mongo = mongoMap.get(key);
	if ( mongo == null ) {
		logger.warn("Failed to find Mongo by key:{}. Need refresh", key);
		return null;
	} else {
		DB db = mongo.getDB(databaseName);
		return db;
	}
}
 
Example 11
@Override
public DB getDb() throws DataAccessException {

    String jobId = TenantContext.getJobId();
    if (jobId == null) {
        return super.getDb();
    }

    String dbName = BatchJobUtils.jobIdToDbName(jobId);
    return super.getDb(dbName);
}
 
Example 12
@Before
public void setUp() {
	DB db = mongo.getDB("test");
	DBCollection col = db.createCollection("testing", new BasicDBObject());
	col.save(new BasicDBObject("greeting", "hello"));
	col.save(new BasicDBObject("greeting", "hola"));
}
 
Example 13
private static Set<DBObject> getUserObjects(String collectionName, MongoClient mongo) {
	Set<DBObject> users = new HashSet<>();
	try {
		DB database = mongo.getDB(dbName);
		DBCollection collection = Task.getDBCollection(database, collectionName);
		DBCursor cursor = collection.find();
		while (cursor.hasNext()) {
			users.add(cursor.next());
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return users;
}
 
Example 14
Source Project: scava   Source File: MetricVisualisationTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testSparky() throws Exception {
	Chart chart = ChartUtil.loadChart("charts/linechart.json");
	JsonNode metricSpecification = ChartUtil.loadJsonFile("data/commitsovertime.json");
	JsonNode vis = metricSpecification.get("vis").get(0);
	
	MetricVisualisation mv = new MetricVisualisation(chart, metricSpecification, vis);
	
	DB db = mongo.getDB("Xtext");
	DBCollection collection = db.getCollection(metricSpecification.path("metricid").textValue());
	
	Random random = new Random();
	int commits = 0;
	Date[] range = Date.range(new Date("20140101"), new Date("20140130"));
	
	for (Date d : range) {
		CommitsOverTime cot = new CommitsOverTime();
		RepositoryData rd = new RepositoryData();
		rd.setUrl("foo");
		rd.setNumberOfCommits(commits);
		commits = commits + (random.nextInt(10));
		cot.getRepositories().add(rd);
		
		DBObject dbObject = cot.getDbObject();
		
		dbObject.put("__date", d.toString());
		dbObject.put("__datetime", d.toJavaDate());
		collection.save(dbObject);
	}
	
	byte[] sparky = mv.getSparky(db, null);
	for (byte b : sparky) System.out.println(b);
	System.out.println(sparky);
	
}
 
Example 15
Source Project: DBus   Source File: DBusMongoClient.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isReplSet() {
    boolean ret = false;
    DB db = new DB(mongoClient, "admin");
    CommandResult cr = db.command("replSetGetStatus");
    logger.info("isReplSet: {}", cr.toJson());
    if (cr.containsField("set") && cr.containsField("members")) {
        ret = true;
    }
    return ret;
}
 
Example 16
Source Project: scava   Source File: ImplementationSmells.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void setDb(DB db) {
	super.setDb(db);
	smells = new ImplementationSmellCollection(db.getCollection("Puppet.implementationSmells"));
	pongoCollections.add(smells);
	customSmells = new ImplementationCustomSmellCollection(db.getCollection("Puppet.customImplementationSmells"));
	pongoCollections.add(customSmells);
}
 
Example 17
Source Project: sample-acmegifts   Source File: MongoAccess.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/** Get a connection to Mongo. */
public synchronized DB getMongoDB() {
  if (database == null) {
    try {
      MongoClient client = new MongoClient(mongoHostname, mongoPort);
      database = client.getDB("gifts-user");
    } catch (UnknownHostException uhe) {
      throw new RuntimeException(uhe);
    }
  }

  return database;
}
 
Example 18
Source Project: scava   Source File: BugzillaManager.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
	public String getContents(DB db, Bugzilla bugzilla,
			BugTrackingSystemComment comment) throws Exception {
		BugzillaSession session = new BugzillaSession(bugzilla.getUrl());
		List<Comment> retrievedComments = 
				session.getCommentsForBugId(Integer.parseInt(comment.getBugId()));
		for (Comment retrievedComment: retrievedComments) {
			if (retrievedComment.getId() == Integer.parseInt(comment.getCommentId())) {
//				System.err.println("getContents:\tcomment retrieved");
				return retrievedComment.getText();
			}
		}
		return null;
	}
 
Example 19
public DefaultMongoDataSource(String creator, MongoClient mongo, DB db, String logicDataSourceId, String realDataSourceId) {
	this.mongo = mongo;
	this.db = db;
	this.creator = creator;
	this.logicDataSourceId = logicDataSourceId;
	this.realDataSourceId = realDataSourceId;
}
 
Example 20
Source Project: scava   Source File: BugzillaManager.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
	public String getContents(DB db, Bugzilla bugzilla, BugTrackingSystemBug bug) throws Exception {
		BugzillaSession session = new BugzillaSession(bugzilla.getUrl());
		Bug retrievedBug = session.getBugById(Integer.parseInt(bug.getBugId()));
//		System.err.println("getContents:\tbug retrieved");
		return retrievedBug.getSummary();
	}
 
Example 21
Source Project: scava   Source File: ZendeskManager.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String getContents(DB db, Zendesk communicationChannel,
		CommunicationChannelArticle article) throws Exception {

	org.eclipse.scava.platform.communicationchannel.zendesk.Zendesk zendesk;
	zendesk = new org.eclipse.scava.platform.communicationchannel.zendesk.Zendesk.Builder(
			communicationChannel.getUrl())
			.setUsername(communicationChannel.getUsername())
			.setPassword(communicationChannel.getPassword()).build();
	String contents = zendesk.getTicket(article.getArticleNumber())
			.getDescription();
	zendesk.close();
	return contents;
}
 
Example 22
Source Project: deep-spark   Source File: MongoNativeExtractor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Is sharded collection.
 *
 * @param collection the collection
 * @return the boolean
 */
private boolean isShardedCollection(DBCollection collection) {

    DB config = collection.getDB().getMongo().getDB("config");
    DBCollection configCollections = config.getCollection("collections");

    DBObject dbObject = configCollections.findOne(new BasicDBObject(MONGO_DEFAULT_ID, collection.getFullName()));
    return dbObject != null;
}
 
Example 23
Source Project: scava   Source File: TestProjectResource.java    License: 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 24
Source Project: scava   Source File: MetricHistoryManager.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public void store(Project project, Date date, IHistoricalMetricProvider provider) {
	DB db = platform.getMetricsRepository(project).getDb();
	
	DBCollection collection = db.getCollection(provider.getCollectionName());

	MetricProviderContext context = new MetricProviderContext(platform, OssmeterLoggerFactory.getInstance().makeNewLoggerInstance(provider.getIdentifier()));
	context.setDate(date);
	provider.setMetricProviderContext(context);
	Pongo metric = provider.measure(project);
	DBObject dbObject = metric.getDbObject();
	
	dbObject.put("__date", date.toString());
	dbObject.put("__datetime", date.toJavaDate());
	collection.save(dbObject);
}
 
Example 25
Source Project: hvdf   Source File: PeriodicAllocator.java    License: Apache License 2.0 5 votes vote down vote up
public PeriodicAllocator(PluginConfiguration config){
	
	TimePeriod tPeriod = config.get(TIME_PERIOD, TimePeriod.class);
	period = tPeriod.getAs(TimeUnit.MILLISECONDS);
	prefix = config.get(HVDF.PREFIX, String.class);
	prefixLength = prefix.length();
	db = config.get(HVDF.DB, DB.class);
}
 
Example 26
Source Project: scava   Source File: EclipseForumsManager.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String getContents(DB db, EclipseForum communicationChannel, CommunicationChannelArticle article)
		throws Exception {

	// NOT USED
	return null;
}
 
Example 27
Source Project: brooklyn-library   Source File: MongoDBTestHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Inserts a new object with { key: value } at given server.
 * @return The new document's id
 */
public static String insert(AbstractMongoDBServer entity, String key, Object value) {
    LOG.info("Inserting {}:{} at {}", new Object[]{key, value, entity});
    MongoClient mongoClient = clientForServer(entity);
    try {
        DB db = mongoClient.getDB(TEST_DB);
        DBCollection testCollection = db.getCollection(TEST_COLLECTION);
        BasicDBObject doc = new BasicDBObject(key, value);
        testCollection.insert(doc);
        ObjectId id = (ObjectId) doc.get("_id");
        return id.toString();
    } finally {
        mongoClient.close();
    }
}
 
Example 28
private void injectFongo(MongoSink mongoSink) {
    try {
        MongoClient mongoClient = fongo.getMongo();
        DB mongoDefaultDb = mongoClient.getDB("test");
        DBCollection mongoDefaultCollection = mongoDefaultDb.getCollection("test");
        setField(mongoSink, "mongoClient", mongoClient);
        setField(mongoSink, "mongoDefaultDb", mongoDefaultDb);
        setField(mongoSink, "mongoDefaultCollection", mongoDefaultCollection);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 29
@Test
public void test() throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException {
    tenantDBIndexValidator.setTenantDA(tenantDA);

    Mockito.doCallRealMethod().when(tenantDBIndexValidator).isValid(Matchers.any(DB.class), Matchers.any(List.class), Matchers.any(AbstractMessageReport.class), Matchers.any(ReportStats.class), Matchers.any(Source.class));

    AbstractMessageReport report = Mockito.mock(AbstractMessageReport.class);
    ReportStats reportStats = Mockito.mock(ReportStats.class);
    Source source = Mockito.mock(Source.class);

    tenantDBIndexValidator.isValid(db, report, reportStats, source, null);

    Mockito.verify(report, Mockito.atLeast(1)).info(Matchers.eq(reportStats), Matchers.eq(source), Matchers.eq(CoreMessageCode.CORE_0018), Matchers.eq("assessment"), Matchers.any(Map.class), Matchers.eq(false));
    Mockito.verify(report, Mockito.atLeast(1)).error(Matchers.eq(reportStats), Matchers.eq(source), Matchers.eq(CoreMessageCode.CORE_0038), Matchers.eq("assessmentFamilyCollection"), Matchers.any(Map.class), Matchers.eq(false));
}
 
Example 30
public List<Pongo> getHistoricalMeasurements(MetricProviderContext context, Project project, Date start, Date end) {
	
	DB db = context.getProjectDB(project);
	DBCollection collection = db.getCollection(this.getCollectionName());
	
	QueryBuilder builder = QueryBuilder.start();
	if (start != null) {
		builder.and("__datetime").greaterThanEquals(start.toJavaDate());
	}
	if (end != null) {
		builder.and("__datetime").lessThanEquals(end.toJavaDate());
	}
	 
	BasicDBObject query = (BasicDBObject) builder.get(); 

	Iterator<DBObject> it = collection.find(query).iterator();
	
	List<Pongo> pongoList = new ArrayList<Pongo>();
	
	while (it.hasNext()) {
		DBObject dbObject = it.next();
		pongoList.add(PongoFactory.getInstance().createPongo(dbObject));
	}
	
	return pongoList;
	
}