Browse Source

DATAMONGO-1858 - Fix line endings to LF.

pull/530/merge
Mark Paluch 8 years ago
parent
commit
07731c39ba
  1. 428
      spring-data-mongodb-cross-store/src/main/java/org/springframework/data/mongodb/crossstore/MongoChangeSetPersister.java
  2. 210
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceReplicaSetTests.java
  3. 478
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceTests.java
  4. 122
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoAdminIntegrationTests.java
  5. 192
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/PersonExample.java
  6. 80
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/PersonExampleAppConfig.java
  7. 146
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Portfolio.java
  8. 120
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Trade.java
  9. 142
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/User.java
  10. 132
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Venue.java
  11. 178
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DSphereTests.java
  12. 158
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DTests.java
  13. 100
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/GeoIndexedAppConfig.java
  14. 432
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/CriteriaTests.java
  15. 190
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/IndexUnitTests.java
  16. 108
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/SortTests.java
  17. 142
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/monitor/MongoMonitorIntegrationTests.java

428
spring-data-mongodb-cross-store/src/main/java/org/springframework/data/mongodb/crossstore/MongoChangeSetPersister.java

@ -1,214 +1,214 @@
/* /*
* Copyright 2011-2017 the original author or authors. * Copyright 2011-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.crossstore; package org.springframework.data.mongodb.crossstore;
import javax.persistence.EntityManagerFactory; import javax.persistence.EntityManagerFactory;
import org.bson.Document; import org.bson.Document;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.crossstore.ChangeSet; import org.springframework.data.crossstore.ChangeSet;
import org.springframework.data.crossstore.ChangeSetBacked; import org.springframework.data.crossstore.ChangeSetBacked;
import org.springframework.data.crossstore.ChangeSetPersister; import org.springframework.data.crossstore.ChangeSetPersister;
import org.springframework.data.mongodb.core.CollectionCallback; import org.springframework.data.mongodb.core.CollectionCallback;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import com.mongodb.MongoException; import com.mongodb.MongoException;
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters; import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.DeleteResult;
/** /**
* @author Thomas Risberg * @author Thomas Risberg
* @author Oliver Gierke * @author Oliver Gierke
* @author Alex Vengrovsk * @author Alex Vengrovsk
* @author Mark Paluch * @author Mark Paluch
* @deprecated will be removed without replacement. * @deprecated will be removed without replacement.
*/ */
@Deprecated @Deprecated
public class MongoChangeSetPersister implements ChangeSetPersister<Object> { public class MongoChangeSetPersister implements ChangeSetPersister<Object> {
private static final String ENTITY_CLASS = "_entity_class"; private static final String ENTITY_CLASS = "_entity_class";
private static final String ENTITY_ID = "_entity_id"; private static final String ENTITY_ID = "_entity_id";
private static final String ENTITY_FIELD_NAME = "_entity_field_name"; private static final String ENTITY_FIELD_NAME = "_entity_field_name";
private static final String ENTITY_FIELD_CLASS = "_entity_field_class"; private static final String ENTITY_FIELD_CLASS = "_entity_field_class";
private final Logger log = LoggerFactory.getLogger(getClass()); private final Logger log = LoggerFactory.getLogger(getClass());
private MongoTemplate mongoTemplate; private MongoTemplate mongoTemplate;
private EntityManagerFactory entityManagerFactory; private EntityManagerFactory entityManagerFactory;
public void setMongoTemplate(MongoTemplate mongoTemplate) { public void setMongoTemplate(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate; this.mongoTemplate = mongoTemplate;
} }
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) { public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory; this.entityManagerFactory = entityManagerFactory;
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see org.springframework.data.crossstore.ChangeSetPersister#getPersistentState(java.lang.Class, java.lang.Object, org.springframework.data.crossstore.ChangeSet) * @see org.springframework.data.crossstore.ChangeSetPersister#getPersistentState(java.lang.Class, java.lang.Object, org.springframework.data.crossstore.ChangeSet)
*/ */
public void getPersistentState(Class<? extends ChangeSetBacked> entityClass, Object id, final ChangeSet changeSet) public void getPersistentState(Class<? extends ChangeSetBacked> entityClass, Object id, final ChangeSet changeSet)
throws DataAccessException, NotFoundException { throws DataAccessException, NotFoundException {
if (id == null) { if (id == null) {
log.debug("Unable to load MongoDB data for null id"); log.debug("Unable to load MongoDB data for null id");
return; return;
} }
String collName = getCollectionNameForEntity(entityClass); String collName = getCollectionNameForEntity(entityClass);
final Document dbk = new Document(); final Document dbk = new Document();
dbk.put(ENTITY_ID, id); dbk.put(ENTITY_ID, id);
dbk.put(ENTITY_CLASS, entityClass.getName()); dbk.put(ENTITY_CLASS, entityClass.getName());
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Loading MongoDB data for {}", dbk); log.debug("Loading MongoDB data for {}", dbk);
} }
mongoTemplate.execute(collName, new CollectionCallback<Object>() { mongoTemplate.execute(collName, new CollectionCallback<Object>() {
public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException { public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
for (Document dbo : collection.find(dbk)) { for (Document dbo : collection.find(dbk)) {
String key = (String) dbo.get(ENTITY_FIELD_NAME); String key = (String) dbo.get(ENTITY_FIELD_NAME);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Processing key: {}", key); log.debug("Processing key: {}", key);
} }
if (!changeSet.getValues().containsKey(key)) { if (!changeSet.getValues().containsKey(key)) {
String className = (String) dbo.get(ENTITY_FIELD_CLASS); String className = (String) dbo.get(ENTITY_FIELD_CLASS);
if (className == null) { if (className == null) {
throw new DataIntegrityViolationException( throw new DataIntegrityViolationException(
"Unble to convert property " + key + ": Invalid metadata, " + ENTITY_FIELD_CLASS + " not available"); "Unble to convert property " + key + ": Invalid metadata, " + ENTITY_FIELD_CLASS + " not available");
} }
Class<?> clazz = ClassUtils.resolveClassName(className, ClassUtils.getDefaultClassLoader()); Class<?> clazz = ClassUtils.resolveClassName(className, ClassUtils.getDefaultClassLoader());
Object value = mongoTemplate.getConverter().read(clazz, dbo); Object value = mongoTemplate.getConverter().read(clazz, dbo);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Adding to ChangeSet: {}", key); log.debug("Adding to ChangeSet: {}", key);
} }
changeSet.set(key, value); changeSet.set(key, value);
} }
} }
return null; return null;
} }
}); });
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see org.springframework.data.crossstore.ChangeSetPersister#getPersistentId(org.springframework.data.crossstore.ChangeSetBacked, org.springframework.data.crossstore.ChangeSet) * @see org.springframework.data.crossstore.ChangeSetPersister#getPersistentId(org.springframework.data.crossstore.ChangeSetBacked, org.springframework.data.crossstore.ChangeSet)
*/ */
public Object getPersistentId(ChangeSetBacked entity, ChangeSet cs) throws DataAccessException { public Object getPersistentId(ChangeSetBacked entity, ChangeSet cs) throws DataAccessException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("getPersistentId called on {}", entity); log.debug("getPersistentId called on {}", entity);
} }
if (entityManagerFactory == null) { if (entityManagerFactory == null) {
throw new DataAccessResourceFailureException("EntityManagerFactory cannot be null"); throw new DataAccessResourceFailureException("EntityManagerFactory cannot be null");
} }
return entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity); return entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see org.springframework.data.crossstore.ChangeSetPersister#persistState(org.springframework.data.crossstore.ChangeSetBacked, org.springframework.data.crossstore.ChangeSet) * @see org.springframework.data.crossstore.ChangeSetPersister#persistState(org.springframework.data.crossstore.ChangeSetBacked, org.springframework.data.crossstore.ChangeSet)
*/ */
public Object persistState(ChangeSetBacked entity, ChangeSet cs) throws DataAccessException { public Object persistState(ChangeSetBacked entity, ChangeSet cs) throws DataAccessException {
if (cs == null) { if (cs == null) {
log.debug("Flush: changeset was null, nothing to flush."); log.debug("Flush: changeset was null, nothing to flush.");
return 0L; return 0L;
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Flush: changeset: {}", cs.getValues()); log.debug("Flush: changeset: {}", cs.getValues());
} }
String collName = getCollectionNameForEntity(entity.getClass()); String collName = getCollectionNameForEntity(entity.getClass());
if (mongoTemplate.getCollection(collName) == null) { if (mongoTemplate.getCollection(collName) == null) {
mongoTemplate.createCollection(collName); mongoTemplate.createCollection(collName);
} }
for (String key : cs.getValues().keySet()) { for (String key : cs.getValues().keySet()) {
if (key != null && !key.startsWith("_") && !key.equals(ChangeSetPersister.ID_KEY)) { if (key != null && !key.startsWith("_") && !key.equals(ChangeSetPersister.ID_KEY)) {
Object value = cs.getValues().get(key); Object value = cs.getValues().get(key);
final Document dbQuery = new Document(); final Document dbQuery = new Document();
dbQuery.put(ENTITY_ID, getPersistentId(entity, cs)); dbQuery.put(ENTITY_ID, getPersistentId(entity, cs));
dbQuery.put(ENTITY_CLASS, entity.getClass().getName()); dbQuery.put(ENTITY_CLASS, entity.getClass().getName());
dbQuery.put(ENTITY_FIELD_NAME, key); dbQuery.put(ENTITY_FIELD_NAME, key);
final Document dbId = mongoTemplate.execute(collName, new CollectionCallback<Document>() { final Document dbId = mongoTemplate.execute(collName, new CollectionCallback<Document>() {
public Document doInCollection(MongoCollection<Document> collection) public Document doInCollection(MongoCollection<Document> collection)
throws MongoException, DataAccessException { throws MongoException, DataAccessException {
Document id = collection.find(dbQuery).first(); Document id = collection.find(dbQuery).first();
return id; return id;
} }
}); });
if (value == null) { if (value == null) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Flush: removing: {}", dbQuery); log.debug("Flush: removing: {}", dbQuery);
} }
mongoTemplate.execute(collName, new CollectionCallback<Object>() { mongoTemplate.execute(collName, new CollectionCallback<Object>() {
public Object doInCollection(MongoCollection<Document> collection) public Object doInCollection(MongoCollection<Document> collection)
throws MongoException, DataAccessException { throws MongoException, DataAccessException {
DeleteResult dr = collection.deleteMany(dbQuery); DeleteResult dr = collection.deleteMany(dbQuery);
return null; return null;
} }
}); });
} else { } else {
final Document dbDoc = new Document(); final Document dbDoc = new Document();
dbDoc.putAll(dbQuery); dbDoc.putAll(dbQuery);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Flush: saving: {}", dbQuery); log.debug("Flush: saving: {}", dbQuery);
} }
mongoTemplate.getConverter().write(value, dbDoc); mongoTemplate.getConverter().write(value, dbDoc);
dbDoc.put(ENTITY_FIELD_CLASS, value.getClass().getName()); dbDoc.put(ENTITY_FIELD_CLASS, value.getClass().getName());
if (dbId != null) { if (dbId != null) {
dbDoc.put("_id", dbId.get("_id")); dbDoc.put("_id", dbId.get("_id"));
} }
mongoTemplate.execute(collName, new CollectionCallback<Object>() { mongoTemplate.execute(collName, new CollectionCallback<Object>() {
public Object doInCollection(MongoCollection<Document> collection) public Object doInCollection(MongoCollection<Document> collection)
throws MongoException, DataAccessException { throws MongoException, DataAccessException {
if (dbId != null) { if (dbId != null) {
collection.replaceOne(Filters.eq("_id", dbId.get("_id")), dbDoc); collection.replaceOne(Filters.eq("_id", dbId.get("_id")), dbDoc);
} else { } else {
if (dbDoc.containsKey("_id") && dbDoc.get("_id") == null) { if (dbDoc.containsKey("_id") && dbDoc.get("_id") == null) {
dbDoc.remove("_id"); dbDoc.remove("_id");
} }
collection.insertOne(dbDoc); collection.insertOne(dbDoc);
} }
return null; return null;
} }
}); });
} }
} }
} }
return 0L; return 0L;
} }
/** /**
* Returns the collection the given entity type shall be persisted to. * Returns the collection the given entity type shall be persisted to.
* *
* @param entityClass must not be {@literal null}. * @param entityClass must not be {@literal null}.
* @return * @return
*/ */
private String getCollectionNameForEntity(Class<? extends ChangeSetBacked> entityClass) { private String getCollectionNameForEntity(Class<? extends ChangeSetBacked> entityClass) {
return mongoTemplate.getCollectionName(entityClass); return mongoTemplate.getCollectionName(entityClass);
} }
} }

