/** * 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); }
/** * 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)); }
@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())); } } }
@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); }
@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")); }
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(); }
/** * 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())); }); }
@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)); }); }
/** * 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; }
public boolean deleteAuthToken(String token, ObjectId clientId) { if (authTokenRepository.existsByIdAndAndClientId(token, clientId)) { authTokenRepository.deleteByIdAndClientId(token, clientId); return true; } else { return false; } }
@Override public SmartiUser addClient(String username, ObjectId id) { return mongoTemplate.findAndModify( byLogin(username), new Update().addToSet(SmartiUser.FIELD_CLIENTS, id), SmartiUser.class ); }
@Override public OracleToMongoGridFsMap generateIdIfAbsentFromDocument(OracleToMongoGridFsMap map) { if (!documentHasId(map)) { map.setMapId(new ObjectId()); } return map; }
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); }
/** 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"); }
@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()))); }
public boolean deleteMessage(ObjectId conversationId, String messageId) { final boolean success = conversationRepository.deleteMessage(conversationId, messageId); if (success) { final Conversation one = conversationRepository.findOne(conversationId); publishSaveEvent(updateQueries(null, one)); } return success; }
@Override public O2MSyncEventLog generateIdIfAbsentFromDocument(O2MSyncEventLog arg0) { if(!documentHasId(arg0)){ arg0.setLogId(new ObjectId()); } return arg0; }
public SyncConnectionInfo updateConnection(SyncConnectionInfo connInfo) { if(connInfo.getConnectionId() == null){ connInfo.setConnectionId(new ObjectId()); } return connectionInfo.findOneAndReplace( Filters.eq(String.valueOf(ConnectionInfoAttributes._id), connInfo.getConnectionId()), connInfo, new FindOneAndReplaceOptions().returnDocument(ReturnDocument.AFTER).upsert(true)); }
public OrclToMngWriter(BlockingQueue<List<Document>> dataBuffer, String mongoDbName, String mongoUserName, SyncMarker marker, ObjectId eventId, String collectionName, CountDownLatch latch) { super(); this.dataBuffer = dataBuffer; this.mongoUserName = mongoUserName; this.mongoDbName = mongoDbName; this.marker = marker; this.collectionName = collectionName; this.eventId = eventId; this.latch = latch; this.eventDao = new SyncEventDao(); }
@GET @Path("{id}") @Produces(MediaType.APPLICATION_JSON) public Response getGroupInfo(@PathParam("id") String id) { // Validate the JWT. At this point, anyone can get a group info if they // have a valid JWT. try { validateJWT(); } catch (JWTException jwte) { return Response.status(Status.UNAUTHORIZED) .type(MediaType.TEXT_PLAIN) .entity(jwte.getMessage()) .build(); } // Check if the id is a valid mongo object id. If not, the server will // throw a 500 if (!ObjectId.isValid(id)) { return Response.status(Status.BAD_REQUEST) .type(MediaType.TEXT_PLAIN) .entity("The group was not found") .build(); } // Query Mongo for group with specified id BasicDBObject group = (BasicDBObject) getGroupCollection().findOne(new ObjectId(id)); if (group == null) { return Response.status(Status.BAD_REQUEST) .type(MediaType.TEXT_PLAIN) .entity("The group was not found") .build(); } // Create a JSON payload with the group content String responsePayload = (new Group(group)).getJson(); return Response.ok().entity(responsePayload).build(); }
@ApiOperation(value = "delete a message", response = Conversation.class) @RequestMapping(value = "{conversationId}/message/{messageId}", method = RequestMethod.DELETE) public ResponseEntity<?> deleteMessage( AuthContext authContext, @PathVariable("conversationId") ObjectId conversationId, @PathVariable("messageId") String messageId) { authenticationService.hasAccessToConversation(authContext, conversationId); if (conversationService.deleteMessage(conversationId, messageId)) { return getConversation(authContext, conversationId); } else { return ResponseEntity.notFound().build(); } }
public static CombinedId random() { CombinedId combinedId = new CombinedId(); combinedId.idPart1 = "Hi " + randomGenerator.nextInt(); combinedId.idPart2 = new ObjectId(); combinedId.idPart3 = new BsonTimestamp(randomGenerator.nextInt(), 0); return combinedId; }
@ApiOperation("revoke an auth-token") @RequestMapping(value = "{id}/token/{token}", method = RequestMethod.DELETE) public ResponseEntity<?> revokeAuthToken(AuthContext authContext, @PathVariable("id") ObjectId id, @PathVariable("token") String tokenId) { final Client client = authenticationService.assertClient(authContext, id); if (authTokenService.deleteAuthToken(tokenId, client.getId())) { return ResponseEntity.noContent().build(); } else { return ResponseEntity.notFound().build(); } }
@Override public Conversation updateConversationStatus(ObjectId conversationId, ConversationMeta.Status status) { final Query query = new Query(Criteria.where("_id").is(conversationId)); final Update update = new Update() .set("meta.status", status) .currentDate("lastModified"); mongoTemplate.updateFirst(query, update, Conversation.class); return mongoTemplate.findById(conversationId, Conversation.class); }
@Override public void deleteCommentById(String commentId) { Story story = mongoTemplate.findOne(new Query(Criteria.where("comments.id").is(new ObjectId(commentId))), Story.class); story.deleteCommentById(commentId); mongoTemplate.save(story); }
@Override public Conversation adjustMessageVotes(ObjectId conversationId, String messageId, int delta) { final Query query = new Query(Criteria.where("_id").is(conversationId)) .addCriteria(Criteria.where("messages._id").is(messageId)); final Update update = new Update() .inc("messages.$.votes", delta); mongoTemplate.updateFirst(query, update, Conversation.class); return mongoTemplate.findById(conversationId, Conversation.class); }
@Test public void likeAndDislikeTest() throws IOException { BsonElement rateID = new BsonElement("ratingOnObjectOfId", new BsonObjectId(new ObjectId("58d1c36efb0cac4e15afd203"))); Document metadataDoc = new Document(); List<BsonElement> rateInfo = new ArrayList<>(); List<BsonValue> rateWrapper = new ArrayList<>(); rateInfo.add(like); rateInfo.add(rateID); BsonDocument rate = new BsonDocument(rateInfo); rateWrapper.add(rate); rateInfo = new ArrayList<>(); rateInfo.add(dislike); rateInfo.add(rateID); rate = new BsonDocument(rateInfo); rateWrapper.add(rate); BsonArray ratings = new BsonArray(rateWrapper); metadataDoc.append("pageViews", 0); metadataDoc.append("ratings", ratings); metadataDoc.append("comments", new BsonArray()); Document searchQuery = new Document("_id", new ObjectId("58d1c36efb0cac4e15afd203")); Document updateThingy = new Document("$set", new Document("metadata", metadataDoc)); // updateThingy.append("$set", new Document().append("metadata", metadataDoc)); plants.updateOne(searchQuery, updateThingy); String expect = "{ \"interactionCount\" : 2}"; String plant = plantController.getFeedbackForPlantByPlantID("16008.0", "first uploadId"); assertEquals("Incorrect interaction count for plant 16008.0", expect, plant); }
@Test public void testDuplicateKeyFailureOrderedFalse() throws Exception { final TestRunner runner = TestRunners.newTestRunner(new StoreInMongo()); addMongoService(runner); runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME); runner.setProperty(MongoProps.COLLECTION, "insert_test"); runner.setProperty(MongoProps.BATCH_SIZE, "10"); runner.setProperty(MongoProps.ORDERED, "false"); ObjectId objectId = ObjectId.get(); String success = FileUtils.readFileToString(Paths.get("src/test/resources/payload.json").toFile()); String successTwo = "{\"a\":\"a\"}"; String payloadOne = "{\"_id\":\"" + objectId.toString() + "\", \"text\": \"first value\"}"; String payloadTwo = "{\"_id\":\"" + objectId.toString() + "\", \"text\": \"second value\"}"; runner.enqueue(payloadOne.getBytes()); runner.enqueue(success.getBytes()); runner.enqueue(payloadTwo.getBytes()); runner.enqueue(successTwo.getBytes()); // add another successful message runner.run(); runner.assertTransferCount(AbstractMongoProcessor.REL_FAILURE, 1); runner.assertTransferCount(AbstractMongoProcessor.REL_SUCCESS, 3); FlowFile failure = runner.getFlowFilesForRelationship(AbstractMongoProcessor.REL_FAILURE).get(0); String errorCode = failure.getAttribute("mongo.errorcode"); assertEquals("11000", errorCode); // duplicate key error code String errorMessage = failure.getAttribute("mongo.errormessage"); assertTrue(StringUtils.isNotBlank(errorMessage)); // Test contents of mongo MongoCollection<Document> collection = mongo.getMongoClient().getDatabase(MONGO_DATABASE_NAME).getCollection("insert_test"); assertEquals(3L, collection.count()); }
/** * Create a group based on a Mongo DB Object * * @param group The existing Mongo DB Object */ public Group(DBObject group) { this.id = ((ObjectId) group.get(DB_ID)).toString(); this.name = (String) group.get(JSON_KEY_GROUP_NAME); BasicDBList dbMembers = ((BasicDBList) group.get(JSON_KEY_MEMBERS_LIST)); this.members = new String[dbMembers.size()]; for (int i = 0; i < dbMembers.size(); i++) { members[i] = (String) dbMembers.get(i); } }
@ApiOperation(value = "delete a client") @RequestMapping(value = "{id}", method = RequestMethod.DELETE) public ResponseEntity<?> deleteClient(AuthContext authContext, @PathVariable("id") ObjectId id) throws IOException { authenticationService.assertRole(authContext, AuthenticationService.ADMIN); if(clientService.exists(id)) { clientService.delete(clientService.get(id)); return ResponseEntity.ok().build(); } else return ResponseEntities.status(404, "client does not exist"); }
@GET @Path("{id}") @Produces(MediaType.APPLICATION_JSON) public Response retrieveOccasion(@PathParam("id") String id) { String method = "retrieveOccasion"; logger.entering(clazz, method, id); // Validate the JWT. At this point, anyone can get an occasion if they // have a valid JWT. try { validateJWT(); } catch (JWTException jwte) { logger.exiting(clazz, method, Status.UNAUTHORIZED); return Response.status(Status.UNAUTHORIZED) .type(MediaType.TEXT_PLAIN) .entity(jwte.getMessage()) .build(); } Response response; // Ensure we recieved a valid ID if (!ObjectId.isValid(id)) { response = Response.status(400).entity("Invalid occasion id").build(); } else { // perform the query and return the occasion, if we find one DBObject occasion = getCollection().findOne(new BasicDBObject(Occasion.OCCASION_ID_KEY, new ObjectId(id))); logger.fine("In " + method + " with Occasion: \n\n" + occasion); String occasionJson = new Occasion(occasion).toString(); if (null == occasionJson || occasionJson.isEmpty()) { response = Response.status(400).entity("no occasion found for given id").build(); } else { response = Response.ok(occasionJson, MediaType.APPLICATION_JSON).build(); } } logger.exiting(clazz, method, response); return response; }
/** * Delete a customer. * <p> * This method is idempotent, if it's called multiples times with the same * id then the first call will delete the customer and subsequent calls will * be silently ignored. * * @param id * The id of the customer to delete. * @return HTTP 204 */ @PreAuthorize("#oauth2.hasAnyScope('write','read-write')") @RequestMapping(method = DELETE, value = "/{id}") public Mono<ResponseEntity<?>> deleteCustomer(@PathVariable @NotNull ObjectId id) { final Mono<ResponseEntity<?>> noContent = Mono.just(noContent().build()); return repo.existsById(id) .filter(Boolean::valueOf) // Delete only if customer exists .flatMap(exists -> repo.deleteById(id).then(noContent)) .switchIfEmpty(noContent); }
@Test public void getNonExistingUserWithValidId() { FindOne findOne = mock(FindOne.class); when(collection.findOne(any(ObjectId.class))).thenReturn(findOne); when(findOne.as(User.class)).thenReturn(null); User user = sut.getUserById("507f1f77bcf86cd799439011"); verify(collection, times(1)).findOne(any(ObjectId.class)); verify(findOne, times(1)).as(User.class); assertNull(user); }
/** * Get Operator Id * * @param agentId Agent id * @return Operator id */ public String getOperatorIdByAgent(String agentId) { if (!ObjectId.isValid(agentId)) { return null; } Document doc = this.database.getCollection("user_assets_info").find(eq("agent_id", new ObjectId(agentId))) .projection(include("user_id")) .first(); if (doc == null) return null; return doc.getObjectId("user_id").toString(); }
@ApiOperation(value = "import conversations") @RequestMapping(value = "import", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE) public ResponseEntity<?> importConversations( AuthContext authContext, @RequestParam("owner") ObjectId owner, @RequestParam(value = "replace", defaultValue = "false", required = false) boolean replace, @RequestBody List<Conversation> conversations ) { if (authenticationService.hasAccessToClient(authContext, owner)) { conversationService.importConversations(owner, conversations, replace); return ResponseEntity.noContent().build(); } else { return ResponseEntity.badRequest().build(); } }
public static void checkBsonTest(BsonTest bsonTest) { Assert.assertEquals(20.99, bsonTest.getTestDouble(), 0); Assert.assertEquals("testStringV", bsonTest.getTestString()); Assert.assertNotNull(bsonTest.getTestArray()); for (BsonTest innerTestObj : bsonTest.getTestArray()) { Assert.assertEquals(20.777, innerTestObj.getTestDouble(), 0); Assert.assertNull(innerTestObj.getTestString()); } Assert.assertNotNull(bsonTest.getBsonTest()); BsonTest testHasTest = bsonTest.getBsonTest(); BsonTest expected = new BsonTest(); expected.setTestDouble(20.99); expected.setTestString("testStringV"); ArrayList<BsonTest> testArray = new ArrayList<BsonTest>(); BsonTest arrayInner = new BsonTest(); arrayInner.setTestDouble(20.777); testArray.add(arrayInner); testArray.add(arrayInner); expected.setTestArray(testArray); Assert.assertEquals(expected, testHasTest); byte[] bytes = new byte[3]; bytes[0] = 3; bytes[1] = 2; bytes[2] = 1; Assert.assertEquals(new Binary(bytes), bsonTest.getTestBinary()); Assert.assertNotNull(bsonTest.getTestObjectId()); Assert.assertTrue(bsonTest.getTestObjectId().getClass() == ObjectId.class); Assert.assertNotNull(bsonTest.getTestStringObjectId()); Assert.assertNull(bsonTest.getTestIgnore()); Assert.assertTrue(bsonTest.isTestBoolean()); Assert.assertEquals(new Date(time), bsonTest.getTestDate()); Assert.assertEquals(null, bsonTest.getTestNull()); Assert.assertTrue(bsonTest.getTestInt() == 233); Assert.assertTrue(bsonTest.getTestLong() == 233332L); }
@Test public void shouldDeleteAnExistingCustomer() throws Exception { given(repo.existsById(any(ObjectId.class))).willReturn(Mono.just(true)); given(repo.deleteById(any(ObjectId.class))).willReturn(Mono.empty()); final URI uri = URI.create(String.format("/customers/%s", ObjectId.get())); webClient.delete().uri(uri).exchange().expectStatus().isNoContent(); }
@Test public void shouldReturnOneCustomerById() { // Given final Customer customer = Customer.ofType(PERSON).build(); when(repo.findById(any(ObjectId.class))).thenReturn(Mono.just(customer)); // When final ResponseEntity<Customer> response = controller.oneCustomer(ObjectId.get()).block(); // Then assertThat(response.getStatusCode()).isEqualTo(OK); assertThat((Customer) response.getBody()).isEqualTo(customer); }
@Override public boolean deleteMessage(ObjectId conversationId, String messageId) { final Query query = new Query(Criteria.where("_id").is(conversationId)); final Update update = new Update() .pull("messages", new BasicDBObject("_id", messageId)) .currentDate("lastModified"); final WriteResult result = mongoTemplate.updateFirst(query, update, Conversation.class); return result.getN() == 1; }
@Override public SyncMap generateIdIfAbsentFromDocument(SyncMap map) { if (!documentHasId(map)) { map.setMapId(new ObjectId()); } return map; }