当前位置: 首页>>代码示例>>Java>>正文


Java ObjectId类代码示例

本文整理汇总了Java中org.bson.types.ObjectId的典型用法代码示例。如果您正苦于以下问题:Java ObjectId类的具体用法?Java ObjectId怎么用?Java ObjectId使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


ObjectId类属于org.bson.types包,在下文中一共展示了ObjectId类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testDeleteGroup

import org.bson.types.ObjectId; //导入依赖的package包/类
/**
 * Add a new group object to the database. Call DELETE using the id of the new mongo object.
 * Verify that the group no longer exists in the database
 *
 * @throws GeneralSecurityException
 */
@Test
public void testDeleteGroup() throws IOException, GeneralSecurityException {
  System.out.println("\nStarting testDeleteGroup");

  // Create group in database
  Group group = new Group(null, "testGroup", new String[] {"12345"});
  BasicDBObject dbGroup = group.getDBObject(false);
  db.getCollection(Group.DB_COLLECTION_NAME).insert(dbGroup);
  group.setId(dbGroup.getObjectId(Group.DB_ID).toString());

  ObjectId groupId = dbGroup.getObjectId(Group.DB_ID);
  // Make DELETE call with group id
  String url = groupServiceURL + "/" + groupId;
  makeConnection("DELETE", url, null, 200);

  // Verify that the group no longer exists in mongo
  BasicDBObject groupAfterDelete = (BasicDBObject) db.getCollection("groups").findOne(groupId);
  assertNull("The group still exists after DELETE was called", groupAfterDelete);
}
 
开发者ID:OpenLiberty,项目名称:sample-acmegifts,代码行数:26,代码来源:GroupResourceTest.java

示例2: successfulInputOfComment

import org.bson.types.ObjectId; //导入依赖的package包/类
@Test
public void successfulInputOfComment() throws IOException {
    String json = "{ plantId: \"58d1c36efb0cac4e15afd278\", comment : \"Here is our comment for this test\" }";

    assertTrue(plantController.addComment(json, "second uploadId"));

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection<Document> plants = db.getCollection("plants");

    Document filterDoc = new Document();

    filterDoc.append("_id", new ObjectId("58d1c36efb0cac4e15afd278"));
    filterDoc.append("uploadID", "second uploadId");

    Iterator<Document> iter = plants.find(filterDoc).iterator();

    Document plant = iter.next();
    List<Document> plantComments = (List<Document>) ((Document) plant.get("metadata")).get("comments");
    long comments = plantComments.size();

    assertEquals(1, comments);
    assertEquals("Here is our comment for this test", plantComments.get(0).getString("comment"));
    assertNotNull(plantComments.get(0).getObjectId("_id"));
  }
 
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-4-dorfner-v2,代码行数:26,代码来源:TestPlantComment.java

示例3: addBedVisit

import org.bson.types.ObjectId; //导入依赖的package包/类
/**
 * When a user views a web page a Bed page a Bed Visit is added.
 * By that we mean that bed's pageViews field is incremented and a new {visit : ObjectId()} is added to visits
 * @param gardenLocation
 * @param uploadId
 * @return
 */
public boolean addBedVisit(String gardenLocation, String uploadId) {

    Document filterDoc = new Document();
    filterDoc.append("gardenLocation", gardenLocation);
    filterDoc.append("uploadId", uploadId);

    Document visit = new Document();
    visit.append("visit", new ObjectId());

    incrementBedMetadata(gardenLocation, "pageViews", uploadId);

    return null != bedCollection.findOneAndUpdate(filterDoc, push("metadata.bedVisits", visit));
}
 
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-4-revolverenguardia-1,代码行数:21,代码来源:BedController.java

示例4: setQuery