210
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceReplicaSetTests.java

@ -1,105 +1,105 @@
/* /*
* Copyright 2011-2016 the original author or authors. * Copyright 2011-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.config; package org.springframework.data.mongodb.config;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import java.net.InetAddress; import java.net.InetAddress;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.mongodb.MongoClient; import com.mongodb.MongoClient;
import org.bson.Document; import org.bson.Document;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.data.mongodb.core.MongoClientFactoryBean; import org.springframework.data.mongodb.core.MongoClientFactoryBean;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import com.mongodb.Mongo; import com.mongodb.Mongo;
import com.mongodb.ServerAddress; import com.mongodb.ServerAddress;
/** /**
* *
* @author Mark Pollack * @author Mark Pollack
* @author Oliver Gierke * @author Oliver Gierke
* @author Thomas Darimont * @author Thomas Darimont
* @author Mark Paluch * @author Mark Paluch
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration @ContextConfiguration
public class MongoNamespaceReplicaSetTests { public class MongoNamespaceReplicaSetTests {
@Autowired private ApplicationContext ctx; @Autowired private ApplicationContext ctx;
@Test @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testParsingMongoWithReplicaSets() throws Exception { public void testParsingMongoWithReplicaSets() throws Exception {
assertTrue(ctx.containsBean("replicaSetMongo")); assertTrue(ctx.containsBean("replicaSetMongo"));
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&replicaSetMongo"); MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&replicaSetMongo");
List<ServerAddress> replicaSetSeeds = (List<ServerAddress>) ReflectionTestUtils.getField(mfb, "replicaSetSeeds"); List<ServerAddress> replicaSetSeeds = (List<ServerAddress>) ReflectionTestUtils.getField(mfb, "replicaSetSeeds");
assertThat(replicaSetSeeds, is(notNullValue())); assertThat(replicaSetSeeds, is(notNullValue()));
assertThat(replicaSetSeeds, hasItems(new ServerAddress(InetAddress.getByName("127.0.0.1"), 10001), assertThat(replicaSetSeeds, hasItems(new ServerAddress(InetAddress.getByName("127.0.0.1"), 10001),
new ServerAddress(InetAddress.getByName("localhost"), 10002))); new ServerAddress(InetAddress.getByName("localhost"), 10002)));
} }
@Test @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testParsingWithPropertyPlaceHolder() throws Exception { public void testParsingWithPropertyPlaceHolder() throws Exception {
assertTrue(ctx.containsBean("manyReplicaSetMongo")); assertTrue(ctx.containsBean("manyReplicaSetMongo"));
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&manyReplicaSetMongo"); MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&manyReplicaSetMongo");
List<ServerAddress> replicaSetSeeds = (List<ServerAddress>) ReflectionTestUtils.getField(mfb, "replicaSetSeeds"); List<ServerAddress> replicaSetSeeds = (List<ServerAddress>) ReflectionTestUtils.getField(mfb, "replicaSetSeeds");
assertThat(replicaSetSeeds, is(notNullValue())); assertThat(replicaSetSeeds, is(notNullValue()));
assertThat(replicaSetSeeds, hasSize(3)); assertThat(replicaSetSeeds, hasSize(3));
List<Integer> ports = new ArrayList<Integer>(); List<Integer> ports = new ArrayList<Integer>();
for (ServerAddress replicaSetSeed : replicaSetSeeds) { for (ServerAddress replicaSetSeed : replicaSetSeeds) {
ports.add(replicaSetSeed.getPort()); ports.add(replicaSetSeed.getPort());
} }
assertThat(ports, hasItems(27017, 27018, 27019)); assertThat(ports, hasItems(27017, 27018, 27019));
} }
@Test @Test
@Ignore("CI infrastructure does not yet support replica sets") @Ignore("CI infrastructure does not yet support replica sets")
public void testMongoWithReplicaSets() { public void testMongoWithReplicaSets() {
MongoClient mongo = ctx.getBean(MongoClient.class); MongoClient mongo = ctx.getBean(MongoClient.class);
assertEquals(2, mongo.getAllAddress().size()); assertEquals(2, mongo.getAllAddress().size());
List<ServerAddress> servers = mongo.getAllAddress(); List<ServerAddress> servers = mongo.getAllAddress();
assertEquals("127.0.0.1", servers.get(0).getHost()); assertEquals("127.0.0.1", servers.get(0).getHost());
assertEquals("localhost", servers.get(1).getHost()); assertEquals("localhost", servers.get(1).getHost());
assertEquals(10001, servers.get(0).getPort()); assertEquals(10001, servers.get(0).getPort());
assertEquals(10002, servers.get(1).getPort()); assertEquals(10002, servers.get(1).getPort());
MongoTemplate template = new MongoTemplate(mongo, "admin"); MongoTemplate template = new MongoTemplate(mongo, "admin");
Document result = template.executeCommand("{replSetGetStatus : 1}"); Document result = template.executeCommand("{replSetGetStatus : 1}");
assertEquals("blort", result.get("set").toString()); assertEquals("blort", result.get("set").toString());
} }
} }

478
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceTests.java

@ -1,239 +1,239 @@
/* /*
* Copyright 2010-2017 the original author or authors. * Copyright 2010-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.config; package org.springframework.data.mongodb.config;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import static org.junit.Assume.*; import static org.junit.Assume.*;
import static org.springframework.data.mongodb.util.MongoClientVersion.*; import static org.springframework.data.mongodb.util.MongoClientVersion.*;
import static org.springframework.test.util.ReflectionTestUtils.*; import static org.springframework.test.util.ReflectionTestUtils.*;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.data.authentication.UserCredentials; import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoClientFactoryBean; import org.springframework.data.mongodb.core.MongoClientFactoryBean;
import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.convert.MongoConverter; import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.gridfs.GridFsOperations; import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mongodb.MongoClient; import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions; import com.mongodb.MongoClientOptions;
import com.mongodb.MongoOptions; import com.mongodb.MongoOptions;
import com.mongodb.WriteConcern; import com.mongodb.WriteConcern;
/** /**
* Integration tests for the MongoDB namespace. * Integration tests for the MongoDB namespace.
* *
* @author Mark Pollack * @author Mark Pollack
* @author Oliver Gierke * @author Oliver Gierke
* @author Martin Baumgartner * @author Martin Baumgartner
* @author Thomas Darimont * @author Thomas Darimont
* @author Christoph Strobl * @author Christoph Strobl
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration @ContextConfiguration
public class MongoNamespaceTests { public class MongoNamespaceTests {
@Autowired ApplicationContext ctx; @Autowired ApplicationContext ctx;
@Test @Test
public void testMongoSingleton() throws Exception { public void testMongoSingleton() throws Exception {
assertTrue(ctx.containsBean("noAttrMongo")); assertTrue(ctx.containsBean("noAttrMongo"));
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&noAttrMongo"); MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&noAttrMongo");
assertNull(getField(mfb, "host")); assertNull(getField(mfb, "host"));
assertNull(getField(mfb, "port")); assertNull(getField(mfb, "port"));
} }
@Test @Test
public void testMongoSingletonWithAttributes() throws Exception { public void testMongoSingletonWithAttributes() throws Exception {
assertTrue(ctx.containsBean("defaultMongo")); assertTrue(ctx.containsBean("defaultMongo"));
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&defaultMongo"); MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&defaultMongo");
String host = (String) getField(mfb, "host"); String host = (String) getField(mfb, "host");
Integer port = (Integer) getField(mfb, "port"); Integer port = (Integer) getField(mfb, "port");
assertEquals("localhost", host); assertEquals("localhost", host);
assertEquals(new Integer(27017), port); assertEquals(new Integer(27017), port);
MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions"); MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions");
assertFalse("By default socketFactory should not be a SSLSocketFactory", assertFalse("By default socketFactory should not be a SSLSocketFactory",
options.getSocketFactory() instanceof SSLSocketFactory); options.getSocketFactory() instanceof SSLSocketFactory);
} }
@Test // DATAMONGO-764 @Test // DATAMONGO-764
public void testMongoSingletonWithSslEnabled() throws Exception { public void testMongoSingletonWithSslEnabled() throws Exception {
assertTrue(ctx.containsBean("mongoSsl")); assertTrue(ctx.containsBean("mongoSsl"));
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoSsl"); MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoSsl");
MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions"); MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions");
assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory); assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory);
} }
@Test // DATAMONGO-1490 @Test // DATAMONGO-1490
public void testMongoClientSingletonWithSslEnabled() { public void testMongoClientSingletonWithSslEnabled() {
assertTrue(ctx.containsBean("mongoClientSsl")); assertTrue(ctx.containsBean("mongoClientSsl"));
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoClientSsl"); MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoClientSsl");
MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions"); MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions");
assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory); assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory);
} }
@Test // DATAMONGO-764 @Test // DATAMONGO-764
public void testMongoSingletonWithSslEnabledAndCustomSslSocketFactory() throws Exception { public void testMongoSingletonWithSslEnabledAndCustomSslSocketFactory() throws Exception {
assertTrue(ctx.containsBean("mongoSslWithCustomSslFactory")); assertTrue(ctx.containsBean("mongoSslWithCustomSslFactory"));
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoSslWithCustomSslFactory"); MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoSslWithCustomSslFactory");
SSLSocketFactory customSslSocketFactory = ctx.getBean("customSslSocketFactory", SSLSocketFactory.class); SSLSocketFactory customSslSocketFactory = ctx.getBean("customSslSocketFactory", SSLSocketFactory.class);
MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions"); MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions");
assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory); assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory);
assertSame(customSslSocketFactory, options.getSocketFactory()); assertSame(customSslSocketFactory, options.getSocketFactory());
} }
@Test @Test
public void testSecondMongoDbFactory() { public void testSecondMongoDbFactory() {
assertTrue(ctx.containsBean("secondMongoDbFactory")); assertTrue(ctx.containsBean("secondMongoDbFactory"));
MongoDbFactory dbf = (MongoDbFactory) ctx.getBean("secondMongoDbFactory"); MongoDbFactory dbf = (MongoDbFactory) ctx.getBean("secondMongoDbFactory");
MongoClient mongo = (MongoClient) getField(dbf, "mongoClient"); MongoClient mongo = (MongoClient) getField(dbf, "mongoClient");
assertEquals("127.0.0.1", mongo.getAddress().getHost()); assertEquals("127.0.0.1", mongo.getAddress().getHost());
assertEquals(27017, mongo.getAddress().getPort()); assertEquals(27017, mongo.getAddress().getPort());
assertEquals("database", getField(dbf, "databaseName")); assertEquals("database", getField(dbf, "databaseName"));
} }
@Test // DATAMONGO-789 @Test // DATAMONGO-789
public void testThirdMongoDbFactory() { public void testThirdMongoDbFactory() {
assertTrue(ctx.containsBean("thirdMongoDbFactory")); assertTrue(ctx.containsBean("thirdMongoDbFactory"));
MongoDbFactory dbf = (MongoDbFactory) ctx.getBean("thirdMongoDbFactory"); MongoDbFactory dbf = (MongoDbFactory) ctx.getBean("thirdMongoDbFactory");
MongoClient mongo = (MongoClient) getField(dbf, "mongoClient"); MongoClient mongo = (MongoClient) getField(dbf, "mongoClient");
assertEquals("127.0.0.1", mongo.getAddress().getHost()); assertEquals("127.0.0.1", mongo.getAddress().getHost());
assertEquals(27017, mongo.getAddress().getPort()); assertEquals(27017, mongo.getAddress().getPort());
assertEquals("database", getField(dbf, "databaseName")); assertEquals("database", getField(dbf, "databaseName"));
} }
@Test // DATAMONGO-140 @Test // DATAMONGO-140
public void testMongoTemplateFactory() { public void testMongoTemplateFactory() {
assertTrue(ctx.containsBean("mongoTemplate")); assertTrue(ctx.containsBean("mongoTemplate"));
MongoOperations operations = (MongoOperations) ctx.getBean("mongoTemplate"); MongoOperations operations = (MongoOperations) ctx.getBean("mongoTemplate");
MongoDbFactory dbf = (MongoDbFactory) getField(operations, "mongoDbFactory"); MongoDbFactory dbf = (MongoDbFactory) getField(operations, "mongoDbFactory");
assertEquals("database", getField(dbf, "databaseName")); assertEquals("database", getField(dbf, "databaseName"));
MongoConverter converter = (MongoConverter) getField(operations, "mongoConverter"); MongoConverter converter = (MongoConverter) getField(operations, "mongoConverter");
assertNotNull(converter); assertNotNull(converter);
} }
@Test // DATAMONGO-140 @Test // DATAMONGO-140
public void testSecondMongoTemplateFactory() { public void testSecondMongoTemplateFactory() {
assertTrue(ctx.containsBean("anotherMongoTemplate")); assertTrue(ctx.containsBean("anotherMongoTemplate"));
MongoOperations operations = (MongoOperations) ctx.getBean("anotherMongoTemplate"); MongoOperations operations = (MongoOperations) ctx.getBean("anotherMongoTemplate");
MongoDbFactory dbf = (MongoDbFactory) getField(operations, "mongoDbFactory"); MongoDbFactory dbf = (MongoDbFactory) getField(operations, "mongoDbFactory");
assertEquals("database", getField(dbf, "databaseName")); assertEquals("database", getField(dbf, "databaseName"));
WriteConcern writeConcern = (WriteConcern) getField(operations, "writeConcern"); WriteConcern writeConcern = (WriteConcern) getField(operations, "writeConcern");
assertEquals(WriteConcern.SAFE, writeConcern); assertEquals(WriteConcern.SAFE, writeConcern);
} }
@Test // DATAMONGO-628 @Test // DATAMONGO-628
public void testGridFsTemplateFactory() { public void testGridFsTemplateFactory() {
assertTrue(ctx.containsBean("gridFsTemplate")); assertTrue(ctx.containsBean("gridFsTemplate"));
GridFsOperations operations = (GridFsOperations) ctx.getBean("gridFsTemplate"); GridFsOperations operations = (GridFsOperations) ctx.getBean("gridFsTemplate");
MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory"); MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory");
assertEquals("database", getField(dbf, "databaseName")); assertEquals("database", getField(dbf, "databaseName"));
MongoConverter converter = (MongoConverter) getField(operations, "converter"); MongoConverter converter = (MongoConverter) getField(operations, "converter");
assertNotNull(converter); assertNotNull(converter);
} }
@Test // DATAMONGO-628 @Test // DATAMONGO-628
public void testSecondGridFsTemplateFactory() { public void testSecondGridFsTemplateFactory() {
assertTrue(ctx.containsBean("secondGridFsTemplate")); assertTrue(ctx.containsBean("secondGridFsTemplate"));
GridFsOperations operations = (GridFsOperations) ctx.getBean("secondGridFsTemplate"); GridFsOperations operations = (GridFsOperations) ctx.getBean("secondGridFsTemplate");
MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory"); MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory");
assertEquals("database", getField(dbf, "databaseName")); assertEquals("database", getField(dbf, "databaseName"));
assertEquals(null, getField(operations, "bucket")); assertEquals(null, getField(operations, "bucket"));
MongoConverter converter = (MongoConverter) getField(operations, "converter"); MongoConverter converter = (MongoConverter) getField(operations, "converter");
assertNotNull(converter); assertNotNull(converter);
} }
@Test // DATAMONGO-823 @Test // DATAMONGO-823
public void testThirdGridFsTemplateFactory() { public void testThirdGridFsTemplateFactory() {
assertTrue(ctx.containsBean("thirdGridFsTemplate")); assertTrue(ctx.containsBean("thirdGridFsTemplate"));
GridFsOperations operations = (GridFsOperations) ctx.getBean("thirdGridFsTemplate"); GridFsOperations operations = (GridFsOperations) ctx.getBean("thirdGridFsTemplate");
MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory"); MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory");
assertEquals("database", getField(dbf, "databaseName")); assertEquals("database", getField(dbf, "databaseName"));
assertEquals("bucketString", getField(operations, "bucket")); assertEquals("bucketString", getField(operations, "bucket"));
MongoConverter converter = (MongoConverter) getField(operations, "converter"); MongoConverter converter = (MongoConverter) getField(operations, "converter");
assertNotNull(converter); assertNotNull(converter);
} }
@Test @Test
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void testMongoSingletonWithPropertyPlaceHolders() throws Exception { public void testMongoSingletonWithPropertyPlaceHolders() throws Exception {
assertTrue(ctx.containsBean("mongoClient")); assertTrue(ctx.containsBean("mongoClient"));
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoClient"); MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoClient");
String host = (String) getField(mfb, "host"); String host = (String) getField(mfb, "host");
Integer port = (Integer) getField(mfb, "port"); Integer port = (Integer) getField(mfb, "port");
assertEquals("127.0.0.1", host); assertEquals("127.0.0.1", host);
assertEquals(new Integer(27017), port); assertEquals(new Integer(27017), port);
MongoClient mongo = mfb.getObject(); MongoClient mongo = mfb.getObject();
MongoClientOptions mongoOpts = mongo.getMongoClientOptions(); MongoClientOptions mongoOpts = mongo.getMongoClientOptions();
assertEquals(8, mongoOpts.getConnectionsPerHost()); assertEquals(8, mongoOpts.getConnectionsPerHost());
assertEquals(1000, mongoOpts.getConnectTimeout()); assertEquals(1000, mongoOpts.getConnectTimeout());
assertEquals(1500, mongoOpts.getMaxWaitTime()); assertEquals(1500, mongoOpts.getMaxWaitTime());
assertEquals(1500, mongoOpts.getSocketTimeout()); assertEquals(1500, mongoOpts.getSocketTimeout());
assertEquals(4, mongoOpts.getThreadsAllowedToBlockForConnectionMultiplier()); assertEquals(4, mongoOpts.getThreadsAllowedToBlockForConnectionMultiplier());
// TODO: check the damned defaults // TODO: check the damned defaults
// assertEquals("w", mongoOpts.getWriteConcern().getW()); // assertEquals("w", mongoOpts.getWriteConcern().getW());
// assertEquals(0, mongoOpts.getWriteConcern().getWtimeout()); // assertEquals(0, mongoOpts.getWriteConcern().getWtimeout());
// assertEquals(true, mongoOpts.getWriteConcern().fsync()); // assertEquals(true, mongoOpts.getWriteConcern().fsync());
} }
} }

122
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoAdminIntegrationTests.java

@ -1,61 +1,61 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mongodb.DB; import com.mongodb.DB;
import com.mongodb.MongoClient; import com.mongodb.MongoClient;
/** /**
* This test class assumes that you are already running the MongoDB server. * This test class assumes that you are already running the MongoDB server.
* *
* @author Mark Pollack * @author Mark Pollack
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:infrastructure.xml") @ContextConfiguration("classpath:infrastructure.xml")
public class MongoAdminIntegrationTests { public class MongoAdminIntegrationTests {
private static final Log logger = LogFactory.getLog(MongoAdminIntegrationTests.class); private static final Log logger = LogFactory.getLog(MongoAdminIntegrationTests.class);
@SuppressWarnings("unused") private DB testAdminDb; @SuppressWarnings("unused") private DB testAdminDb;
@Autowired MongoClient mongoClient; @Autowired MongoClient mongoClient;
MongoAdmin mongoAdmin; MongoAdmin mongoAdmin;
@Before @Before
public void setUp() { public void setUp() {
mongoAdmin = new MongoAdmin(mongoClient); mongoAdmin = new MongoAdmin(mongoClient);
} }
@Test @Test
public void serverStats() { public void serverStats() {
logger.info("stats = " + mongoAdmin.getServerStatus()); logger.info("stats = " + mongoAdmin.getServerStatus());
} }
@Test @Test
public void databaseStats() { public void databaseStats() {
logger.info(mongoAdmin.getDatabaseStats("testAdminDb")); logger.info(mongoAdmin.getDatabaseStats("testAdminDb"));
} }
} }

192
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/PersonExample.java

@ -1,96 +1,96 @@
/* /*
* Copyright 2002-2013 the original author or authors. * Copyright 2002-2013 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
import java.util.List; import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.AbstractApplicationContext;
/** /**
* @author Jon Brisbin * @author Jon Brisbin
* @author Oliver Gierke * @author Oliver Gierke
*/ */
public class PersonExample { public class PersonExample {
private static final Logger LOGGER = LoggerFactory.getLogger(PersonExample.class); private static final Logger LOGGER = LoggerFactory.getLogger(PersonExample.class);
@Autowired private MongoOperations mongoOps; @Autowired private MongoOperations mongoOps;
public static void main(String[] args) { public static void main(String[] args) {
AbstractApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonExampleAppConfig.class); AbstractApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonExampleAppConfig.class);
PersonExample example = applicationContext.getBean(PersonExample.class); PersonExample example = applicationContext.getBean(PersonExample.class);
example.doWork(); example.doWork();
applicationContext.close(); applicationContext.close();
} }
public void doWork() { public void doWork() {
mongoOps.dropCollection("personexample"); mongoOps.dropCollection("personexample");
PersonWithIdPropertyOfTypeString p = new PersonWithIdPropertyOfTypeString(); PersonWithIdPropertyOfTypeString p = new PersonWithIdPropertyOfTypeString();
p.setFirstName("Sven"); p.setFirstName("Sven");
p.setAge(22); p.setAge(22);
mongoOps.save(p); mongoOps.save(p);
PersonWithIdPropertyOfTypeString p2 = new PersonWithIdPropertyOfTypeString(); PersonWithIdPropertyOfTypeString p2 = new PersonWithIdPropertyOfTypeString();
p2.setFirstName("Jon"); p2.setFirstName("Jon");
p2.setAge(23); p2.setAge(23);
mongoOps.save(p2); mongoOps.save(p2);
LOGGER.debug("Saved: " + p); LOGGER.debug("Saved: " + p);
p = mongoOps.findById(p.getId(), PersonWithIdPropertyOfTypeString.class); p = mongoOps.findById(p.getId(), PersonWithIdPropertyOfTypeString.class);
LOGGER.debug("Found: " + p); LOGGER.debug("Found: " + p);
// mongoOps.updateFirst(new Query(where("firstName").is("Sven")), new Update().set("age", 24)); // mongoOps.updateFirst(new Query(where("firstName").is("Sven")), new Update().set("age", 24));
// mongoOps.updateFirst(new Query(where("firstName").is("Sven")), update("age", 24)); // mongoOps.updateFirst(new Query(where("firstName").is("Sven")), update("age", 24));
p = mongoOps.findById(p.getId(), PersonWithIdPropertyOfTypeString.class); p = mongoOps.findById(p.getId(), PersonWithIdPropertyOfTypeString.class);
LOGGER.debug("Updated: " + p); LOGGER.debug("Updated: " + p);
List<PersonWithIdPropertyOfTypeString> folks = mongoOps.findAll(PersonWithIdPropertyOfTypeString.class); List<PersonWithIdPropertyOfTypeString> folks = mongoOps.findAll(PersonWithIdPropertyOfTypeString.class);
LOGGER.debug("Querying for all people..."); LOGGER.debug("Querying for all people...");
for (PersonWithIdPropertyOfTypeString element : folks) { for (PersonWithIdPropertyOfTypeString element : folks) {
LOGGER.debug(element.toString()); LOGGER.debug(element.toString());
} }
// mongoOps.remove( query(whereId().is(p.getId())), p.getClass()); // mongoOps.remove( query(whereId().is(p.getId())), p.getClass());
mongoOps.remove(p); mongoOps.remove(p);
List<PersonWithIdPropertyOfTypeString> people = mongoOps.findAll(PersonWithIdPropertyOfTypeString.class); List<PersonWithIdPropertyOfTypeString> people = mongoOps.findAll(PersonWithIdPropertyOfTypeString.class);
LOGGER.debug("Number of people = : " + people.size()); LOGGER.debug("Number of people = : " + people.size());
} }
public void doWork2() { public void doWork2() {
mongoOps.dropCollection("personexample"); mongoOps.dropCollection("personexample");
PersonWithIdPropertyOfTypeString p = new PersonWithIdPropertyOfTypeString(); PersonWithIdPropertyOfTypeString p = new PersonWithIdPropertyOfTypeString();
p.setFirstName("Sven"); p.setFirstName("Sven");
p.setAge(22); p.setAge(22);
} }
} }

