com.mongodb.DBCollection Java Examples

The following examples show how to use com.mongodb.DBCollection. 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: InitialSetupMigration.java    From spring-boot-completablefuture with MIT License 7 votes vote down vote up
@ChangeSet(order = "01",
           author = "developer",
           id = "01-addUsers")
public void addUsers(final DB db) {
    final DBCollection userCollection = db.getCollection(User.COLLECTION_NAME);

    userCollection.insert(BasicDBObjectBuilder
                                  .start()
                                  .add(FIELD_NAME_ID, new ObjectId("590f86d92449343841cc2c3f"))
                                  .add(User.FIELD_NAME_FIRST_NAME, "User")
                                  .add(User.FIELD_NAME_LAST_NAME, "One")
                                  .add(User.FIELD_NAME_EMAIL, "[email protected]")
                                  .get());

    userCollection.insert(BasicDBObjectBuilder
                                  .start()
                                  .add(FIELD_NAME_ID, new ObjectId("590f86d92449343841cc2c40"))
                                  .add(User.FIELD_NAME_FIRST_NAME, "User")
                                  .add(User.FIELD_NAME_LAST_NAME, "Two")
                                  .add(User.FIELD_NAME_EMAIL, "[email protected]")
                                  .get());
}
 
Example #2
Source File: RawMetricResource.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private ArrayNode getHistoricDocuments(DBCollection dbCollection, DBObject query) {
	ObjectMapper mapper = new ObjectMapper();
	ArrayNode nodeArray = mapper.createArrayNode();		
	DBCursor cursor = dbCollection.find(query);
	while(cursor.hasNext()) {
		DBObject obj = cursor.next();
		JsonNode json;
		try {
			json = mapper.readTree(obj.toString());
			nodeArray.add(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return nodeArray;
}
 
Example #3
Source File: MongoUtil.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Find a DBObject from database using the query. If the ‘fields' argument is null, 
 * then return the whole document. Otherwise, only returns given fields.
 * 
 * This method uses reflection to convert the result DBObject into given Object.
 * 
 * @param query The query condition
 * @param databaseName The database name
 * @param namespace The collection namespace
 * @param collection The collection name
 * @param filterFields The fields that will be returned.
 * @return
 */
public static final Object queryObjectFromMongo(DBObject query, String databaseName,
		String namespace, String collection, DBObject filterFields) {
	
	DBCollection coll = getDBCollection(databaseName, namespace, collection);
	DBObject dbObject = null;
	if ( filterFields != null ) {
		dbObject = coll.findOne(query, filterFields);
	} else {
		dbObject = coll.findOne(query);
	}
	if ( dbObject != null ) {
		return constructObject(dbObject);
	} else {
		return null;
	}
}
 
Example #4
Source File: TagView.java    From XBDD with Apache License 2.0 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/featureTagIndex/{product}/{major}.{minor}.{servicePack}/{build}")
public Response getFeatureTagIndexForReport(@BeanParam final Coordinates coordinates,
		@QueryParam("searchText") final String searchText, @QueryParam("viewPassed") final Integer viewPassed,
		@QueryParam("viewFailed") final Integer viewFailed,
		@QueryParam("viewUndefined") final Integer viewUndefined, @QueryParam("viewSkipped") final Integer viewSkipped,
		@QueryParam("start") final String start) {

	final DBCollection featuresCollection = this.mongoLegacyDb.getCollection("features");

	final BasicDBObject query = QueryBuilder.getInstance().buildFilterQuery(coordinates, searchText, viewPassed,
			viewFailed, viewUndefined, viewSkipped, start);

	query.append("$and", QueryBuilder.getInstance().buildHasTagsQuery());

	final DBCursor results = featuresCollection.find(query,
			new BasicDBObject("tags", 1).append("elements.tags", 1).append("name", 1).append("calculatedStatus", 1)
					.append("id", 1).append("elements.steps", 1).append("elements.name", 1).append("elements.id", 1));

	return Response.ok(SerializerUtil.serialise(getTagList(results))).build();
}
 
Example #5
Source File: CsvCombine.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Create a neutral record from a dbElement of a base collection.
 * Initiates recursive parsing of sub tables filling the neutralRecord map.
 */
private NeutralRecord createNeutralRecord(DBObject dbElement, String entityName,
        List<DBCollection> supportingCollections) {

    NeutralRecord record = new NeutralRecord();
    record.setRecordType(entityName);

    int joinKey = Integer.parseInt(dbElement.get("JoinKey").toString());
    try {
        Map<String, Object> attributes = parseDbElement(dbElement, joinKey, entityName, supportingCollections);
        record.setAttributes(attributes);
    } catch (Exception e) {
        e.printStackTrace();
        PRINT_STREAM.println("invalid collection format for entity type " + entityName);
    }

    return record;
}
 
Example #6
Source File: MarcMongodbClientTest.java    From metadata-qa-marc with GNU General Public License v3.0 6 votes vote down vote up
public void testFindOne() throws UnknownHostException {
  MarcMongodbClient client = new MarcMongodbClient("localhost" , 27017, "sub_last_print");
  DBCollection collection = client.getCollection("marc");
  BasicDBObject doc = createTestObject();
  collection.insert(doc);
  assertEquals(1, collection.count());
  DBObject myDoc = collection.findOne();
  assertEquals("MongoDB", myDoc.get("name"));
  assertEquals("database", myDoc.get("type"));
  assertEquals(1, myDoc.get("count"));
  assertEquals(BasicDBObject.class, myDoc.get("info").getClass());
  assertEquals(new BasicDBObject("x", 203).append("y", 102), myDoc.get("info"));
  assertEquals(203, ((BasicDBObject)myDoc.get("info")).get("x"));
  assertEquals(Integer.class, ((BasicDBObject)myDoc.get("info")).get("x").getClass());
  System.out.println(myDoc);
  collection.remove(new BasicDBObject("name", "MongoDB"));
}
 
Example #7
Source File: MongoNativeExtractor.java    From deep-spark with Apache License 2.0 6 votes vote down vote up
/**
 * Gets shards.
 *
 * @param collection the collection
 * @return the shards
 */
private Map<String, String[]> getShards(DBCollection collection) {
    DB config = collection.getDB().getSisterDB("config");
    DBCollection configShards = config.getCollection("shards");

    DBCursor cursorShards = configShards.find();

    Map<String, String[]> map = new HashMap<>();
    while (cursorShards.hasNext()) {
        DBObject currentShard = cursorShards.next();
        String currentHost = (String) currentShard.get("host");
        int slashIndex = currentHost.indexOf("/");
        if (slashIndex > 0) {
            map.put((String) currentShard.get(MONGO_DEFAULT_ID),
                    currentHost.substring(slashIndex + 1).split(","));
        }
    }
    return map;
}
 
Example #8
Source File: FeatureRepositoryCustomImplTest.java    From osiris with Apache License 2.0 6 votes vote down vote up
@Test
public void saveIndexAndFeatureByAppIdTest() throws Exception{
	
	String idApplication = "1";  
	//Fixture
	Feature feature=Mockito.mock(Feature.class);
	DBCollection dbCollection=Mockito.mock(DBCollection.class);
	BasicDBObject obj=Mockito.mock(BasicDBObject.class);
	Mockito.when(mongoTemplate.collectionExists(collectionName+idApplication)).thenReturn(false);
	Mockito.when(mongoTemplate.getCollection(collectionName+idApplication)).thenReturn(dbCollection);
	PowerMockito.whenNew(BasicDBObject.class).withNoArguments().thenReturn(obj);
	Mockito.when(obj.put("geometry", "2dsphere")).thenReturn(dbCollection);
	
	//Experimentation
	featureRepository.save(idApplication, feature);
	//Expectation
	Mockito.verify(mongoTemplate).collectionExists(collectionName+idApplication);
	Mockito.verify(mongoTemplate).save(feature,collectionName+idApplication);
}
 
Example #9
Source File: CsvCombine.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public List<NeutralRecord> getNeutralRecordsFromCollection(String entityName) {
    PRINT_STREAM.println("importing from collection " + entityName);

    List<NeutralRecord> records = new ArrayList<NeutralRecord>();

    // Get a list of all the collections in the staging DB
    Set<String> allCollections = db.getCollectionNames();
    List<DBCollection> dbSupportingCollections = new ArrayList<DBCollection>();
    Iterator<String> it = allCollections.iterator();
    while (it.hasNext()) {
        dbSupportingCollections.add(db.getCollection(it.next().toString()));
    }

    // Get the data in the primary (entityName) collection.
    DBCollection dbCollection = db.getCollection(entityName);
    DBCursor cursor = dbCollection.find();

    // Create the neutral record on a entry-by-entry basis
    while (cursor.hasNext()) {
        records.add(createNeutralRecord(cursor.next(), entityName, dbSupportingCollections));
    }

    return records;
}
 
Example #10
Source File: RawStorageInterceptor.java    From hvdf with Apache License 2.0 6 votes vote down vote up
public void pushSample(DBObject sample, boolean isList, BasicDBList resultList) {
	
	if(isList){
		
		// Use the batch API to send a number of samples
		storeBatch((BasicDBList)sample, resultList);			
	}
	else if(sample != null){
		
		// Create an oid to embed the sample time
		BasicDBObject doc = ((BasicDBObject) sample);
		SampleId _id = this.idFactory.createId(sample);
		sample.put(Sample.ID_KEY, _id.toObject());
		resultList.add(_id.toObject());

		// Get the correct slice from the allocator and insert
		long timestamp = doc.getLong(Sample.TS_KEY);
		DBCollection collection = collectionAllocator.getCollection(timestamp);
		collection.insert(doc);
	}
}
 
Example #11
Source File: Tailer.java    From zerowing with MIT License 6 votes vote down vote up
private DBCursor createCursor() {
  DBCollection oplog = _mongo.getDB("local").getCollection("oplog.rs");
  BSONTimestamp startingTimestamp = getStartingTimestamp();

  DBCursor cursor;
  if (startingTimestamp == null) {
    log.info("Tailing the oplog from the beginning...");
    cursor = oplog.find();
  } else {
    log.info("Tailing the oplog from " + startingTimestamp);
    BasicDBObject query = new BasicDBObject("ts", new BasicDBObject("$gt", startingTimestamp));
    cursor = oplog.find(query);
    cursor.addOption(Bytes.QUERYOPTION_OPLOGREPLAY);
  }

  cursor.addOption(Bytes.QUERYOPTION_NOTIMEOUT);
  cursor.addOption(Bytes.QUERYOPTION_TAILABLE);
  cursor.addOption(Bytes.QUERYOPTION_AWAITDATA);

  return cursor;
}
 
Example #12
Source File: RdbmsDeleteTest.java    From kafka-connect-mongodb with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("when valid cdc event with single field PK then correct DeleteOneModel")
public void testValidSinkDocumentSingleFieldPK() {

    BsonDocument filterDoc =
            new BsonDocument(DBCollection.ID_FIELD_NAME,
                    new BsonDocument("id",new BsonInt32(1004)));

    BsonDocument keyDoc = new BsonDocument("id",new BsonInt32(1004));
    BsonDocument valueDoc = new BsonDocument("op",new BsonString("d"));

    WriteModel<BsonDocument> result =
            RDBMS_DELETE.perform(new SinkDocument(keyDoc,valueDoc));

    assertTrue(result instanceof DeleteOneModel,
            () -> "result expected to be of type DeleteOneModel");

    DeleteOneModel<BsonDocument> writeModel =
            (DeleteOneModel<BsonDocument>) result;

    assertTrue(writeModel.getFilter() instanceof BsonDocument,
            () -> "filter expected to be of type BsonDocument");

    assertEquals(filterDoc,writeModel.getFilter());

}
 
Example #13
Source File: UserResource.java    From XBDD with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/ignoredTags/{product}")
@Consumes(MediaType.APPLICATION_JSON)
public Response putIgnoredTags(@BeanParam final Coordinates coordinates, final BasicDBObject patch) {
	final DBCollection collection = this.mongoLegacyDb.getCollection("ignoredTags");
	final BasicDBObject coq = coordinates.getProductCoordinatesQueryObject();
	final BasicDBObject storedDocument = (BasicDBObject) collection.findOne(coq);

	final String tagName = (String) patch.get("tagName");

	if (storedDocument != null) {
		final BasicDBObject documentToUpdate = (BasicDBObject) storedDocument.copy();
		updateIgnoredTag(documentToUpdate, tagName);
		collection.save(documentToUpdate);
	} else {
		final DBObject newDocument = generateNewIgnoredTags(coordinates, tagName);
		collection.save(newDocument);
	}
	return Response.ok().build();
}
 
Example #14
Source File: MongoStoreTest.java    From todo-apps with Apache License 2.0 6 votes vote down vote up
@Test
public void testPersist() {
	DBCollection coll = createMockCollection();
	ToDo td = new ToDo();
	td.setTitle("This is a test");
	td.setId("aaaaaaaaaaaaaaaaaaaaaaa1");
	expect(coll.insert(isA(DBObject.class))).andAnswer(new IAnswer<WriteResult>() {
		@Override
		public WriteResult answer() throws Throwable {
			DBObject obj = (DBObject)getCurrentArguments()[0];
			obj.put("_id", new ObjectId("aaaaaaaaaaaaaaaaaaaaaaa1"));
			return null;
		}
	});
	replay(coll);
	MongoStore store = new MongoStore(coll);
	assertEquals(td, store.persist(td));
	verify(coll);
}
 
Example #15
Source File: DatabaseSpec.java    From bdt with Apache License 2.0 6 votes vote down vote up
/**
 * Execute a query on (mongo) database
 *
 * @param query         path to query
 * @param type          type of data in query (string or json)
 * @param collection    collection in database
 * @param modifications modifications to perform in query
 */
@When("^I execute a query '(.+?)' of type '(json|string)' in mongo '(.+?)' database using collection '(.+?)' with:$")
public void sendQueryOfType(String query, String type, String database, String collection, DataTable modifications) throws Exception {
    try {
        commonspec.setResultsType("mongo");
        String retrievedData = commonspec.retrieveData(query, type);
        String modifiedData = commonspec.modifyData(retrievedData, type, modifications);
        commonspec.getMongoDBClient().connectToMongoDBDataBase(database);
        DBCollection dbCollection = commonspec.getMongoDBClient().getMongoDBCollection(collection);
        DBObject dbObject = (DBObject) JSON.parse(modifiedData);
        DBCursor cursor = dbCollection.find(dbObject);
        commonspec.setMongoResults(cursor);
    } catch (Exception e) {
        commonspec.getExceptions().add(e);
    }
}
 
Example #16
Source File: FeatureRepositoryCustomImplTest.java    From osiris with Apache License 2.0 6 votes vote down vote up
@Test(expected=MongoGeospatialException.class)
public void shouldThrowErrorWhenGeospatialIndexNotCreated() throws Exception{
	
	String idApplication = "1";  
	//Fixture
	Feature feature=Mockito.mock(Feature.class);
	DBCollection dbCollection=Mockito.mock(DBCollection.class);
	BasicDBObject obj=Mockito.mock(BasicDBObject.class);
	Mockito.when(mongoTemplate.collectionExists(collectionName+idApplication)).thenReturn(false);
	Mockito.when(mongoTemplate.getCollection(collectionName+idApplication)).thenReturn(dbCollection);
	PowerMockito.whenNew(BasicDBObject.class).withNoArguments().thenReturn(obj);
	Mockito.doThrow(UncategorizedMongoDbException.class).when(mongoTemplate).save(feature,collectionName+idApplication);
	//Experimentation
	featureRepository.save(idApplication, feature);
	//Expectation
	Mockito.verify(mongoTemplate).collectionExists(collectionName+idApplication);
	Mockito.verify(mongoTemplate).save(feature,collectionName+idApplication);
}
 
Example #17
Source File: KmeansClulsterCalulator.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private Map<String, Float> readDistanceScores(String object) {
	Map<String, Float> result = new HashMap<String, Float>();
	Query query = new org.springframework.data.mongodb.core.query.Query();
	query.addCriteria(Criteria.where("type.name").is(sm.getSimilarityName())
			.orOperator(Criteria.where("fromArtifact.$id").is(new ObjectId(object)), 
					    Criteria.where("toArtifact.$id").is(new ObjectId(object))));
	DBCollection dbCollection = mongoTemplate.getCollection("relation");
    DBCursor cursor = dbCollection.find(query.getQueryObject());
    List<DBObject> list = cursor.toArray();
    for (DBObject dbObject : list) {
		String toArtifact = ((DBRef)dbObject.get("toArtifact")).getId().toString();
		String fromArtifact = ((DBRef)dbObject.get("fromArtifact")).getId().toString();
		double value = ((double)dbObject.get("value"));
		if (toArtifact.equals(object))  
			result.put(fromArtifact, (float) (1 - value));
		else 
			result.put(toArtifact, (float) (1 - value));
	}
	return result;
}
 
Example #18
Source File: MongoNodeGroupStore.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
public MongoNodeGroupStore(Config config) {
    super(config);
    setTableName(JobQueueUtils.NODE_GROUP_STORE);

    // create table
    DBCollection dbCollection = template.getCollection();
    List<DBObject> indexInfo = dbCollection.getIndexInfo();
    // create index if not exist
    if (CollectionUtils.sizeOf(indexInfo) <= 1) {
        template.ensureIndex("idx_nodeType_name", "nodeType,name", true, true);
    }
}
 
Example #19
Source File: MongoDBTestHelper.java    From brooklyn-library with 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 #20
Source File: MetricHistoryManager.java    From scava with 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 #21
Source File: SelectVo.java    From tangyuan2 with GNU General Public License v3.0 5 votes vote down vote up
public Object selectVar(DBCollection collection) {
	if (null == this.count) {
		DBObject result = selectOne(collection);
		return result;
	} else {
		return getQueryCount(collection);
	}
}
 
Example #22
Source File: MongoExecutableJobQueue.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
@Override
public boolean removeQueue(String taskTrackerNodeGroup) {
    String tableName = JobQueueUtils.getExecutableQueueName(taskTrackerNodeGroup);
    DBCollection dbCollection = template.getCollection(tableName);
    dbCollection.drop();
    LOGGER.info("drop queue " + tableName);

    return true;
}
 
Example #23
Source File: MetricVisualisation.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private DBCollection getCollection(DB db) {
	// TODO: Look up metric provider and get collection name from there.
	// 		 If we're visualising transients, this may need amending 
	
	String id = metricId.replace("org.eclipse.scava.metricprovider.", "");
	if (db.getCollection(id).count() == 0) {
		System.err.println("ERROR: Could not find collection: " + metricId);
	}
	
	DBCollection collection = db.getCollection(id);
	return collection;
}
 
Example #24
Source File: ChartTest.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDatatableWithoutRowDefinition() throws Exception {
	DBCollection collection = ChartUtil.getCollection(mongo, "Epsilon","org.eclipse.scava.metricprovider.historic.commitsovertime.CommitsOverTimeHistoricMetricProvider");
	JsonNode node = ChartUtil.loadJsonFile("data/commitsovertime.json");
	
	ArrayNode vis = (ArrayNode) node.get("vis");
	JsonNode datatable = vis.get(0).get("datatable");
	
	Chart chart = ChartUtil.loadChart("charts/linechart.json");
	ArrayNode table = chart.createDatatable(datatable, collection, null);
	System.out.println(table);
}
 
Example #25
Source File: Environment.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{product}")
public Response getEnvironmentsForProduct(@PathParam("product") final String product) {
	final DBCollection collection = this.mongoLegacyDb.getCollection("environments");
	final DBObject rtn = collection.findOne(new BasicDBObject("coordinates.product", product));

	return Response.ok(SerializerUtil.serialise(rtn)).build();
}
 
Example #26
Source File: Feature.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/comments/{product}/{major}.{minor}.{servicePack}/{build}/{featureId:.+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateCommentWithPatch(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId,
		final BasicDBObject patch) {
	try {
		final DBCollection collection = this.mongoLegacyDb.getCollection("features");
		final BasicDBObject example = coordinates.getReportCoordinatesQueryObject().append("id", featureId);
		final BasicDBObject storedFeature = (BasicDBObject) collection.findOne(example);

		final String scenarioId = (String) patch.get("scenarioId");
		final String label = (String) patch.get("label");
		final String content = (String) patch.get("content");

		final BasicDBObject featureToUpdate = (BasicDBObject) storedFeature.copy();
		final BasicDBObject scenarioToUpdate = getScenarioById(scenarioId, featureToUpdate);
		scenarioToUpdate.put(label, content);

		if (label.equals("testing-tips")) {
			final DBCollection tips = this.mongoLegacyDb.getCollection("testingTips");
			updateTestingTipsForScenario(tips, scenarioToUpdate, coordinates, featureId);
		}
		featureToUpdate.put("statusLastEditedBy", LoggedInUserUtil.getLoggedInUser().getDisplay());
		featureToUpdate.put("lastEditOn", new Date());
		featureToUpdate.put("calculatedStatus", calculateStatusForFeature(featureToUpdate));
		collection.save(featureToUpdate);
		if (label.equals("testing-tips")) {
			Feature.embedTestingTips(featureToUpdate, coordinates, this.mongoLegacyDb);
		}
		return Response.ok().build();
	} catch (final Throwable th) {
		th.printStackTrace();
		return Response.serverError().build();
	}

}
 
Example #27
Source File: DocumentIdAdderTest.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("test _id field added by IdStrategy")
public void testAddingIdFieldByStrategy() {

    BsonValue fakeId = mock(BsonValue.class);

    IdStrategy ids = mock(IdStrategy.class);
    when(ids.generateId(any(SinkDocument.class), ArgumentMatchers.isNull()))
            .thenReturn(fakeId);

    DocumentIdAdder idAdder = new DocumentIdAdder(null,ids,"");
    SinkDocument sinkDocWithValueDoc = new SinkDocument(null,new BsonDocument());
    SinkDocument sinkDocWithoutValueDoc = new SinkDocument(null,null);

    assertAll("check for _id field when processing DocumentIdAdder",
            () -> {
                idAdder.process(sinkDocWithValueDoc,null);
                assertAll("_id checks",
                        () ->  assertTrue(sinkDocWithValueDoc.getValueDoc().orElseGet(() -> new BsonDocument())
                                        .keySet().contains(DBCollection.ID_FIELD_NAME),
                                "must contain _id field in valueDoc"
                        ),
                        () -> assertTrue(sinkDocWithValueDoc.getValueDoc().orElseGet(() -> new BsonDocument())
                               .get(DBCollection.ID_FIELD_NAME) instanceof BsonValue,
                        "_id field must be of type BsonValue")
                );
            },
            () -> {
                idAdder.process(sinkDocWithoutValueDoc,null);
                assertTrue(!sinkDocWithoutValueDoc.getValueDoc().isPresent(),
                        "no _id added since valueDoc cannot not be present"
                );
            }
    );

}
 
Example #28
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public static void testMapDBObject(int max, DB db) {
	String collName = "testmapobject";
	DBCollection coll = db.getCollection(collName);
	
	//Setup a sharded collection
	BasicDBObject command = new BasicDBObject();
	command.put("shardcollection", collName);
	DBObject key = new BasicDBObject();
	key.put("_id", 1);
	command.put("key", key);
	command.put("unique", true);
	db.command(command);
	
	long startM = System.currentTimeMillis();
	BasicDBObject objKey = new BasicDBObject();
	UserId userId = new UserId("username");
	objKey.put("_id", userId.getInternal());
	
	MapDBObject obj = new MapDBObject();
	for ( int i=0; i<max; i++ ) {
		obj.put("_id", userId.getInternal());
		obj.put("test-"+(i)%10, "value-"+i);
		coll.update(objKey, obj, true, false);
	}
	long endM = System.currentTimeMillis();
	
	System.out.println(collName+ " update " + max + " my objectid. time: " + (endM-startM) + " benchmark(114892)");
	
	CommandResult result = db.getStats();
	System.out.println(result);
}
 
Example #29
Source File: WriteModelStrategyTest.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("when sink document is valid for ReplaceOneDefaultStrategy then correct ReplaceOneModel")
public void testReplaceOneDefaultStrategyWithValidSinkDocument() {

    BsonDocument valueDoc = new BsonDocument(DBCollection.ID_FIELD_NAME,new BsonInt32(1004))
            .append("first_name",new BsonString("Anne"))
            .append("last_name",new BsonString("Kretchmar"))
            .append("email",new BsonString("[email protected]"));

    WriteModel<BsonDocument> result =
            REPLACE_ONE_DEFAULT_STRATEGY.createWriteModel(new SinkDocument(null,valueDoc));

    assertTrue(result instanceof ReplaceOneModel,
            () -> "result expected to be of type ReplaceOneModel");

    ReplaceOneModel<BsonDocument> writeModel =
            (ReplaceOneModel<BsonDocument>) result;

    assertEquals(REPLACEMENT_DOC_DEFAULT,writeModel.getReplacement(),
            ()-> "replacement doc not matching what is expected");

    assertTrue(writeModel.getFilter() instanceof BsonDocument,
            () -> "filter expected to be of type BsonDocument");

    assertEquals(FILTER_DOC_REPLACE_DEFAULT,writeModel.getFilter());

    assertTrue(writeModel.getOptions().isUpsert(),
            () -> "replacement expected to be done in upsert mode");

}
 
Example #30
Source File: MongodbSourceApplicationTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@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"));
}