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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -1,66 +1,66 @@ @@ -1,66 +1,66 @@
/*
* Copyright 2010-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core;
import java.util.Arrays;
import org.joda.time.LocalDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "newyork")
public class Venue {
@Id private String id;
private String name;
private double[] location;
private LocalDate openingDate;
@PersistenceConstructor
Venue(String name, double[] location) {
super();
this.name = name;
this.location = location;
}
public Venue(String name, double x, double y) {
super();
this.name = name;
this.location = new double[] { x, y };
}
public String getName() {
return name;
}
public double[] getLocation() {
return location;
}
public LocalDate getOpeningDate() {
return openingDate;
}
public void setOpeningDate(LocalDate openingDate) {
this.openingDate = openingDate;
}
@Override
public String toString() {
return "Venue [id=" + id + ", name=" + name + ", location=" + Arrays.toString(location) + "]";
}
}
/*
* Copyright 2010-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core;
import java.util.Arrays;
import org.joda.time.LocalDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "newyork")
public class Venue {
@Id private String id;
private String name;
private double[] location;
private LocalDate openingDate;
@PersistenceConstructor
Venue(String name, double[] location) {
super();
this.name = name;
this.location = location;
}
public Venue(String name, double x, double y) {
super();
this.name = name;
this.location = new double[] { x, y };
}
public String getName() {
return name;
}
public double[] getLocation() {
return location;
}
public LocalDate getOpeningDate() {
return openingDate;
}
public void setOpeningDate(LocalDate openingDate) {
this.openingDate = openingDate;
}
@Override
public String toString() {
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 @@ @@ -1,89 +1,89 @@
/*
* Copyright 2010-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.geo;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*;
import java.util.List;
import org.junit.Test;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.Venue;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.data.mongodb.core.index.IndexField;
import org.springframework.data.mongodb.core.index.IndexInfo;
import org.springframework.data.mongodb.core.query.NearQuery;
/**
* @author Christoph Strobl
*/
public class GeoSpatial2DSphereTests extends AbstractGeoSpatialTests {
@Test // DATAMONGO-360
public void indexInfoIsCorrect() {
IndexOperations operations = template.indexOps(Venue.class);
List<IndexInfo> indexInfo = operations.getIndexInfo();
assertThat(indexInfo.size(), is(2));
List<IndexField> fields = indexInfo.get(0).getIndexFields();
assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC)));
fields = indexInfo.get(1).getIndexFields();
assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.geo("location")));
}
@Test // DATAMONGO-1110
public void geoNearWithMinDistance() {
NearQuery geoNear = NearQuery.near(-73, 40, Metrics.KILOMETERS).num(10).minDistance(1);
GeoResults<Venue> result = template.geoNear(geoNear, Venue.class);
assertThat(result.getContent().size(), is(not(0)));
assertThat(result.getAverageDistance().getMetric(), is((Metric) Metrics.KILOMETERS));
}
@Test // DATAMONGO-1110
public void nearSphereWithMinDistance() {
Point point = new Point(-73.99171, 40.738868);
List<Venue> venues = template.find(query(where("location").nearSphere(point).minDistance(0.01)), Venue.class);
assertThat(venues.size(), is(1));
}
@Override
protected void createIndex() {
template.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE));
}
@Override
protected void dropIndex() {
template.indexOps(Venue.class).dropIndex("location_2dsphere");
}
}
/*
* Copyright 2010-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.geo;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*;
import java.util.List;
import org.junit.Test;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.Venue;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.data.mongodb.core.index.IndexField;
import org.springframework.data.mongodb.core.index.IndexInfo;
import org.springframework.data.mongodb.core.query.NearQuery;
/**
* @author Christoph Strobl
*/
public class GeoSpatial2DSphereTests extends AbstractGeoSpatialTests {
@Test // DATAMONGO-360
public void indexInfoIsCorrect() {
IndexOperations operations = template.indexOps(Venue.class);
List<IndexInfo> indexInfo = operations.getIndexInfo();
assertThat(indexInfo.size(), is(2));
List<IndexField> fields = indexInfo.get(0).getIndexFields();
assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC)));
fields = indexInfo.get(1).getIndexFields();
assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.geo("location")));
}
@Test // DATAMONGO-1110
public void geoNearWithMinDistance() {
NearQuery geoNear = NearQuery.near(-73, 40, Metrics.KILOMETERS).num(10).minDistance(1);
GeoResults<Venue> result = template.geoNear(geoNear, Venue.class);
assertThat(result.getContent().size(), is(not(0)));
assertThat(result.getAverageDistance().getMetric(), is((Metric) Metrics.KILOMETERS));
}
@Test // DATAMONGO-1110
public void nearSphereWithMinDistance() {
Point point = new Point(-73.99171, 40.738868);
List<Venue> venues = template.find(query(where("location").nearSphere(point).minDistance(0.01)), Venue.class);
assertThat(venues.size(), is(1));
}
@Override
protected void createIndex() {
template.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE));
}
@Override
protected void dropIndex() {
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 @@ @@ -1,79 +1,79 @@
/*
* Copyright 2010-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.geo;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*;
import java.util.List;
import org.junit.Test;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.Venue;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.data.mongodb.core.index.IndexField;
import org.springframework.data.mongodb.core.index.IndexInfo;
/**
* Modified from https://github.com/deftlabs/mongo-java-geospatial-example
*
* @author Mark Pollack
* @author Oliver Gierke
* @author Thomas Darimont
* @author Christoph Strobl
*/
public class GeoSpatial2DTests extends AbstractGeoSpatialTests {
@Test
public void nearPoint() {
Point point = new Point(-73.99171, 40.738868);
List<Venue> venues = template.find(query(where("location").near(point).maxDistance(0.01)), Venue.class);
assertThat(venues.size(), is(7));
}
@Test // DATAMONGO-360
public void indexInfoIsCorrect() {
IndexOperations operations = template.indexOps(Venue.class);
List<IndexInfo> indexInfo = operations.getIndexInfo();
assertThat(indexInfo.size(), is(2));
List<IndexField> fields = indexInfo.get(0).getIndexFields();
assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC)));
fields = indexInfo.get(1).getIndexFields();
assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.geo("location")));
}
@Override
protected void createIndex() {
template.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2D));
}
@Override
protected void dropIndex() {
template.indexOps(Venue.class).dropIndex("location_2d");
}
}
/*
* Copyright 2010-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.geo;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*;
import java.util.List;
import org.junit.Test;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.Venue;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.data.mongodb.core.index.IndexField;
import org.springframework.data.mongodb.core.index.IndexInfo;
/**
* Modified from https://github.com/deftlabs/mongo-java-geospatial-example
*
* @author Mark Pollack
* @author Oliver Gierke
* @author Thomas Darimont
* @author Christoph Strobl
*/
public class GeoSpatial2DTests extends AbstractGeoSpatialTests {
@Test
public void nearPoint() {
Point point = new Point(-73.99171, 40.738868);
List<Venue> venues = template.find(query(where("location").near(point).maxDistance(0.01)), Venue.class);
assertThat(venues.size(), is(7));
}
@Test // DATAMONGO-360
public void indexInfoIsCorrect() {
IndexOperations operations = template.indexOps(Venue.class);
List<IndexInfo> indexInfo = operations.getIndexInfo();
assertThat(indexInfo.size(), is(2));
List<IndexField> fields = indexInfo.get(0).getIndexFields();
assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC)));
fields = indexInfo.get(1).getIndexFields();
assertThat(fields.size(), is(1));
assertThat(fields, hasItem(IndexField.geo("location")));
}
@Override
protected void createIndex() {
template.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2D));
}
@Override
protected void dropIndex() {
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 @@ @@ -1,50 +1,50 @@
/*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.mapping;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.mapping.event.LoggingEventListener;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
public class GeoIndexedAppConfig extends AbstractMongoConfiguration {
public static String GEO_DB = "database";
public static String GEO_COLLECTION = "geolocation";
@Override
public String getDatabaseName() {
return GEO_DB;
}
@Override
@Bean
public MongoClient mongoClient() {
return new MongoClient("127.0.0.1");
}
@Override
public String getMappingBasePackage() {
return "org.springframework.data.mongodb.core.core.mapping";
}
@Bean
public LoggingEventListener mappingEventsListener() {
return new LoggingEventListener();
}
}
/*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.mapping;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.mapping.event.LoggingEventListener;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
public class GeoIndexedAppConfig extends AbstractMongoConfiguration {
public static String GEO_DB = "database";
public static String GEO_COLLECTION = "geolocation";
@Override
public String getDatabaseName() {
return GEO_DB;
}
@Override
@Bean
public MongoClient mongoClient() {
return new MongoClient("127.0.0.1");
}
@Override
public String getMappingBasePackage() {
return "org.springframework.data.mongodb.core.core.mapping";
}
@Bean
public LoggingEventListener mappingEventsListener() {
return new LoggingEventListener();
}
}

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

@ -1,216 +1,216 @@ @@ -1,216 +1,216 @@
/*
* Copyright 2010-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.test.util.IsBsonObject.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.InvalidMongoDbApiUsageException;
import org.springframework.data.mongodb.core.geo.GeoJsonLineString;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
/**
* @author Oliver Gierke
* @author Thomas Darimont
* @author Christoph Strobl
*/
public class CriteriaTests {
@Test
public void testSimpleCriteria() {
Criteria c = new Criteria("name").is("Bubba");
assertEquals(Document.parse("{ \"name\" : \"Bubba\"}"), c.getCriteriaObject());
}
@Test
public void testNotEqualCriteria() {
Criteria c = new Criteria("name").ne("Bubba");
assertEquals(Document.parse("{ \"name\" : { \"$ne\" : \"Bubba\"}}"), c.getCriteriaObject());
}
@Test
public void buildsIsNullCriteriaCorrectly() {
Document reference = new Document("name", null);
Criteria criteria = new Criteria("name").is(null);
assertThat(criteria.getCriteriaObject(), is(reference));
}
@Test
public void testChainedCriteria() {
Criteria c = new Criteria("name").is("Bubba").and("age").lt(21);
assertEquals(Document.parse("{ \"name\" : \"Bubba\" , \"age\" : { \"$lt\" : 21}}"), c.getCriteriaObject());
}
@Test(expected = InvalidMongoDbApiUsageException.class)
public void testCriteriaWithMultipleConditionsForSameKey() {
Criteria c = new Criteria("name").gte("M").and("name").ne("A");
c.getCriteriaObject();
}
@Test
public void equalIfCriteriaMatches() {
Criteria left = new Criteria("name").is("Foo").and("lastname").is("Bar");
Criteria right = new Criteria("name").is("Bar").and("lastname").is("Bar");
assertThat(left, is(not(right)));
assertThat(right, is(not(left)));
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-507
public void shouldThrowExceptionWhenTryingToNegateAndOperation() {
new Criteria() //
.not() //
.andOperator(Criteria.where("delete").is(true).and("_id").is(42)); //
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-507
public void shouldThrowExceptionWhenTryingToNegateOrOperation() {
new Criteria() //
.not() //
.orOperator(Criteria.where("delete").is(true).and("_id").is(42)); //
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-507
public void shouldThrowExceptionWhenTryingToNegateNorOperation() {
new Criteria() //
.not() //
.norOperator(Criteria.where("delete").is(true).and("_id").is(42)); //
}
@Test // DATAMONGO-507
public void shouldNegateFollowingSimpleExpression() {
Criteria c = Criteria.where("age").not().gt(18).and("status").is("student");
Document co = c.getCriteriaObject();
assertThat(co, is(notNullValue()));
assertThat(co, is(Document.parse("{ \"age\" : { \"$not\" : { \"$gt\" : 18}} , \"status\" : \"student\"}")));
}
@Test // DATAMONGO-1068
public void getCriteriaObjectShouldReturnEmptyDocumentWhenNoCriteriaSpecified() {
Document document = new Criteria().getCriteriaObject();
assertThat(document, equalTo(new Document()));
}
@Test // DATAMONGO-1068
public void getCriteriaObjectShouldUseCritieraValuesWhenNoKeyIsPresent() {
Document document = new Criteria().lt("foo").getCriteriaObject();
assertThat(document, equalTo(new Document().append("$lt", "foo")));
}
@Test // DATAMONGO-1068
public void getCriteriaObjectShouldUseCritieraValuesWhenNoKeyIsPresentButMultipleCriteriasPresent() {
Document document = new Criteria().lt("foo").gt("bar").getCriteriaObject();
assertThat(document, equalTo(new Document().append("$lt", "foo").append("$gt", "bar")));
}
@Test // DATAMONGO-1068
public void getCriteriaObjectShouldRespectNotWhenNoKeyPresent() {
Document document = new Criteria().lt("foo").not().getCriteriaObject();
assertThat(document, equalTo(new Document().append("$not", new Document("$lt", "foo"))));
}
@Test // DATAMONGO-1135
public void geoJsonTypesShouldBeWrappedInGeometry() {
Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$near.$geometry", new GeoJsonPoint(100, 200)));
}
@Test // DATAMONGO-1135
public void legacyCoordinateTypesShouldNotBeWrappedInGeometry() {
Document document = new Criteria("foo").near(new Point(100, 200)).getCriteriaObject();
assertThat(document, isBsonObject().notContaining("foo.$near.$geometry"));
}
@Test // DATAMONGO-1135
public void maxDistanceShouldBeMappedInsideNearWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).maxDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$near.$maxDistance", 50D));
}
@Test // DATAMONGO-1135
public void maxDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).maxDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$nearSphere.$maxDistance", 50D));
}
@Test // DATAMONGO-1110
public void minDistanceShouldBeMappedInsideNearWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).minDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$near.$minDistance", 50D));
}
@Test // DATAMONGO-1110
public void minDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).minDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$nearSphere.$minDistance", 50D));
}
@Test // DATAMONGO-1110
public void minAndMaxDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).minDistance(50D).maxDistance(100D)
.getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$nearSphere.$minDistance", 50D));
assertThat(document, isBsonObject().containing("foo.$nearSphere.$maxDistance", 100D));
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-1134
public void intersectsShouldThrowExceptionWhenCalledWihtNullValue() {
new Criteria("foo").intersects(null);
}
@Test // DATAMONGO-1134
public void intersectsShouldWrapGeoJsonTypeInGeometryCorrectly() {
GeoJsonLineString lineString = new GeoJsonLineString(new Point(0, 0), new Point(10, 10));
Document document = new Criteria("foo").intersects(lineString).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$geoIntersects.$geometry", lineString));
}
}
/*
* Copyright 2010-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.mongodb.test.util.IsBsonObject.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.InvalidMongoDbApiUsageException;
import org.springframework.data.mongodb.core.geo.GeoJsonLineString;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
/**
* @author Oliver Gierke
* @author Thomas Darimont
* @author Christoph Strobl
*/
public class CriteriaTests {
@Test
public void testSimpleCriteria() {
Criteria c = new Criteria("name").is("Bubba");
assertEquals(Document.parse("{ \"name\" : \"Bubba\"}"), c.getCriteriaObject());
}
@Test
public void testNotEqualCriteria() {
Criteria c = new Criteria("name").ne("Bubba");
assertEquals(Document.parse("{ \"name\" : { \"$ne\" : \"Bubba\"}}"), c.getCriteriaObject());
}
@Test
public void buildsIsNullCriteriaCorrectly() {
Document reference = new Document("name", null);
Criteria criteria = new Criteria("name").is(null);
assertThat(criteria.getCriteriaObject(), is(reference));
}
@Test
public void testChainedCriteria() {
Criteria c = new Criteria("name").is("Bubba").and("age").lt(21);
assertEquals(Document.parse("{ \"name\" : \"Bubba\" , \"age\" : { \"$lt\" : 21}}"), c.getCriteriaObject());
}
@Test(expected = InvalidMongoDbApiUsageException.class)
public void testCriteriaWithMultipleConditionsForSameKey() {
Criteria c = new Criteria("name").gte("M").and("name").ne("A");
c.getCriteriaObject();
}
@Test
public void equalIfCriteriaMatches() {
Criteria left = new Criteria("name").is("Foo").and("lastname").is("Bar");
Criteria right = new Criteria("name").is("Bar").and("lastname").is("Bar");
assertThat(left, is(not(right)));
assertThat(right, is(not(left)));
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-507
public void shouldThrowExceptionWhenTryingToNegateAndOperation() {
new Criteria() //
.not() //
.andOperator(Criteria.where("delete").is(true).and("_id").is(42)); //
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-507
public void shouldThrowExceptionWhenTryingToNegateOrOperation() {
new Criteria() //
.not() //
.orOperator(Criteria.where("delete").is(true).and("_id").is(42)); //
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-507
public void shouldThrowExceptionWhenTryingToNegateNorOperation() {
new Criteria() //
.not() //
.norOperator(Criteria.where("delete").is(true).and("_id").is(42)); //
}
@Test // DATAMONGO-507
public void shouldNegateFollowingSimpleExpression() {
Criteria c = Criteria.where("age").not().gt(18).and("status").is("student");
Document co = c.getCriteriaObject();
assertThat(co, is(notNullValue()));
assertThat(co, is(Document.parse("{ \"age\" : { \"$not\" : { \"$gt\" : 18}} , \"status\" : \"student\"}")));
}
@Test // DATAMONGO-1068
public void getCriteriaObjectShouldReturnEmptyDocumentWhenNoCriteriaSpecified() {
Document document = new Criteria().getCriteriaObject();
assertThat(document, equalTo(new Document()));
}
@Test // DATAMONGO-1068
public void getCriteriaObjectShouldUseCritieraValuesWhenNoKeyIsPresent() {
Document document = new Criteria().lt("foo").getCriteriaObject();
assertThat(document, equalTo(new Document().append("$lt", "foo")));
}
@Test // DATAMONGO-1068
public void getCriteriaObjectShouldUseCritieraValuesWhenNoKeyIsPresentButMultipleCriteriasPresent() {
Document document = new Criteria().lt("foo").gt("bar").getCriteriaObject();
assertThat(document, equalTo(new Document().append("$lt", "foo").append("$gt", "bar")));
}
@Test // DATAMONGO-1068
public void getCriteriaObjectShouldRespectNotWhenNoKeyPresent() {
Document document = new Criteria().lt("foo").not().getCriteriaObject();
assertThat(document, equalTo(new Document().append("$not", new Document("$lt", "foo"))));
}
@Test // DATAMONGO-1135
public void geoJsonTypesShouldBeWrappedInGeometry() {
Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$near.$geometry", new GeoJsonPoint(100, 200)));
}
@Test // DATAMONGO-1135
public void legacyCoordinateTypesShouldNotBeWrappedInGeometry() {
Document document = new Criteria("foo").near(new Point(100, 200)).getCriteriaObject();
assertThat(document, isBsonObject().notContaining("foo.$near.$geometry"));
}
@Test // DATAMONGO-1135
public void maxDistanceShouldBeMappedInsideNearWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).maxDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$near.$maxDistance", 50D));
}
@Test // DATAMONGO-1135
public void maxDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).maxDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$nearSphere.$maxDistance", 50D));
}
@Test // DATAMONGO-1110
public void minDistanceShouldBeMappedInsideNearWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").near(new GeoJsonPoint(100, 200)).minDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$near.$minDistance", 50D));
}
@Test // DATAMONGO-1110
public void minDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).minDistance(50D).getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$nearSphere.$minDistance", 50D));
}
@Test // DATAMONGO-1110
public void minAndMaxDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() {
Document document = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).minDistance(50D).maxDistance(100D)
.getCriteriaObject();
assertThat(document, isBsonObject().containing("foo.$nearSphere.$minDistance", 50D));
assertThat(document, isBsonObject().containing("foo.$nearSphere.$maxDistance", 100D));
}
@Test(expected = IllegalArgumentException.class) // DATAMONGO-1134
public void intersectsShouldThrowExceptionWhenCalledWihtNullValue() {
new Criteria("foo").intersects(null);
}
@Test // DATAMONGO-1134
public void intersectsShouldWrapGeoJsonTypeInGeometryCorrectly() {
GeoJsonLineString lineString = new GeoJsonLineString(new Point(0, 0), new Point(10, 10));
Document document = new Criteria("foo").intersects(lineString).getCriteriaObject();
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 @@ @@ -1,95 +1,95 @@
/*
* Copyright 2010-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.Index.Duplicates;
/**
* Unit tests for {@link Index}.
*
* @author Oliver Gierke
* @author Laurent Canet
*/
public class IndexUnitTests {
@Test
public void testWithAscendingIndex() {
Index i = new Index().on("name", Direction.ASC);
assertEquals(Document.parse("{ \"name\" : 1}"), i.getIndexKeys());
}
@Test
public void testWithDescendingIndex() {
Index i = new Index().on("name", Direction.DESC);
assertEquals(Document.parse("{ \"name\" : -1}"), i.getIndexKeys());
}
@Test
public void testNamedMultiFieldUniqueIndex() {
Index i = new Index().on("name", Direction.ASC).on("age", Direction.DESC);
i.named("test").unique();
assertEquals(Document.parse("{ \"name\" : 1 , \"age\" : -1}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"name\" : \"test\" , \"unique\" : true}"), i.getIndexOptions());
}
@Test
public void testWithSparse() {
Index i = new Index().on("name", Direction.ASC);
i.sparse().unique();
assertEquals(Document.parse("{ \"name\" : 1}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"unique\" : true , \"sparse\" : true}"), i.getIndexOptions());
}
@Test
public void testGeospatialIndex() {
GeospatialIndex i = new GeospatialIndex("location").withMin(0);
assertEquals(Document.parse("{ \"location\" : \"2d\"}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"min\" : 0}"), i.getIndexOptions());
}
@Test // DATAMONGO-778
public void testGeospatialIndex2DSphere() {
GeospatialIndex i = new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE);
assertEquals(Document.parse("{ \"location\" : \"2dsphere\"}"), i.getIndexKeys());
assertEquals(Document.parse("{ }"), i.getIndexOptions());
}
@Test // DATAMONGO-778
public void testGeospatialIndexGeoHaystack() {
GeospatialIndex i = new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_HAYSTACK)
.withAdditionalField("name").withBucketSize(40);
assertEquals(Document.parse("{ \"location\" : \"geoHaystack\" , \"name\" : 1}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"bucketSize\" : 40.0}"), i.getIndexOptions());
}
@Test
public void ensuresPropertyOrder() {
Index on = new Index("foo", Direction.ASC).on("bar", Direction.ASC);
assertThat(on.getIndexKeys(), is(Document.parse("{ \"foo\" : 1 , \"bar\" : 1}")));
}
}
/*
* Copyright 2010-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.Index.Duplicates;
/**
* Unit tests for {@link Index}.
*
* @author Oliver Gierke
* @author Laurent Canet
*/
public class IndexUnitTests {
@Test
public void testWithAscendingIndex() {
Index i = new Index().on("name", Direction.ASC);
assertEquals(Document.parse("{ \"name\" : 1}"), i.getIndexKeys());
}
@Test
public void testWithDescendingIndex() {
Index i = new Index().on("name", Direction.DESC);
assertEquals(Document.parse("{ \"name\" : -1}"), i.getIndexKeys());
}
@Test
public void testNamedMultiFieldUniqueIndex() {
Index i = new Index().on("name", Direction.ASC).on("age", Direction.DESC);
i.named("test").unique();
assertEquals(Document.parse("{ \"name\" : 1 , \"age\" : -1}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"name\" : \"test\" , \"unique\" : true}"), i.getIndexOptions());
}
@Test
public void testWithSparse() {
Index i = new Index().on("name", Direction.ASC);
i.sparse().unique();
assertEquals(Document.parse("{ \"name\" : 1}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"unique\" : true , \"sparse\" : true}"), i.getIndexOptions());
}
@Test
public void testGeospatialIndex() {
GeospatialIndex i = new GeospatialIndex("location").withMin(0);
assertEquals(Document.parse("{ \"location\" : \"2d\"}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"min\" : 0}"), i.getIndexOptions());
}
@Test // DATAMONGO-778
public void testGeospatialIndex2DSphere() {
GeospatialIndex i = new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE);
assertEquals(Document.parse("{ \"location\" : \"2dsphere\"}"), i.getIndexKeys());
assertEquals(Document.parse("{ }"), i.getIndexOptions());
}
@Test // DATAMONGO-778
public void testGeospatialIndexGeoHaystack() {
GeospatialIndex i = new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_HAYSTACK)
.withAdditionalField("name").withBucketSize(40);
assertEquals(Document.parse("{ \"location\" : \"geoHaystack\" , \"name\" : 1}"), i.getIndexKeys());
assertEquals(Document.parse("{ \"bucketSize\" : 40.0}"), i.getIndexOptions());
}
@Test
public void ensuresPropertyOrder() {
Index on = new Index("foo", Direction.ASC).on("bar", Direction.ASC);
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 @@ @@ -1,54 +1,54 @@
/*
* Copyright 2010-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
/**
* Unit tests for sorting.
*
* @author Oliver Gierke
* @author Mark Paluch
*/
public class SortTests {
@Test
public void testWithSortAscending() {
Query s = new Query().with(Sort.by(Direction.ASC, "name"));
assertEquals(Document.parse("{ \"name\" : 1}"), s.getSortObject());
}
@Test
public void testWithSortDescending() {
Query s = new Query().with(Sort.by(Direction.DESC, "name"));
assertEquals(Document.parse("{ \"name\" : -1}"), s.getSortObject());
}
@Test // DATADOC-177
public void preservesOrderKeysOnMultipleSorts() {
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}")));
}
}
/*
* Copyright 2010-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.bson.Document;
import org.junit.Test;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
/**
* Unit tests for sorting.
*
* @author Oliver Gierke
* @author Mark Paluch
*/
public class SortTests {
@Test
public void testWithSortAscending() {
Query s = new Query().with(Sort.by(Direction.ASC, "name"));
assertEquals(Document.parse("{ \"name\" : 1}"), s.getSortObject());
}
@Test
public void testWithSortDescending() {
Query s = new Query().with(Sort.by(Direction.DESC, "name"));
assertEquals(Document.parse("{ \"name\" : -1}"), s.getSortObject());
}
@Test // DATADOC-177
public void preservesOrderKeysOnMultipleSorts() {
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}")));
}
}

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

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

Loading…
Cancel
Save