80
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/PersonExampleAppConfig.java

@ -1,40 +1,40 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import com.mongodb.MongoClient; import com.mongodb.MongoClient;
@Configuration @Configuration
public class PersonExampleAppConfig { public class PersonExampleAppConfig {
@Bean @Bean
public MongoClient mongoClient() { public MongoClient mongoClient() {
return new MongoClient("localhost"); return new MongoClient("localhost");
} }
@Bean @Bean
public MongoTemplate mongoTemplate() throws Exception { public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoClient(), "database"); return new MongoTemplate(mongoClient(), "database");
} }
@Bean @Bean
public PersonExample personExample() { public PersonExample personExample() {
return new PersonExample(); return new PersonExample();
} }
} }

146
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Portfolio.java

@ -1,73 +1,73 @@
/* /*
* Copyright 2010-2011 the original author or authors. * Copyright 2010-2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
public class Portfolio { public class Portfolio {
private String portfolioName; private String portfolioName;
private User user; private User user;
private List<Trade> trades; private List<Trade> trades;
private Map<String, Integer> positions; private Map<String, Integer> positions;
private Map<String, Person> portfolioManagers; private Map<String, Person> portfolioManagers;
public Map<String, Person> getPortfolioManagers() { public Map<String, Person> getPortfolioManagers() {
return portfolioManagers; return portfolioManagers;
} }
public void setPortfolioManagers(Map<String, Person> portfolioManagers) { public void setPortfolioManagers(Map<String, Person> portfolioManagers) {
this.portfolioManagers = portfolioManagers; this.portfolioManagers = portfolioManagers;
} }
public Map<String, Integer> getPositions() { public Map<String, Integer> getPositions() {
return positions; return positions;
} }
public void setPositions(Map<String, Integer> positions) { public void setPositions(Map<String, Integer> positions) {
this.positions = positions; this.positions = positions;
} }
public Portfolio() { public Portfolio() {
trades = new ArrayList<Trade>(); trades = new ArrayList<Trade>();
} }
public String getPortfolioName() { public String getPortfolioName() {
return portfolioName; return portfolioName;
} }
public void setPortfolioName(String portfolioName) { public void setPortfolioName(String portfolioName) {
this.portfolioName = portfolioName; this.portfolioName = portfolioName;
} }
public List<Trade> getTrades() { public List<Trade> getTrades() {
return trades; return trades;
} }
public void setTrades(List<Trade> trades) { public void setTrades(List<Trade> trades) {
this.trades = trades; this.trades = trades;
} }
public User getUser() { public User getUser() {
return user; return user;
} }
public void setUser(User user) { public void setUser(User user) {
this.user = user; this.user = user;
} }
} }

120
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Trade.java

@ -1,60 +1,60 @@
/* /*
* Copyright 2010-2011 the original author or authors. * Copyright 2010-2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
public class Trade { public class Trade {
private String ticker; private String ticker;
private long quantity; private long quantity;
private double price; private double price;
private String orderType; private String orderType;
public String getOrderType() { public String getOrderType() {
return orderType; return orderType;
} }
public void setOrderType(String orderType) { public void setOrderType(String orderType) {
this.orderType = orderType; this.orderType = orderType;
} }
public double getPrice() { public double getPrice() {
return price; return price;
} }
public void setPrice(double price) { public void setPrice(double price) {
this.price = price; this.price = price;
} }
public long getQuantity() { public long getQuantity() {
return quantity; return quantity;
} }
public void setQuantity(long quantity) { public void setQuantity(long quantity) {
this.quantity = quantity; this.quantity = quantity;
} }
public String getTicker() { public String getTicker() {
return ticker; return ticker;
} }
public void setTicker(String ticker) { public void setTicker(String ticker) {
this.ticker = ticker; this.ticker = ticker;
} }
} }

142
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/User.java

@ -1,71 +1,71 @@
/* /*
* Copyright 2010-2011 the original author or authors. * Copyright 2010-2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
public class User { public class User {
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((accountName == null) ? 0 : accountName.hashCode()); result = prime * result + ((accountName == null) ? 0 : accountName.hashCode());
result = prime * result + ((userName == null) ? 0 : userName.hashCode()); result = prime * result + ((userName == null) ? 0 : userName.hashCode());
return result; return result;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) if (this == obj)
return true; return true;
if (obj == null) if (obj == null)
return false; return false;
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
User other = (User) obj; User other = (User) obj;
if (accountName == null) { if (accountName == null) {
if (other.accountName != null) if (other.accountName != null)
return false; return false;
} else if (!accountName.equals(other.accountName)) } else if (!accountName.equals(other.accountName))
return false; return false;
if (userName == null) { if (userName == null) {
if (other.userName != null) if (other.userName != null)
return false; return false;
} else if (!userName.equals(other.userName)) } else if (!userName.equals(other.userName))
return false; return false;
return true; return true;
} }
private String accountName; private String accountName;
private String userName; private String userName;
public String getAccountName() { public String getAccountName() {
return accountName; return accountName;
} }
public void setAccountName(String accountName) { public void setAccountName(String accountName) {
this.accountName = accountName; this.accountName = accountName;
} }
public String getUserName() { public String getUserName() {
return userName; return userName;
} }
public void setUserName(String userName) { public void setUserName(String userName) {
this.userName = userName; this.userName = userName;
} }
} }

132
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Venue.java

@ -1,66 +1,66 @@
/* /*
* Copyright 2010-2011 the original author or authors. * Copyright 2010-2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
import java.util.Arrays; import java.util.Arrays;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor; import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "newyork") @Document(collection = "newyork")
public class Venue { public class Venue {
@Id private String id; @Id private String id;
private String name; private String name;
private double[] location; private double[] location;
private LocalDate openingDate; private LocalDate openingDate;
@PersistenceConstructor @PersistenceConstructor
Venue(String name, double[] location) { Venue(String name, double[] location) {
super(); super();
this.name = name; this.name = name;
this.location = location; this.location = location;
} }
public Venue(String name, double x, double y) { public Venue(String name, double x, double y) {
super(); super();
this.name = name; this.name = name;
this.location = new double[] { x, y }; this.location = new double[] { x, y };
} }
public String getName() { public String getName() {
return name; return name;
} }
public double[] getLocation() { public double[] getLocation() {
return location; return location;
} }
public LocalDate getOpeningDate() { public LocalDate getOpeningDate() {
return openingDate; return openingDate;
} }
public void setOpeningDate(LocalDate openingDate) { public void setOpeningDate(LocalDate openingDate) {
this.openingDate = openingDate; this.openingDate = openingDate;
} }
@Override @Override
public String toString() { public String toString() {
return "Venue [id=" + id + ", name=" + name + ", location=" + Arrays.toString(location) + "]"; return "Venue [id=" + id + ", name=" + name + ", location=" + Arrays.toString(location) + "]";
} }
} }

178
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DSphereTests.java

@ -1,89 +1,89 @@
/* /*
* Copyright 2010-2017 the original author or authors. * Copyright 2010-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core.geo; package org.springframework.data.mongodb.core.geo;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.query.Criteria.*; import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*; import static org.springframework.data.mongodb.core.query.Query.*;
import java.util.List; import java.util.List;
import org.junit.Test; import org.junit.Test;
import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.geo.GeoResults; import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Metric; import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point; import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.index.IndexOperations; import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.Venue; import org.springframework.data.mongodb.core.Venue;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType; import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeospatialIndex; import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.data.mongodb.core.index.IndexField; import org.springframework.data.mongodb.core.index.IndexField;
import org.springframework.data.mongodb.core.index.IndexInfo; import org.springframework.data.mongodb.core.index.IndexInfo;
import org.springframework.data.mongodb.core.query.NearQuery; import org.springframework.data.mongodb.core.query.NearQuery;
/** /**
* @author Christoph Strobl * @author Christoph Strobl
*/ */
public class GeoSpatial2DSphereTests extends AbstractGeoSpatialTests { public class GeoSpatial2DSphereTests extends AbstractGeoSpatialTests {
@Test // DATAMONGO-360 @Test // DATAMONGO-360
public void indexInfoIsCorrect() { public void indexInfoIsCorrect() {
IndexOperations operations = template.indexOps(Venue.class); IndexOperations operations = template.indexOps(Venue.class);
List<IndexInfo> indexInfo = operations.getIndexInfo(); List<IndexInfo> indexInfo = operations.getIndexInfo();
assertThat(indexInfo.size(), is(2)); assertThat(indexInfo.size(), is(2));
List<IndexField> fields = indexInfo.get(0).getIndexFields(); List<IndexField> fields = indexInfo.get(0).getIndexFields();
assertThat(fields.size(), is(1)); assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC))); assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC)));
fields = indexInfo.get(1).getIndexFields(); fields = indexInfo.get(1).getIndexFields();
assertThat(fields.size(), is(1)); assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.geo("location"))); assertThat(fields, hasItem(IndexField.geo("location")));
} }
@Test // DATAMONGO-1110 @Test // DATAMONGO-1110
public void geoNearWithMinDistance() { public void geoNearWithMinDistance() {
NearQuery geoNear = NearQuery.near(-73, 40, Metrics.KILOMETERS).num(10).minDistance(1); NearQuery geoNear = NearQuery.near(-73, 40, Metrics.KILOMETERS).num(10).minDistance(1);
GeoResults<Venue> result = template.geoNear(geoNear, Venue.class); GeoResults<Venue> result = template.geoNear(geoNear, Venue.class);
assertThat(result.getContent().size(), is(not(0))); assertThat(result.getContent().size(), is(not(0)));
assertThat(result.getAverageDistance().getMetric(), is((Metric) Metrics.KILOMETERS)); assertThat(result.getAverageDistance().getMetric(), is((Metric) Metrics.KILOMETERS));
} }
@Test // DATAMONGO-1110 @Test // DATAMONGO-1110
public void nearSphereWithMinDistance() { public void nearSphereWithMinDistance() {
Point point = new Point(-73.99171, 40.738868); Point point = new Point(-73.99171, 40.738868);
List<Venue> venues = template.find(query(where("location").nearSphere(point).minDistance(0.01)), Venue.class); List<Venue> venues = template.find(query(where("location").nearSphere(point).minDistance(0.01)), Venue.class);
assertThat(venues.size(), is(1)); assertThat(venues.size(), is(1));
} }
@Override @Override
protected void createIndex() { protected void createIndex() {
template.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE)); template.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE));
} }
@Override @Override
protected void dropIndex() { protected void dropIndex() {
template.indexOps(Venue.class).dropIndex("location_2dsphere"); template.indexOps(Venue.class).dropIndex("location_2dsphere");
} }
} }