import org.bson.types.ObjectId; //导入依赖的package包/类
@Override
public void setQuery(DBObject query, BasicDBList orList) {
	// if (null == orList) {
	// query.put(this.name, value.getValue());
	// } else {
	// orList.add(new BasicDBObject(this.name, value.getValue()));
	// }

	if (this.name.equals("_id")) {
		if (null == orList) {
			query.put(this.name, new ObjectId(value.getValue().toString()));
		} else {
			orList.add(new BasicDBObject(this.name, new ObjectId(value.getValue().toString())));
		}
	} else {
		if (null == orList) {
			query.put(this.name, value.getValue());
		} else {
			orList.add(new BasicDBObject(this.name, value.getValue()));
		}
	}
}
 
开发者ID:xsonorg,项目名称:tangyuan2,代码行数:23,代码来源:EqualCondition.java

示例5: AddFlowerRatingReturnsTrueWithValidJsonInput

import org.bson.types.ObjectId; //导入依赖的package包/类
@Test
public void AddFlowerRatingReturnsTrueWithValidJsonInput() throws IOException{

    String json = "{like: true, id: \"58d1c36efb0cac4e15afd202\"}";

    assertTrue(plantController.addFlowerRating(json, "first uploadId") instanceof ObjectId);

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection plants = db.getCollection("plants");

    FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();

    List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
    assertEquals(1, ratings.size());

    Document rating = ratings.get(0);
    assertTrue(rating.getBoolean("like"));
    assertTrue(rating.get("id") instanceof ObjectId);
}
 
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-4-dorfner-v2,代码行数:23,代码来源:FlowerRating.java

示例6: getCityItem

import org.bson.types.ObjectId; //导入依赖的package包/类
public static CityItem getCityItem(String id)
    {
        MongoCollection<BasicDBObject> collection = Configurator.INSTANCE.getDatabase().getCollection(COLLECTION,BasicDBObject.class);
        BasicDBObject query = new BasicDBObject();
        query.append("_id",new ObjectId(id));
        BasicDBObject result = collection.find(query).first();
        JSONObject json = new JSONObject(result.toJson());
        CityItem.Builder builder = new CityItem.Builder();

        builder.id(id);
        builder.type(json.getInt("type"));
        builder.description(json.getString("description"));

        JSONObject location = json.getJSONObject("location");
        builder.longitude(location.getDouble("x"));
        builder.latitude(location.getDouble("y"));

//        JSONObject report = json.getJSONObject("report");
//        builder.priority(report.getString("priority"));
//        builder.comment(report.getString("comment"));
//        builder.resolved(report.getBoolean("resolved"));
//        builder.report_date(new Date(report.getLong("report_date")));
//        builder.resolve_date(new Date(report.getLong("resolve_date")));

        return builder.build();
    }
 
开发者ID:Labas-Vakaras,项目名称:Smart_City,代码行数:27,代码来源:CityItemDAO.java

示例7: updateCustomer

import org.bson.types.ObjectId; //导入依赖的package包/类
/**
 * Update an existing customer.
 * <p>
 * This method is idempotent.
 * <p>
 * 
 * @param id
 *            The id of the customer to update.
 * @param update
 *            The Customer object containing the updated version to be
 *            persisted.
 * 
 * @return HTTP 204 otherwise HTTP 400 if the customer does not exist.
 */
@PreAuthorize("#oauth2.hasAnyScope('write','read-write')")
@RequestMapping(method = PUT, value = "/{id}", consumes = { APPLICATION_JSON_UTF8_VALUE })
public Mono<ResponseEntity<?>> updateCustomer(@PathVariable @NotNull ObjectId id,
		@RequestBody @Valid Customer customerToUpdate) {

	return repo.existsById(id).flatMap(exists -> {

		if (!exists) {
			throw new CustomerServiceException(HttpStatus.BAD_REQUEST,
				"Customer does not exist, to create a new customer use POST instead.");
		}

		return repo.save(customerToUpdate).then(Mono.just(noContent().build()));
	});
}
 
开发者ID:dserradji,项目名称:reactive-customer-service,代码行数:30,代码来源:CustomerController.java

示例8: shouldReturnOneCustomerById

