下面列出了com.mongodb.DBCollection#save ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
/**
* Uses the '.+' regexp on featureId to allow for symbols such as slashes in the id
*
* @param featureId String The featureId to make changes to
* @return DBObjet Returns the the features new state if changes were made and returns null if bad JSON was sent
*/
@PUT
@Path("/{product}/{major}.{minor}.{servicePack}/{build}/{featureId:.+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response putFeature(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId,
final BasicDBObject feature) {
feature.put("calculatedStatus", StatusHelper.getFeatureStatus(feature));
final DBCollection collection = this.mongoLegacyDb.getCollection("features");
final BasicDBObject example = coordinates.getReportCoordinatesQueryObject().append("id", featureId);
final DBObject report = collection.findOne(example);
// get the differences/new edits
// Detect if the edits caused a change
feature.put("statusLastEditedBy", LoggedInUserUtil.getLoggedInUser().getDisplay());
feature.put("lastEditOn", new Date());
final BasicDBList edits = updateEdits(feature, report);
feature.put("edits", edits);
updateTestingTips(this.mongoLegacyDb, coordinates, featureId, feature); // save testing tips / strip them out of the document.
updateEnvironmentDetails(this.mongoLegacyDb, coordinates, feature);
collection.save(feature);
Feature.embedTestingTips(feature, coordinates, this.mongoLegacyDb); // rembed testing tips.
return Response.ok(SerializerUtil.serialise(feature))
.build();// pull back feature - will re-include tips that were extracted prior to saving
}
@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();
}
public static void testMongoUserId(int max, DB db) {
String collName = "testmongobjid";
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();
for ( int i=0; i<max; i++ ) {
BasicDBObject obj = new BasicDBObject();
obj.put("test", "value-"+i);
coll.save(obj);
}
long endM = System.currentTimeMillis();
System.out.println("Insert " + max + " mongo objectid. time: " + (endM-startM) + " benchmark()");
CommandResult result = db.getStats();
System.out.println(result);
}
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);
}
@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);
}
@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"));
}
@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();
}
}
@PUT
@Path("/step/{product}/{major}.{minor}.{servicePack}/{build}/{featureId:.+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateStepWithPatch(@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 int stepLine = (int) patch.get("line");
final String status = (String) patch.get("status");
final String scenarioId = (String) patch.get("scenarioId");
final BasicDBObject featureToUpdate = (BasicDBObject) storedFeature.copy();
final BasicDBObject scenarioToUpdate = getScenarioById(scenarioId, featureToUpdate);
boolean found = false;
if (scenarioToUpdate.get("background") != null) {
final BasicDBObject backgroundToUpdate = (BasicDBObject) (scenarioToUpdate.get("background"));
final BasicDBList backgroundStepsToUpdate = (BasicDBList) (backgroundToUpdate.get("steps"));
found = updateSteps(backgroundStepsToUpdate, stepLine, status);
}
if (!found) {
final BasicDBList stepsToUpdate = (BasicDBList) (scenarioToUpdate.get("steps"));
updateSteps(stepsToUpdate, stepLine, status);
}
featureToUpdate.put("statusLastEditedBy", LoggedInUserUtil.getLoggedInUser().getDisplay());
featureToUpdate.put("lastEditOn", new Date());
featureToUpdate.put("calculatedStatus", calculateStatusForFeature(featureToUpdate));
collection.save(featureToUpdate);
return Response.ok().build();
} catch (final Throwable th) {
th.printStackTrace();
return Response.serverError().build();
}
}
@PUT
@Path("/steps/{product}/{major}.{minor}.{servicePack}/{build}/{featureId:.+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateStepsWithPatch(@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 status = (String) patch.get("status");
final String scenarioId = (String) patch.get("scenarioId");
final BasicDBObject featureToUpdate = (BasicDBObject) storedFeature.copy();
final BasicDBObject scenarioToUpdate = getScenarioById(scenarioId, featureToUpdate);
if (scenarioToUpdate.get("background") != null) {
final BasicDBObject backgroundToUpdate = (BasicDBObject) (scenarioToUpdate.get("background"));
final BasicDBList backgroundStepsToUpdate = (BasicDBList) (backgroundToUpdate.get("steps"));
updateAllSteps(backgroundStepsToUpdate, status);
}
if (scenarioToUpdate.get("steps") != null) {
final BasicDBList stepsToUpdate = (BasicDBList) (scenarioToUpdate.get("steps"));
updateAllSteps(stepsToUpdate, status);
}
featureToUpdate.put("statusLastEditedBy", LoggedInUserUtil.getLoggedInUser().getDisplay());
featureToUpdate.put("lastEditOn", new Date());
featureToUpdate.put("calculatedStatus", calculateStatusForFeature(featureToUpdate));
collection.save(featureToUpdate);
return Response.ok().build();
} catch (final Throwable th) {
th.printStackTrace();
return Response.serverError().build();
}
}
public static void testMyUserId(int max, DB db) {
String collName = "testmyuserid";
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 obj = new BasicDBObject();
for ( int i=0; i<max; i++ ) {
UserId userId = new UserId("username"+i);
obj.put("_id", userId.getInternal());
obj.put("test", "value-"+i);
coll.save(obj);
}
long endM = System.currentTimeMillis();
System.out.println("Insert " + max + " my objectid. time: " + (endM-startM) + " benchmark()");
CommandResult result = db.getStats();
System.out.println(result);
}
public static void testStringUserId(int max, DB db) {
String collName = "teststringid";
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 obj = new BasicDBObject();
for ( int i=0; i<max; i++ ) {
obj.put("_id", "username"+i);
obj.put("test", "value-"+i);
coll.save(obj);
}
long endM = System.currentTimeMillis();
System.out.println("Insert " + max + " my objectid. time: " + (endM-startM) + " benchmark()");
CommandResult result = db.getStats();
System.out.println(result);
}
@Test
public void testRascalDatatable() throws Exception {
// Create test data
DB db = mongo.getDB("rascalloc");
DBCollection collection = db.getCollection("locperlanguage");
Calendar cal = Calendar.getInstance();
for (int i = 0; i < 10; i++) {
ListMeasurement list = new ListMeasurement();
for (String lang : new String[]{"HTML", "Java", "PHP"}) {
StringMeasurement l = new StringMeasurement();
l.setValue(lang);
IntegerMeasurement loc = new IntegerMeasurement();
loc.setValue(3);
TupleMeasurement tuple = new TupleMeasurement();
tuple.getValue().add(l);
tuple.getValue().add(loc);
list.getValue().add(tuple);
}
DBObject obj = list.getDbObject();
obj.put("__date", new org.eclipse.scava.platform.Date(cal.getTime()).toString());
obj.put("__datetime", cal.getTime());
collection.save(obj);
cal.add(Calendar.DATE, 1);
}
JsonNode node = ChartUtil.loadJsonFile("data/rascalloc.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);
// Tidy up
mongo.dropDatabase("rascalloc");
}
public JSONObject authorize(String projectId, String authToken, String... roles) {
JSONObject response = new JSONObject();
if(authToken == null){
return response.put(SUCCESS, false).put("msg", UNAUTHORIZED);
}
List<String> roleList = Arrays.asList(roles);
DBCollection dbCollection = mongoTemplate.getCollection(ENTITY_AUTH);
BasicDBObject queryObject = new BasicDBObject();
queryObject.append("_id", new ObjectId(authToken));
DBObject authData = dbCollection.findOne(queryObject);
if(authData != null && projectId.equals(authData.get("projectId"))) {
DBRef userRef = (DBRef)authData.get("user");
DBObject user = mongoTemplate.getCollection(userRef.getCollectionName()).findOne(userRef.getId());
DBObject roleObj = null;
if(user.containsField("role")){
DBRef roleRef = (DBRef)user.get("role");
roleObj = mongoTemplate.getCollection(roleRef.getCollectionName()).findOne(roleRef.getId());
}
if((roleObj != null && roleList.contains(roleObj.get("name"))) || roleList.contains("USER")){
response.put(SUCCESS, true);
response.put("user", userRef);
authData.put("expireAt", new Date(System.currentTimeMillis() + 3600 * 1000));
dbCollection.save(authData);
} else {
response.put(SUCCESS, false).put("msg", UNAUTHORIZED);
}
} else {
response.put(SUCCESS, false).put("msg", UNAUTHORIZED);
}
return response;
}