158
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DTests.java

@ -1,79 +1,79 @@
/* /*
* Copyright 2010-2017 the original author or authors. * Copyright 2010-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core.geo; package org.springframework.data.mongodb.core.geo;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.query.Criteria.*; import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*; import static org.springframework.data.mongodb.core.query.Query.*;
import java.util.List; import java.util.List;
import org.junit.Test; import org.junit.Test;
import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.geo.Point; import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.index.IndexOperations; import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.Venue; import org.springframework.data.mongodb.core.Venue;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType; import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeospatialIndex; import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.data.mongodb.core.index.IndexField; import org.springframework.data.mongodb.core.index.IndexField;
import org.springframework.data.mongodb.core.index.IndexInfo; import org.springframework.data.mongodb.core.index.IndexInfo;
/** /**
* Modified from https://github.com/deftlabs/mongo-java-geospatial-example * Modified from https://github.com/deftlabs/mongo-java-geospatial-example
* *
* @author Mark Pollack * @author Mark Pollack
* @author Oliver Gierke * @author Oliver Gierke
* @author Thomas Darimont * @author Thomas Darimont
* @author Christoph Strobl * @author Christoph Strobl
*/ */
public class GeoSpatial2DTests extends AbstractGeoSpatialTests { public class GeoSpatial2DTests extends AbstractGeoSpatialTests {
@Test @Test
public void nearPoint() { public void nearPoint() {
Point point = new Point(-73.99171, 40.738868); Point point = new Point(-73.99171, 40.738868);
List<Venue> venues = template.find(query(where("location").near(point).maxDistance(0.01)), Venue.class); List<Venue> venues = template.find(query(where("location").near(point).maxDistance(0.01)), Venue.class);
assertThat(venues.size(), is(7)); assertThat(venues.size(), is(7));
} }
@Test // DATAMONGO-360 @Test // DATAMONGO-360
public void indexInfoIsCorrect() { public void indexInfoIsCorrect() {
IndexOperations operations = template.indexOps(Venue.class); IndexOperations operations = template.indexOps(Venue.class);
List<IndexInfo> indexInfo = operations.getIndexInfo(); List<IndexInfo> indexInfo = operations.getIndexInfo();
assertThat(indexInfo.size(), is(2)); assertThat(indexInfo.size(), is(2));
List<IndexField> fields = indexInfo.get(0).getIndexFields(); List<IndexField> fields = indexInfo.get(0).getIndexFields();
assertThat(fields.size(), is(1)); assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC))); assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC)));
fields = indexInfo.get(1).getIndexFields(); fields = indexInfo.get(1).getIndexFields();
assertThat(fields.size(), is(1)); assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.geo("location"))); assertThat(fields, hasItem(IndexField.geo("location")));
} }
@Override @Override
protected void createIndex() { protected void createIndex() {
template.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2D)); template.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2D));
} }
@Override @Override
protected void dropIndex() { protected void dropIndex() {
template.indexOps(Venue.class).dropIndex("location_2d"); template.indexOps(Venue.class).dropIndex("location_2d");
} }
} }