import org.bson.types.ObjectId; //导入依赖的package包/类
@Test
public void shouldReturnOneCustomerById() throws Exception {

	final LocalDate birthDate = LocalDate.of(1990, Month.JULY, 31);
	final Customer mockCustomer = Customer.ofType(PERSON).withBirthDate(birthDate).build();
	final ObjectId id = ObjectId.get();

	given(repo.findById(any(ObjectId.class))).willReturn(Mono.just(mockCustomer));

	webClient.get().uri(String.format("/customers/%s", id)).accept(APPLICATION_JSON_UTF8).exchange()
		.expectStatus().isOk()	// HTTP 200
		.expectBody(Customer.class)
		.consumeWith(customer -> {
			assertThat(customer.getResponseBody().getCustomerType()).isEqualTo(PERSON);
			assertThat(customer.getResponseBody().getBirthDate()).isEqualTo(LocalDate.of(1990, 07, 31));
		});
}
 
开发者ID:dserradji,项目名称:reactive-customer-service,代码行数:18,代码来源:CustomerControllerWebTest.java

示例9: addBedQRVisit

import org.bson.types.ObjectId; //导入依赖的package包/类
/**
 * When a user scans a QR code, that QR code brings them to a page that sends a POST request
 * to the server whose body contains which gardenLocation was visited via QR Code.
 *
 * This function is responsible for incrementing qrScans and adding a {scan : ObjectId()} to metadata.qrVisits
 *
 * @param gardenLocation
 * @param uploadId
 * @return
 */
public boolean addBedQRVisit(String gardenLocation, String uploadId) {

    Document filterDoc = new Document();
    filterDoc.append("gardenLocation", gardenLocation);
    filterDoc.append("uploadId", uploadId);

    Document visit = new Document();
    visit.append("visit", new ObjectId());

    Document scan = new Document();
    scan.append("scan", new ObjectId());

    incrementBedMetadata(gardenLocation, "pageViews", uploadId);
    incrementBedMetadata(gardenLocation, "qrScans", uploadId);

    Document a = bedCollection.findOneAndUpdate(filterDoc, push("metadata.bedVisits", visit));
    if(a == null)
        return false;
    Document b = bedCollection.findOneAndUpdate(filterDoc, push("metadata.qrVisits", scan));

    return null != b;
}
 
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-4-revolverenguardia-1,代码行数:33,代码来源:BedController.java

示例10: deleteAuthToken

import org.bson.types.ObjectId; //导入依赖的package包/类
public boolean deleteAuthToken(String token, ObjectId clientId) {
    if (authTokenRepository.existsByIdAndAndClientId(token, clientId)) {
        authTokenRepository.deleteByIdAndClientId(token, clientId);
        return true;
    } else {
        return false;
    }
}
 
开发者ID:redlink-gmbh,项目名称:smarti,代码行数:9,代码来源:AuthTokenService.java

示例11: addClient

import org.bson.types.ObjectId; //导入依赖的package包/类
@Override
public SmartiUser addClient(String username, ObjectId id) {
    return mongoTemplate.findAndModify(
            byLogin(username),
            new Update().addToSet(SmartiUser.FIELD_CLIENTS, id),
            SmartiUser.class
    );
}
 
开发者ID:redlink-gmbh,项目名称:smarti,代码行数:9,代码来源:UserRepositoryImpl.java

示例12: generateIdIfAbsentFromDocument

import org.bson.types.ObjectId; //导入依赖的package包/类
@Override
public OracleToMongoGridFsMap generateIdIfAbsentFromDocument(OracleToMongoGridFsMap map) {
	if (!documentHasId(map)) {
		map.setMapId(new ObjectId());
	}
	return map;
}
 
开发者ID:gagoyal01,项目名称:mongodb-rdbms-sync,代码行数:8,代码来源:OrclToMongoGridFsMapCodec.java

示例13: MngToOrclSyncWriter

import org.bson.types.ObjectId; //导入依赖的package包/类
public MngToOrclSyncWriter(BlockingQueue<Document> dataBuffer, MongoToOracleMap map, SyncMarker marker,
		CountDownLatch latch, boolean isRestrictedSyncEnabled, ObjectId eventId) {
	super();
	this.dataBuffer = dataBuffer;
	this.map = map;
	this.marker = marker;
	this.latch = latch;
	this.isRestrictedSyncEnabled = isRestrictedSyncEnabled;
	this.eventId = eventId;
	this.options = new FindOneAndUpdateOptions();
	options.returnDocument(ReturnDocument.BEFORE);
}
 