100
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/GeoIndexedAppConfig.java

@ -1,50 +1,50 @@
/* /*
* Copyright 2011-2017 the original author or authors. * Copyright 2011-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core.mapping; package org.springframework.data.mongodb.core.mapping;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration; import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.mapping.event.LoggingEventListener; import org.springframework.data.mongodb.core.mapping.event.LoggingEventListener;
import com.mongodb.Mongo; import com.mongodb.Mongo;
import com.mongodb.MongoClient; import com.mongodb.MongoClient;
public class GeoIndexedAppConfig extends AbstractMongoConfiguration { public class GeoIndexedAppConfig extends AbstractMongoConfiguration {
public static String GEO_DB = "database"; public static String GEO_DB = "database";
public static String GEO_COLLECTION = "geolocation"; public static String GEO_COLLECTION = "geolocation";
@Override @Override
public String getDatabaseName() { public String getDatabaseName() {
return GEO_DB; return GEO_DB;
} }
@Override @Override
@Bean @Bean
public MongoClient mongoClient() { public MongoClient mongoClient() {
return new MongoClient("127.0.0.1"); return new MongoClient("127.0.0.1");
} }
@Override @Override
public String getMappingBasePackage() { public String getMappingBasePackage() {
return "org.springframework.data.mongodb.core.core.mapping"; return "org.springframework.data.mongodb.core.core.mapping";
} }
@Bean @Bean
public LoggingEventListener mappingEventsListener() { public LoggingEventListener mappingEventsListener() {
return new LoggingEventListener(); return new LoggingEventListener();
} }
} }

432
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/CriteriaTests.java

@ -1,216 +1,216 @@
/* /*
* Copyright 2010-2017 the original author or authors. * Copyright 2010-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core.query; package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import static org.springframework.data.mongodb.test.util.IsBsonObject.*; import static org.springframework.data.mongodb.test.util.IsBsonObject.*;
import org.bson.Document; import org.bson.Document;
import org.junit.Test; import org.junit.Test;
import org.springframework.data.geo.Point; import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.InvalidMongoDbApiUsageException; import org.springframework.data.mongodb.InvalidMongoDbApiUsageException;
import org.springframework.data.mongodb.core.geo.GeoJsonLineString; import org.springframework.data.mongodb.core.geo.GeoJsonLineString;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint; import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
/** /**
* @author Oliver Gierke * @author Oliver Gierke
* @author Thomas Darimont * @author Thomas Darimont
* @author Christoph Strobl * @author Christoph Strobl
*/ */
public class CriteriaTests { public class CriteriaTests {
@Test @Test
public void testSimpleCriteria() { public void testSimpleCriteria() {
Criteria c = new Criteria("name").is("Bubba"); Criteria c = new Criteria("name").is("Bubba");
assertEquals(Document.parse("{ \"name\" : \"Bubba\"}"), c.getCriteriaObject()); assertEquals(Document.parse("{ \"name\" : \"Bubba\"}"), c.getCriteriaObject());
} }
@Test @Test
public void testNotEqualCriteria() { public void testNotEqualCriteria() {
Criteria c = new Criteria("name").ne("Bubba"); Criteria c = new Criteria("name").ne("Bubba");
assertEquals(Document.parse("{ \"name\" : { \"$ne\" : \"Bubba\"}}"), c.getCriteriaObject()); assertEquals(Document.parse("{ \"name\" : { \"$ne\" : \"Bubba\"}}"), c.getCriteriaObject());
} }
@Test @Test
public void buildsIsNullCriteriaCorrectly() { public void buildsIsNullCriteriaCorrectly() {
Document reference = new Document("name", null); Document reference = new Document("name", null);
Criteria criteria = new Criteria("name").is(null); Criteria criteria = new Criteria("name").is(null);
assertThat(criteria.getCriteriaObject(), is(reference)); assertThat(criteria.getCriteriaObject(), is(reference));
} }
@Test @Test
public void testChainedCriteria() { public void testChainedCriteria() {
Criteria c = new Criteria("name").is("Bubba").and("age").lt(21); Criteria c = new Criteria("name").is("Bubba").and("age").lt(21);
assertEquals(Document.parse("{ \"name\" : \"Bubba\" , \"age\" : { \"$lt\" : 21}}"), c.getCriteriaObject()); assertEquals(Document.parse("{ \"name\" : \"Bubba\" , \"age\" : { \"$lt\" : 21}}"), c.getCriteriaObject());
} }
@Test(expected = InvalidMongoDbApiUsageException.class) @Test(expected = InvalidMongoDbApiUsageException.class)
public void testCriteriaWithMultipleConditionsForSameKey() { public void testCriteriaWithMultipleConditionsForSameKey() {
Criteria c = new Criteria("name").gte("M").and("name").ne("A"); Criteria c = new Criteria("name").gte("M").and("name").ne("A");
c.getCriteriaObject(); c.getCriteriaObject();
} }
@Test @Test
public void equalIfCriteriaMatches() { public void equalIfCriteriaMatches() {
Criteria left = new Criteria("name").is("Foo").and("lastname").is("Bar"); Criteria left = new Criteria("name").is("Foo").and("lastname").is("Bar");
Criteria right = new Criteria("name").is("Bar").and("lastname").is("Bar"); Criteria right = new Criteria("name").is("Bar").and("lastname").is("Bar");
assertThat(left, is(not(right))); assertThat(left, is(not(right)));
assertThat(right, is(not(left))); assertThat(right, is(not(left)));
} }
@Test(expected = IllegalArgumentException.class) // DATAMONGO-507 @Test(expected = IllegalArgumentException.class) // DATAMONGO-507
public void shouldThrowExceptionWhenTryingToNegateAndOperation() { public void shouldThrowExceptionWhenTryingToNegateAndOperation() {
new Criteria() // new Criteria() //
.not() // .not() //
.andOperator(Criteria.where("delete").is(true).and("_id").is(42)); // .andOperator(Criteria.where("delete").is(true).and("_id").is(42)); //
} }
@Test(expected = IllegalArgumentException.class) // DATAMONGO-507 @Test(expected = IllegalArgumentException.class) // DATAMONGO-507
public void shouldThrowExceptionWhenTryingToNegateOrOperation() { public void shouldThrowExceptionWhenTryingToNegateOrOperation() {
new Criteria() // new Criteria() //
.not() // .not() //
.orOperator(Criteria.where("delete").is(true).and("_id").is(42)); // .orOperator(Criteria.where("delete").is(true).and("_id").is(42)); //
} }
@Test(expected = IllegalArgumentException.class) // DATAMONGO-507 @Test(expected = IllegalArgumentException.class) // DATAMONGO-507
public void shouldThrowExceptionWhenTryingToNegateNorOperation() { public void shouldThrowExceptionWhenTryingToNegateNorOperation() {
new Criteria() // new Criteria() //
.not() // .not() //
.norOperator(Criteria.where("delete").is(true).and("_id").is(42)); // .norOperator(Criteria.where("delete").is(true).and("_id").is(42)); //
} }
@Test // DATAMONGO-507 @Test // DATAMONGO-507
public void shouldNegateFollowingSimpleExpression() { public void shouldNegateFollowingSimpleExpression() {
Criteria c = Criteria.where("age").not().gt(18).and("status").is("student"); Criteria c = Criteria.where("age").not().gt(18).and("status").is("student");
Document co = c.getCriteriaObject(); Document co = c.getCriteriaObject();
assertThat(co, is(notNullValue())); assertThat(co, is(notNullValue()));
assertThat(co, is(Document.parse("{ \"age\" : { \"$not\" : { \"$gt\" : 18}} , \"status\" : \"student\"}"))); assertThat(co, is(Document.parse("{ \"age\" : { \"$not\" : { \"$gt\" : 18}} , \"status\" : \"student\"}")));
} }
@Test // DATAMONGO-1068 @Test // DATAMONGO-1068
public void getCriteriaObjectShouldReturnEmptyDocumentWhenNoCriteriaSpecified() { public void getCriteriaObjectShouldReturnEmptyDocumentWhenNoCriteriaSpecified() {
Document document = new Criteria().getCriteriaObject(); Document document = new Criteria().getCriteriaObject();
assertThat(document, equalTo(new Document())); assertThat(document, equalTo(new Document()));
} }
@Test // DATAMONGO-1068 @Test // DATAMONGO-1068
public void getCriteriaObjectShouldUseCritieraValuesWhenNoKeyIsPresent() { public void getCriteriaObjectShouldUseCritieraValuesWhenNoKeyIsPresent() {
Document document = new Criteria().lt("foo").getCriteriaObject(); Document document = new Criteria().lt("foo").getCriteriaObject();
assertThat(document, equalTo(new Document().append("$lt", "foo"))); assertThat(document, equalTo(new Document().append("$lt", "foo")));
} }
@Test // DATAMONGO-1068 @Test // DATAMONGO-1068
public void getCriteriaObjectShouldUseCritieraValuesWhenNoKeyIsPresentButMultipleCriteriasPresent() { public void getCriteriaObjectShouldUseCritieraValuesWhenNoKeyIsPresentButMultipleCriteriasPresent() {
Document document = new Criteria().lt("foo").gt("bar").getCriteriaObject(); Document document = new Criteria().lt("foo").gt("bar").getCriteriaObject();
assertThat(document, equalTo(new Document().append("$lt", "foo").append("$gt", "bar"))); assertThat(document, equalTo(new Document().append("$lt", "foo").append("$gt", "bar")));
} }
@Test // DATAMONGO-1068 @Test // DATAMONGO-1068
public void getCriteriaObjectShouldRespectNotWhenNoKeyPresent() { public void getCriteriaObjectShouldRespectNotWhenNoKeyPresent() {
Document document = new Criteria().lt("foo").not().getCriteriaObject(); Document document = new Criteria().lt("foo").not().getCriteriaObject();
assertThat(document, equalTo(new Document().append("$not", new Document("$lt", "foo")))); assertThat(document, equalTo(new Document().append("$not", new Document("$lt", "foo"))));
} }
@Test // DATAMONGO-1135 @Test // DATAMONGO-1135
public void geoJsonTypesShouldBeWrappedInGeometry() { public void geoJsonTypesShouldBeWrappedInGeometry() {
Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).getCriteriaObject(); Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$near.$geometry", new GeoJsonPoint(100, 200))); assertThat(document, isBsonObject().containing("foo.$near.$geometry", new GeoJsonPoint(100, 200)));
} }
@Test // DATAMONGO-1135 @Test // DATAMONGO-1135
public void legacyCoordinateTypesShouldNotBeWrappedInGeometry() { public void legacyCoordinateTypesShouldNotBeWrappedInGeometry() {
Document document = new Criteria("foo").near(new Point(100, 200)).getCriteriaObject(); Document document = new Criteria("foo").near(new Point(100, 200)).getCriteriaObject();
assertThat(document, isBsonObject().notContaining("foo.$near.$geometry")); assertThat(document, isBsonObject().notContaining("foo.$near.$geometry"));
} }
@Test // DATAMONGO-1135 @Test // DATAMONGO-1135
public void maxDistanceShouldBeMappedInsideNearWhenUsedAlongWithGeoJsonType() { public void maxDistanceShouldBeMappedInsideNearWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).maxDistance(50D).getCriteriaObject(); Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).maxDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$near.$maxDistance", 50D)); assertThat(document, isBsonObject().containing("foo.$near.$maxDistance", 50D));
} }
@Test // DATAMONGO-1135 @Test // DATAMONGO-1135
public void maxDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() { public void maxDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).maxDistance(50D).getCriteriaObject(); Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).maxDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$nearSphere.$maxDistance", 50D)); assertThat(document, isBsonObject().containing("foo.$nearSphere.$maxDistance", 50D));
} }
@Test // DATAMONGO-1110 @Test // DATAMONGO-1110
public void minDistanceShouldBeMappedInsideNearWhenUsedAlongWithGeoJsonType() { public void minDistanceShouldBeMappedInsideNearWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).minDistance(50D).getCriteriaObject(); Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).minDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$near.$minDistance", 50D)); assertThat(document, isBsonObject().containing("foo.$near.$minDistance", 50D));
} }
@Test // DATAMONGO-1110 @Test // DATAMONGO-1110
public void minDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() { public void minDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).minDistance(50D).getCriteriaObject(); Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).minDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$nearSphere.$minDistance", 50D)); assertThat(document, isBsonObject().containing("foo.$nearSphere.$minDistance", 50D));
} }
@Test // DATAMONGO-1110 @Test // DATAMONGO-1110
public void minAndMaxDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() { public void minAndMaxDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).minDistance(50D).maxDistance(100D) Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).minDistance(50D).maxDistance(100D)
.getCriteriaObject(); .getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$nearSphere.$minDistance", 50D)); assertThat(document, isBsonObject().containing("foo.$nearSphere.$minDistance", 50D));
assertThat(document, isBsonObject().containing("foo.$nearSphere.$maxDistance", 100D)); assertThat(document, isBsonObject().containing("foo.$nearSphere.$maxDistance", 100D));
} }
@Test(expected = IllegalArgumentException.class) // DATAMONGO-1134 @Test(expected = IllegalArgumentException.class) // DATAMONGO-1134
public void intersectsShouldThrowExceptionWhenCalledWihtNullValue() { public void intersectsShouldThrowExceptionWhenCalledWihtNullValue() {
new Criteria("foo").intersects(null); new Criteria("foo").intersects(null);
} }
@Test // DATAMONGO-1134 @Test // DATAMONGO-1134
public void intersectsShouldWrapGeoJsonTypeInGeometryCorrectly() { public void intersectsShouldWrapGeoJsonTypeInGeometryCorrectly() {
GeoJsonLineString lineString = new GeoJsonLineString(new Point(0, 0), new Point(10, 10)); GeoJsonLineString lineString = new GeoJsonLineString(new Point(0, 0), new Point(10, 10));
Document document = new Criteria("foo").intersects(lineString).getCriteriaObject(); Document document = new Criteria("foo").intersects(lineString).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$geoIntersects.$geometry", lineString)); assertThat(document, isBsonObject().containing("foo.$geoIntersects.$geometry", lineString));
} }
} }

190
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/IndexUnitTests.java

@ -1,95 +1,95 @@
/* /*
* Copyright 2010-2017 the original author or authors. * Copyright 2010-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core.query; package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import org.bson.Document; import org.bson.Document;
import org.junit.Test; import org.junit.Test;
import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType; import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeospatialIndex; import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.data.mongodb.core.index.Index; import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.Index.Duplicates; import org.springframework.data.mongodb.core.index.Index.Duplicates;
/** /**
* Unit tests for {@link Index}. * Unit tests for {@link Index}.
* *
* @author Oliver Gierke * @author Oliver Gierke
* @author Laurent Canet * @author Laurent Canet
*/ */
public class IndexUnitTests { public class IndexUnitTests {
@Test @Test
public void testWithAscendingIndex() { public void testWithAscendingIndex() {
Index i = new Index().on("name", Direction.ASC); Index i = new Index().on("name", Direction.ASC);
assertEquals(Document.parse("{ \"name\" : 1}"), i.getIndexKeys()); assertEquals(Document.parse("{ \"name\" : 1}"), i.getIndexKeys());
} }
@Test @Test
public void testWithDescendingIndex() { public void testWithDescendingIndex() {
Index i = new Index().on("name", Direction.DESC); Index i = new Index().on("name", Direction.DESC);
assertEquals(Document.parse("{ \"name\" : -1}"), i.getIndexKeys()); assertEquals(Document.parse("{ \"name\" : -1}"), i.getIndexKeys());
} }
@Test @Test
public void testNamedMultiFieldUniqueIndex() { public void testNamedMultiFieldUniqueIndex() {
Index i = new Index().on("name", Direction.ASC).on("age", Direction.DESC); Index i = new Index().on("name", Direction.ASC).on("age", Direction.DESC);
i.named("test").unique(); i.named("test").unique();
assertEquals(Document.parse("{ \"name\" : 1 , \"age\" : -1}"), i.getIndexKeys()); assertEquals(Document.parse("{ \"name\" : 1 , \"age\" : -1}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"name\" : \"test\" , \"unique\" : true}"), i.getIndexOptions()); assertEquals(Document.parse("{ \"name\" : \"test\" , \"unique\" : true}"), i.getIndexOptions());
} }
@Test @Test
public void testWithSparse() { public void testWithSparse() {
Index i = new Index().on("name", Direction.ASC); Index i = new Index().on("name", Direction.ASC);
i.sparse().unique(); i.sparse().unique();
assertEquals(Document.parse("{ \"name\" : 1}"), i.getIndexKeys()); assertEquals(Document.parse("{ \"name\" : 1}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"unique\" : true , \"sparse\" : true}"), i.getIndexOptions()); assertEquals(Document.parse("{ \"unique\" : true , \"sparse\" : true}"), i.getIndexOptions());
} }
@Test @Test
public void testGeospatialIndex() { public void testGeospatialIndex() {
GeospatialIndex i = new GeospatialIndex("location").withMin(0); GeospatialIndex i = new GeospatialIndex("location").withMin(0);
assertEquals(Document.parse("{ \"location\" : \"2d\"}"), i.getIndexKeys()); assertEquals(Document.parse("{ \"location\" : \"2d\"}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"min\" : 0}"), i.getIndexOptions()); assertEquals(Document.parse("{ \"min\" : 0}"), i.getIndexOptions());
} }
@Test // DATAMONGO-778 @Test // DATAMONGO-778
public void testGeospatialIndex2DSphere() { public void testGeospatialIndex2DSphere() {
GeospatialIndex i = new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE); GeospatialIndex i = new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE);
assertEquals(Document.parse("{ \"location\" : \"2dsphere\"}"), i.getIndexKeys()); assertEquals(Document.parse("{ \"location\" : \"2dsphere\"}"), i.getIndexKeys());
assertEquals(Document.parse("{ }"), i.getIndexOptions()); assertEquals(Document.parse("{ }"), i.getIndexOptions());
} }
@Test // DATAMONGO-778 @Test // DATAMONGO-778
public void testGeospatialIndexGeoHaystack() { public void testGeospatialIndexGeoHaystack() {
GeospatialIndex i = new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_HAYSTACK) GeospatialIndex i = new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_HAYSTACK)
.withAdditionalField("name").withBucketSize(40); .withAdditionalField("name").withBucketSize(40);
assertEquals(Document.parse("{ \"location\" : \"geoHaystack\" , \"name\" : 1}"), i.getIndexKeys()); assertEquals(Document.parse("{ \"location\" : \"geoHaystack\" , \"name\" : 1}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"bucketSize\" : 40.0}"), i.getIndexOptions()); assertEquals(Document.parse("{ \"bucketSize\" : 40.0}"), i.getIndexOptions());
} }
@Test @Test
public void ensuresPropertyOrder() { public void ensuresPropertyOrder() {
Index on = new Index("foo", Direction.ASC).on("bar", Direction.ASC); Index on = new Index("foo", Direction.ASC).on("bar", Direction.ASC);
assertThat(on.getIndexKeys(), is(Document.parse("{ \"foo\" : 1 , \"bar\" : 1}"))); assertThat(on.getIndexKeys(), is(Document.parse("{ \"foo\" : 1 , \"bar\" : 1}")));
} }
} }