开发者ID:gagoyal01,项目名称:mongodb-rdbms-sync,代码行数:13,代码来源:MngToOrclSyncWriter.java

示例14: testPOSTWithId

import org.bson.types.ObjectId; //导入依赖的package包/类
/** Similar to testPOST, but this test sends a payload with an id field */
@Test(expected = IllegalArgumentException.class)
public void testPOSTWithId() {
  logger.entering(
      clazz, name.getMethodName(), "\n\n+ + + + + Entering " + name.getMethodName() + "\n\n");

  // build the json payload
  List<Occasion.Contribution> contributions = new ArrayList<>();
  contributions.add(new Occasion.Contribution("0004", 21));
  contributions.add(new Occasion.Contribution("0005", 51));
  contributions.add(new Occasion.Contribution("0006", 52));
  Occasion occasion =
      new Occasion(
          /* ID            */ new ObjectId("1000"),
          /* date          */ "2117-07-31",
          /* group ID      */ "0002",
          /* interval      */ "annual",
          /* occasion name */ "John Doe's Birthday",
          /* organizer ID  */ "0004",
          /* recipient ID  */ "0006",
          contributions);

  // expecting 400 because POST is for creating a new occasion and should not include an ID
  testEndpointJson("/", "POST", occasion.toString(), "IllegalArgumentException", 400);

  logger.exiting(
      clazz, name.getMethodName(), "\n\n- - - - - Exiting " + name.getMethodName() + "\n\n");
}
 
开发者ID:OpenLiberty,项目名称:sample-acmegifts,代码行数:29,代码来源:OccasionResourceTest.java

示例15: getAtiveUserStoriesTest

import org.bson.types.ObjectId; //导入依赖的package包/类
@Test
public void getAtiveUserStoriesTest() throws Exception {
    String dashboardName = "mirrorgate";
    String sprintProjectName = "mirrorgate";

    Dashboard dashboard = new Dashboard();
    dashboard.setId(ObjectId.get());
    dashboard.setName(dashboardName);
    dashboard.setsProductName(sprintProjectName);
    dashboard.setBoards(Arrays.asList(sprintProjectName));

    Feature story1 = new Feature();
    story1.setId(ObjectId.get());
    story1.setsId("1");
    story1.setsSprintAssetState("Active");
    story1.setsProjectName(dashboardName);

    Feature story2= new Feature();
    story2.setId(ObjectId.get());
    story2.setsId("2");
    story2.setsSprintAssetState("Active");
    story2.setsProjectName(dashboardName);

    List<Feature> stories = new ArrayList<>();
    stories.add(story1);
    stories.add(story2);

    when(dashboardService.getDashboard(dashboardName)).thenReturn(map(dashboard));
    when(featureService.getActiveUserStoriesByBoards(Arrays.asList(dashboardName)))
            .thenReturn(stories);

    this.mockMvc.perform(get("/dashboards/" + dashboardName + "/stories"))
            .andExpect(status().isOk())
        .andExpect(jsonPath("$.currentSprint[0].sId", equalTo(story1.getsId())))
        .andExpect(jsonPath("$.currentSprint[0].sSprintAssetState", equalTo(story1.getsSprintAssetState())))
        .andExpect(jsonPath("$.currentSprint[0].sProjectName", equalTo(story1.getsProjectName())))
        .andExpect(jsonPath("$.currentSprint[1].sId", equalTo(story2.getsId())))
        .andExpect(jsonPath("$.currentSprint[1].sSprintAssetState", equalTo(story2.getsSprintAssetState())))
        .andExpect(jsonPath("$.currentSprint[1].sProjectName", equalTo(story2.getsProjectName())));
}
 
开发者ID:BBVA,项目名称:mirrorgate,代码行数:41,代码来源:FeatureControllerTests.java


注:本文中的org.bson.types.ObjectId类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。