108
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/SortTests.java

@ -1,54 +1,54 @@
/* /*
* Copyright 2010-2017 the original author or authors. * Copyright 2010-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core.query; package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import org.bson.Document; import org.bson.Document;
import org.junit.Test; import org.junit.Test;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Direction;
/** /**
* Unit tests for sorting. * Unit tests for sorting.
* *
* @author Oliver Gierke * @author Oliver Gierke
* @author Mark Paluch * @author Mark Paluch
*/ */
public class SortTests { public class SortTests {
@Test @Test
public void testWithSortAscending() { public void testWithSortAscending() {
Query s = new Query().with(Sort.by(Direction.ASC, "name")); Query s = new Query().with(Sort.by(Direction.ASC, "name"));
assertEquals(Document.parse("{ \"name\" : 1}"), s.getSortObject()); assertEquals(Document.parse("{ \"name\" : 1}"), s.getSortObject());
} }
@Test @Test
public void testWithSortDescending() { public void testWithSortDescending() {
Query s = new Query().with(Sort.by(Direction.DESC, "name")); Query s = new Query().with(Sort.by(Direction.DESC, "name"));
assertEquals(Document.parse("{ \"name\" : -1}"), s.getSortObject()); assertEquals(Document.parse("{ \"name\" : -1}"), s.getSortObject());
} }
@Test // DATADOC-177 @Test // DATADOC-177
public void preservesOrderKeysOnMultipleSorts() { public void preservesOrderKeysOnMultipleSorts() {
Query sort = new Query().with(Sort.by(Direction.DESC, "foo").and(Sort.by(Direction.DESC, "bar"))); Query sort = new Query().with(Sort.by(Direction.DESC, "foo").and(Sort.by(Direction.DESC, "bar")));
assertThat(sort.getSortObject(), is(Document.parse("{ \"foo\" : -1 , \"bar\" : -1}"))); assertThat(sort.getSortObject(), is(Document.parse("{ \"foo\" : -1 , \"bar\" : -1}")));
} }
} }

142
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/monitor/MongoMonitorIntegrationTests.java

@ -1,71 +1,71 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.monitor; package org.springframework.data.mongodb.monitor;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mongodb.MongoClient; import com.mongodb.MongoClient;
/** /**
* This test class assumes that you are already running the MongoDB server. * This test class assumes that you are already running the MongoDB server.
* *
* @author Mark Pollack * @author Mark Pollack
* @author Thomas Darimont * @author Thomas Darimont
* @author Mark Paluch * @author Mark Paluch
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:infrastructure.xml") @ContextConfiguration("classpath:infrastructure.xml")
public class MongoMonitorIntegrationTests { public class MongoMonitorIntegrationTests {
@Autowired MongoClient mongoClient; @Autowired MongoClient mongoClient;
@Test @Test
public void serverInfo() { public void serverInfo() {
ServerInfo serverInfo = new ServerInfo(mongoClient); ServerInfo serverInfo = new ServerInfo(mongoClient);
serverInfo.getVersion(); serverInfo.getVersion();
} }
@Test // DATAMONGO-685 @Test // DATAMONGO-685
public void getHostNameShouldReturnServerNameReportedByMongo() throws UnknownHostException { public void getHostNameShouldReturnServerNameReportedByMongo() throws UnknownHostException {
ServerInfo serverInfo = new ServerInfo(mongoClient); ServerInfo serverInfo = new ServerInfo(mongoClient);
String hostName = null; String hostName = null;
try { try {
hostName = serverInfo.getHostName(); hostName = serverInfo.getHostName();
} catch (UnknownHostException e) { } catch (UnknownHostException e) {
throw e; throw e;
} }
assertThat(hostName, is(notNullValue())); assertThat(hostName, is(notNullValue()));
assertThat(hostName, is("127.0.0.1")); assertThat(hostName, is("127.0.0.1"));
} }
@Test @Test
public void operationCounters() { public void operationCounters() {
OperationCounters operationCounters = new OperationCounters(mongoClient); OperationCounters operationCounters = new OperationCounters(mongoClient);
operationCounters.getInsertCount(); operationCounters.getInsertCount();
} }
} }

Loading…
Cancel
Save