Polished formatting and Javadoc.
This commit is contained in:
@@ -143,11 +143,11 @@ public class MappingMongoConverterParser extends AbstractBeanDefinitionParser {
|
||||
List<Element> customConvertersElements = DomUtils.getChildElementsByTagName(element, "custom-converters");
|
||||
|
||||
if (customConvertersElements.size() == 1) {
|
||||
|
||||
|
||||
Element customerConvertersElement = customConvertersElements.get(0);
|
||||
ManagedList<BeanMetadataElement> converterBeans = new ManagedList<BeanMetadataElement>();
|
||||
List<Element> converterElements = DomUtils.getChildElementsByTagName(customerConvertersElement, "converter");
|
||||
|
||||
|
||||
if (converterElements != null) {
|
||||
for (Element listenerElement : converterElements) {
|
||||
converterBeans.add(parseConverter(listenerElement, parserContext));
|
||||
@@ -158,9 +158,9 @@ public class MappingMongoConverterParser extends AbstractBeanDefinitionParser {
|
||||
String packageToScan = customerConvertersElement.getAttribute(BASE_PACKAGE);
|
||||
if (StringUtils.hasText(packageToScan)) {
|
||||
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
|
||||
provider.addExcludeFilter(new NegatingFilter(new AssignableTypeFilter(Converter.class), new AssignableTypeFilter(
|
||||
GenericConverter.class)));
|
||||
|
||||
provider.addExcludeFilter(new NegatingFilter(new AssignableTypeFilter(Converter.class),
|
||||
new AssignableTypeFilter(GenericConverter.class)));
|
||||
|
||||
for (BeanDefinition candidate : provider.findCandidateComponents(packageToScan)) {
|
||||
converterBeans.add(candidate);
|
||||
}
|
||||
@@ -221,7 +221,7 @@ public class MappingMongoConverterParser extends AbstractBeanDefinitionParser {
|
||||
|
||||
/**
|
||||
* {@link TypeFilter} that returns {@literal false} in case any of the given delegates matches.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
private static class NegatingFilter implements TypeFilter {
|
||||
|
||||
@@ -21,15 +21,16 @@ import com.mongodb.DBObject;
|
||||
import com.mongodb.MongoException;
|
||||
|
||||
/**
|
||||
* An interface used by {@link MongoTemplate} for processing documents returned from a MongoDB query on a per-document basis.
|
||||
* Implementations of this interface perform the actual work of prcoessing each document but don't need to worry about
|
||||
* exception handling. {@MongoException}s will be caught and translated by the calling MongoTemplate
|
||||
* An interface used by {@link MongoTemplate} for processing documents returned from a MongoDB query on a per-document
|
||||
* basis. Implementations of this interface perform the actual work of prcoessing each document but don't need to worry
|
||||
* about exception handling. {@MongoException}s will be caught and translated by the calling
|
||||
* MongoTemplate
|
||||
*
|
||||
* An DocumentCallbackHandler is typically stateful: It keeps the result state within the object, to be available later for later
|
||||
* inspection.
|
||||
* An DocumentCallbackHandler is typically stateful: It keeps the result state within the object, to be available later
|
||||
* for later inspection.
|
||||
*
|
||||
* @author Mark Pollack
|
||||
*
|
||||
*
|
||||
*/
|
||||
public interface DocumentCallbackHandler {
|
||||
|
||||
|
||||
@@ -18,9 +18,9 @@ package org.springframework.data.mongodb.core;
|
||||
public class FindAndModifyOptions {
|
||||
|
||||
boolean returnNew;
|
||||
|
||||
|
||||
boolean upsert;
|
||||
|
||||
|
||||
boolean remove;
|
||||
|
||||
/**
|
||||
@@ -31,17 +31,17 @@ public class FindAndModifyOptions {
|
||||
public static FindAndModifyOptions options() {
|
||||
return new FindAndModifyOptions();
|
||||
}
|
||||
|
||||
|
||||
public FindAndModifyOptions returnNew(boolean returnNew) {
|
||||
this.returnNew = returnNew;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public FindAndModifyOptions upsert(boolean upsert) {
|
||||
this.upsert = upsert;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public FindAndModifyOptions remove(boolean remove) {
|
||||
this.remove = remove;
|
||||
return this;
|
||||
@@ -58,7 +58,5 @@ public class FindAndModifyOptions {
|
||||
public boolean isRemove() {
|
||||
return remove;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -20,35 +20,38 @@ import com.mongodb.DBObject;
|
||||
import com.mongodb.WriteConcern;
|
||||
|
||||
/**
|
||||
* Represents an action taken against the collection. Used by {@link WriteConcernResolver} to determine a custom
|
||||
* Represents an action taken against the collection. Used by {@link WriteConcernResolver} to determine a custom
|
||||
* WriteConcern based on this information.
|
||||
*
|
||||
* Properties that will always be not-null are collectionName and defaultWriteConcern.
|
||||
* The EntityClass is null only for the MongoActionOperaton.INSERT_LIST.
|
||||
* Properties that will always be not-null are collectionName and defaultWriteConcern. The EntityClass is null only for
|
||||
* the MongoActionOperaton.INSERT_LIST.
|
||||
*
|
||||
* INSERT, SAVE have null query,
|
||||
* REMOVE has null document
|
||||
* INSERT_LIST has null entityClass, document, and query.
|
||||
* <ul>
|
||||
* <li>INSERT, SAVE have null query</li>
|
||||
* <li>REMOVE has null document</li>
|
||||
* <li>INSERT_LIST has null entityClass, document, and query</li>
|
||||
* </ul>
|
||||
*
|
||||
* @author Mark Pollack
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class MongoAction {
|
||||
|
||||
|
||||
private String collectionName;
|
||||
|
||||
|
||||
private WriteConcern defaultWriteConcern;
|
||||
|
||||
|
||||
private Class<?> entityClass;
|
||||
|
||||
|
||||
private MongoActionOperation mongoActionOperation;
|
||||
|
||||
|
||||
private DBObject query;
|
||||
|
||||
|
||||
private DBObject document;
|
||||
|
||||
/**
|
||||
* Create an instance of a MongoAction
|
||||
*
|
||||
* @param defaultWriteConcern the default write concern
|
||||
* @param mongoActionOperation action being taken against the collection
|
||||
* @param collectionName the collection name
|
||||
@@ -90,7 +93,5 @@ public class MongoAction {
|
||||
public DBObject getDocument() {
|
||||
return document;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -16,18 +16,14 @@
|
||||
package org.springframework.data.mongodb.core;
|
||||
|
||||
/**
|
||||
* Enumeration for operations on a collection. Used with {@link MongoAction} to help determine the
|
||||
* WriteConcern to use for a given mutating operation
|
||||
* Enumeration for operations on a collection. Used with {@link MongoAction} to help determine the WriteConcern to use
|
||||
* for a given mutating operation
|
||||
*
|
||||
* @author Mark Pollack
|
||||
* @see MongoAction
|
||||
*
|
||||
*
|
||||
*/
|
||||
public enum MongoActionOperation {
|
||||
|
||||
REMOVE,
|
||||
UPDATE,
|
||||
INSERT,
|
||||
INSERT_LIST,
|
||||
SAVE
|
||||
|
||||
REMOVE, UPDATE, INSERT, INSERT_LIST, SAVE
|
||||
}
|
||||
|
||||
@@ -56,7 +56,8 @@ public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory {
|
||||
public SimpleMongoDbFactory(Mongo mongo, String databaseName) {
|
||||
Assert.notNull(mongo, "Mongo must not be null");
|
||||
Assert.hasText(databaseName, "Database name must not be empty");
|
||||
Assert.isTrue(databaseName.matches("[\\w-]+"), "Database name must only contain letters, numbers, underscores and dashes!");
|
||||
Assert.isTrue(databaseName.matches("[\\w-]+"),
|
||||
"Database name must only contain letters, numbers, underscores and dashes!");
|
||||
this.mongo = mongo;
|
||||
this.databaseName = databaseName;
|
||||
}
|
||||
@@ -73,7 +74,7 @@ public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory {
|
||||
this.username = userCredentials.getUsername();
|
||||
this.password = userCredentials.getPassword();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoURI}.
|
||||
*
|
||||
@@ -82,7 +83,7 @@ public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory {
|
||||
* @throws UnknownHostException
|
||||
* @see MongoURI
|
||||
*/
|
||||
public SimpleMongoDbFactory(MongoURI uri) throws MongoException, UnknownHostException {
|
||||
public SimpleMongoDbFactory(MongoURI uri) throws MongoException, UnknownHostException {
|
||||
this(new Mongo(uri), uri.getDatabase(), new UserCredentials(uri.getUsername(), parseChars(uri.getPassword())));
|
||||
}
|
||||
|
||||
@@ -94,7 +95,7 @@ public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory {
|
||||
public void setWriteConcern(WriteConcern writeConcern) {
|
||||
this.writeConcern = writeConcern;
|
||||
}
|
||||
|
||||
|
||||
public WriteConcern getWriteConcern() {
|
||||
return writeConcern;
|
||||
}
|
||||
@@ -130,7 +131,7 @@ public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory {
|
||||
public void destroy() throws Exception {
|
||||
mongo.close();
|
||||
}
|
||||
|
||||
|
||||
public static String parseChars(char[] chars) {
|
||||
if (chars == null) {
|
||||
return null;
|
||||
|
||||
@@ -24,14 +24,16 @@ import com.mongodb.WriteConcern;
|
||||
* Return the passed in default WriteConcern (a property on MongoAction) if no determination can be made.
|
||||
*
|
||||
* @author Mark Pollack
|
||||
*
|
||||
*
|
||||
*/
|
||||
public interface WriteConcernResolver {
|
||||
|
||||
/**
|
||||
* Resolve the WriteConcern given the MongoAction
|
||||
* @param action describes the context of the Mongo action. Contains a default WriteConcern to use if one should not be resolved.
|
||||
* @return a WriteConcern based on the passed in MongoAction value, maybe null
|
||||
*/
|
||||
WriteConcern resolve(MongoAction action);
|
||||
/**
|
||||
* Resolve the WriteConcern given the MongoAction
|
||||
*
|
||||
* @param action describes the context of the Mongo action. Contains a default WriteConcern to use if one should not
|
||||
* be resolved.
|
||||
* @return a WriteConcern based on the passed in MongoAction value, maybe null
|
||||
*/
|
||||
WriteConcern resolve(MongoAction action);
|
||||
}
|
||||
|
||||
@@ -50,23 +50,22 @@ public class DefaultMongoTypeMapper extends DefaultTypeMapper<DBObject> implemen
|
||||
public DefaultMongoTypeMapper() {
|
||||
this(DEFAULT_TYPE_KEY, Arrays.asList(SimpleTypeInformationMapper.INSTANCE));
|
||||
}
|
||||
|
||||
|
||||
public DefaultMongoTypeMapper(String typeKey) {
|
||||
super(new DBObjectTypeAliasAccessor(typeKey));
|
||||
this.typeKey = typeKey;
|
||||
}
|
||||
|
||||
public DefaultMongoTypeMapper(String typeKey, MappingContext<? extends PersistentEntity<?,?>, ?> mappingContext) {
|
||||
|
||||
public DefaultMongoTypeMapper(String typeKey, MappingContext<? extends PersistentEntity<?, ?>, ?> mappingContext) {
|
||||
super(new DBObjectTypeAliasAccessor(typeKey), mappingContext, Arrays.asList(SimpleTypeInformationMapper.INSTANCE));
|
||||
this.typeKey = typeKey;
|
||||
}
|
||||
|
||||
|
||||
public DefaultMongoTypeMapper(String typeKey, List<? extends TypeInformationMapper> mappers) {
|
||||
super(new DBObjectTypeAliasAccessor(typeKey), mappers);
|
||||
this.typeKey = typeKey;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.mongodb.core.convert.MongoTypeMapper#isTypeKey(java.lang.String)
|
||||
@@ -75,7 +74,6 @@ public class DefaultMongoTypeMapper extends DefaultTypeMapper<DBObject> implemen
|
||||
return typeKey == null ? false : typeKey.equals(key);
|
||||
}
|
||||
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.springframework.data.convert.DefaultTypeMapper#getFallbackTypeFor(java.lang.Object)
|
||||
*/
|
||||
@@ -83,29 +81,29 @@ public class DefaultMongoTypeMapper extends DefaultTypeMapper<DBObject> implemen
|
||||
protected TypeInformation<?> getFallbackTypeFor(DBObject source) {
|
||||
return source instanceof BasicDBList ? LIST_TYPE_INFO : MAP_TYPE_INFO;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public static final class DBObjectTypeAliasAccessor implements TypeAliasAccessor<DBObject> {
|
||||
|
||||
|
||||
private final String typeKey;
|
||||
|
||||
|
||||
public DBObjectTypeAliasAccessor(String typeKey) {
|
||||
this.typeKey = typeKey;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.convert.TypeAliasAccessor#readAliasFrom(java.lang.Object)
|
||||
*/
|
||||
public Object readAliasFrom(DBObject source) {
|
||||
|
||||
|
||||
if (source instanceof BasicDBList) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
return source.get(typeKey);
|
||||
}
|
||||
|
||||
|
||||
@@ -164,7 +164,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
|
||||
if (conversions.hasCustomReadTarget(dbo.getClass(), rawType)) {
|
||||
return conversionService.convert(dbo, rawType);
|
||||
}
|
||||
|
||||
|
||||
if (DBObject.class.isAssignableFrom(rawType)) {
|
||||
return (S) dbo;
|
||||
}
|
||||
@@ -286,7 +286,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
|
||||
|
||||
boolean handledByCustomConverter = conversions.getCustomWriteTarget(obj.getClass(), DBObject.class) != null;
|
||||
TypeInformation<? extends Object> type = ClassTypeInformation.from(obj.getClass());
|
||||
|
||||
|
||||
if (!handledByCustomConverter && !(dbo instanceof BasicDBList)) {
|
||||
typeMapper.writeType(type, dbo);
|
||||
}
|
||||
@@ -345,7 +345,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
|
||||
// Write the ID
|
||||
final MongoPersistentProperty idProperty = entity.getIdProperty();
|
||||
if (!dbo.containsField("_id") && null != idProperty) {
|
||||
|
||||
|
||||
try {
|
||||
Object id = wrapper.getProperty(idProperty, Object.class, useFieldAccessOnly);
|
||||
dbo.put("_id", idMapper.convertId(id));
|
||||
@@ -356,13 +356,13 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
|
||||
// Write the properties
|
||||
entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
|
||||
public void doWithPersistentProperty(MongoPersistentProperty prop) {
|
||||
|
||||
|
||||
if (prop.equals(idProperty)) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Object propertyObj = wrapper.getProperty(prop, prop.getType(), useFieldAccessOnly);
|
||||
|
||||
|
||||
if (null != propertyObj) {
|
||||
if (!conversions.isSimpleType(propertyObj.getClass())) {
|
||||
writePropertyInternal(propertyObj, dbo, prop);
|
||||
@@ -528,7 +528,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
|
||||
* @return
|
||||
*/
|
||||
protected DBObject writeMapInternal(Map<Object, Object> obj, DBObject dbo, TypeInformation<?> propertyType) {
|
||||
|
||||
|
||||
for (Map.Entry<Object, Object> entry : obj.entrySet()) {
|
||||
Object key = entry.getKey();
|
||||
Object val = entry.getValue();
|
||||
@@ -543,7 +543,8 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
|
||||
writeCollectionInternal(asCollection(val), propertyType.getMapValueType(), new BasicDBList()));
|
||||
} else {
|
||||
DBObject newDbo = new BasicDBObject();
|
||||
TypeInformation<?> valueTypeInfo = propertyType.isMap() ? propertyType.getMapValueType() : ClassTypeInformation.OBJECT;
|
||||
TypeInformation<?> valueTypeInfo = propertyType.isMap() ? propertyType.getMapValueType()
|
||||
: ClassTypeInformation.OBJECT;
|
||||
writeInternal(val, newDbo, valueTypeInfo);
|
||||
dbo.put(simpleKey, newDbo);
|
||||
}
|
||||
@@ -551,7 +552,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
|
||||
throw new MappingException("Cannot use a complex object as a key value.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return dbo;
|
||||
}
|
||||
|
||||
@@ -643,7 +644,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
|
||||
MongoPersistentProperty idProperty = targetEntity.getIdProperty();
|
||||
BeanWrapper<MongoPersistentEntity<Object>, Object> wrapper = BeanWrapper.create(target, conversionService);
|
||||
Object id = wrapper.getProperty(idProperty, Object.class, useFieldAccessOnly);
|
||||
|
||||
|
||||
if (null == id) {
|
||||
throw new MappingException("Cannot create a reference to an object with a NULL id.");
|
||||
}
|
||||
@@ -858,7 +859,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
|
||||
}
|
||||
return newDbl;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Removes the type information from the conversion result.
|
||||
*
|
||||
|
||||
@@ -66,7 +66,7 @@ public class Box implements Shape {
|
||||
list.add(getUpperRight().asList());
|
||||
return list;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.mongodb.core.geo.Shape#getCommand()
|
||||
@@ -74,7 +74,7 @@ public class Box implements Shape {
|
||||
public String getCommand() {
|
||||
return "$box";
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("Box [%s, %s]", first, second);
|
||||
|
||||
@@ -40,10 +40,10 @@ public class Circle implements Shape {
|
||||
*/
|
||||
@PersistenceConstructor
|
||||
public Circle(Point center, double radius) {
|
||||
|
||||
|
||||
Assert.notNull(center);
|
||||
Assert.isTrue(radius >= 0, "Radius must not be negative!");
|
||||
|
||||
|
||||
this.center = center;
|
||||
this.radius = radius;
|
||||
}
|
||||
@@ -76,7 +76,7 @@ public class Circle implements Shape {
|
||||
public double getRadius() {
|
||||
return radius;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.mongodb.core.geo.Shape#asList()
|
||||
@@ -87,7 +87,7 @@ public class Circle implements Shape {
|
||||
result.add(getRadius());
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.mongodb.core.geo.Shape#getCommand()
|
||||
@@ -104,26 +104,26 @@ public class Circle implements Shape {
|
||||
public String toString() {
|
||||
return String.format("Circle [center=%s, radius=%f]", center, radius);
|
||||
}
|
||||
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see java.lang.Object#equals(java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
|
||||
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
if (obj == null || !getClass().equals(obj.getClass())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
Circle that = (Circle) obj;
|
||||
|
||||
|
||||
return this.center.equals(that.center) && this.radius == that.radius;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#hashCode()
|
||||
|
||||
@@ -50,22 +50,22 @@ public class Polygon implements Shape, Iterable<Point> {
|
||||
this.points.addAll(Arrays.asList(x, y, z));
|
||||
this.points.addAll(Arrays.asList(others));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.mongodb.core.geo.Shape#asList()
|
||||
*/
|
||||
public List<List<Double>> asList() {
|
||||
|
||||
|
||||
List<List<Double>> result = new ArrayList<List<Double>>();
|
||||
|
||||
|
||||
for (Point point : points) {
|
||||
result.add(point.asList());
|
||||
}
|
||||
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.mongodb.core.geo.Shape#getCommand()
|
||||
@@ -73,7 +73,7 @@ public class Polygon implements Shape, Iterable<Point> {
|
||||
public String getCommand() {
|
||||
return "$polygon";
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Iterable#iterator()
|
||||
@@ -88,20 +88,20 @@ public class Polygon implements Shape, Iterable<Point> {
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
|
||||
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
if (obj == null || !getClass().equals(obj.getClass())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
Polygon that = (Polygon) obj;
|
||||
|
||||
|
||||
return this.points.equals(that.points);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#hashCode()
|
||||
|
||||
@@ -19,7 +19,7 @@ import java.util.List;
|
||||
|
||||
/**
|
||||
* Common interface for all shapes. Allows building MongoDB representations of them.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public interface Shape {
|
||||
@@ -31,7 +31,7 @@ public interface Shape {
|
||||
* @return
|
||||
*/
|
||||
List<? extends Object> asList();
|
||||
|
||||
|
||||
/**
|
||||
* Returns the command to be used to create the {@literal $within} criterion.
|
||||
*
|
||||
|
||||
@@ -31,7 +31,6 @@ public class IndexInfo {
|
||||
|
||||
private boolean sparse = false;
|
||||
|
||||
|
||||
public IndexInfo(Map<String, Order> fieldSpec, String name, boolean unique, boolean dropDuplicates, boolean sparse) {
|
||||
super();
|
||||
this.fieldSpec = fieldSpec;
|
||||
@@ -107,9 +106,8 @@ public class IndexInfo {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* [{ "v" : 1 , "key" : { "_id" : 1} , "ns" : "database.person" , "name" : "_id_"},
|
||||
{ "v" : 1 , "key" : { "age" : -1} , "ns" : "database.person" , "name" : "age_-1" , "unique" : true , "dropDups" : true}]
|
||||
* [{ "v" : 1 , "key" : { "_id" : 1} , "ns" : "database.person" , "name" : "_id_"}, { "v" : 1 , "key" : { "age" : -1}
|
||||
* , "ns" : "database.person" , "name" : "age_-1" , "unique" : true , "dropDups" : true}]
|
||||
*/
|
||||
}
|
||||
|
||||
@@ -23,12 +23,12 @@ import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
|
||||
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
|
||||
|
||||
/**
|
||||
* An implementation of ApplicationEventPublisher that will only fire MappingContextEvents for use by the index creator when
|
||||
* MongoTemplate is used 'stand-alone', that is not declared inside a Spring ApplicationContext.
|
||||
* An implementation of ApplicationEventPublisher that will only fire MappingContextEvents for use by the index creator
|
||||
* when MongoTemplate is used 'stand-alone', that is not declared inside a Spring ApplicationContext.
|
||||
*
|
||||
* Declare MongoTemplate inside an ApplicationContext to enable the publishing of all persistence events such as
|
||||
* {@link AfterLoadEvent}, {@link AfterSaveEvent}, etc.
|
||||
*
|
||||
* Declare MongoTemplate inside an ApplicationContext to enable the publishing of all persistence events such as
|
||||
* {@link AfterLoadEvent}, {@link AfterSaveEvent}, etc.
|
||||
*
|
||||
* @author Jon Brisbin <jbrisbin@vmware.com>
|
||||
*/
|
||||
public class MongoMappingEventPublisher implements ApplicationEventPublisher {
|
||||
|
||||
@@ -30,7 +30,8 @@ import org.springframework.data.util.TypeInformation;
|
||||
* @author Jon Brisbin <jbrisbin@vmware.com>
|
||||
* @author Oliver Gierke ogierke@vmware.com
|
||||
*/
|
||||
public class MongoMappingContext extends AbstractMappingContext<BasicMongoPersistentEntity<?>, MongoPersistentProperty> implements ApplicationContextAware {
|
||||
public class MongoMappingContext extends AbstractMappingContext<BasicMongoPersistentEntity<?>, MongoPersistentProperty>
|
||||
implements ApplicationContextAware {
|
||||
|
||||
private ApplicationContext context;
|
||||
|
||||
@@ -57,16 +58,16 @@ public class MongoMappingContext extends AbstractMappingContext<BasicMongoPersis
|
||||
*/
|
||||
@Override
|
||||
protected <T> BasicMongoPersistentEntity<T> createPersistentEntity(TypeInformation<T> typeInformation) {
|
||||
|
||||
|
||||
BasicMongoPersistentEntity<T> entity = new BasicMongoPersistentEntity<T>(typeInformation);
|
||||
|
||||
|
||||
if (context != null) {
|
||||
entity.setApplicationContext(context);
|
||||
}
|
||||
|
||||
|
||||
return entity;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
|
||||
|
||||
@@ -36,7 +36,7 @@ import com.mongodb.DBRef;
|
||||
public abstract class MongoSimpleTypes {
|
||||
|
||||
public static final Set<Class<?>> AUTOGENERATED_ID_TYPES;
|
||||
|
||||
|
||||
static {
|
||||
Set<Class<?>> classes = new HashSet<Class<?>>();
|
||||
classes.add(ObjectId.class);
|
||||
|
||||
@@ -31,7 +31,7 @@ public abstract class AbstractMongoEventListener<E> implements ApplicationListen
|
||||
|
||||
protected final Log LOG = LogFactory.getLog(getClass());
|
||||
private final Class<?> domainClass;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link AbstractMongoEventListener}.
|
||||
*/
|
||||
|
||||
@@ -39,9 +39,9 @@ public class AfterLoadEvent<T> extends MongoMappingEvent<DBObject> {
|
||||
* @param type must not be {@literal null}.
|
||||
*/
|
||||
public AfterLoadEvent(DBObject dbo, Class<T> type) {
|
||||
|
||||
|
||||
super(dbo, dbo);
|
||||
|
||||
|
||||
Assert.notNull(type, "Type must not be null!");
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@@ -19,24 +19,19 @@ import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DBObject;
|
||||
|
||||
/**
|
||||
* Collects the parameters required to perform a group operation on a collection. The query condition and the input collection are specified on the group method as method arguments
|
||||
* to be consistent with other operations, e.g. map-reduce.
|
||||
* Collects the parameters required to perform a group operation on a collection. The query condition and the input
|
||||
* collection are specified on the group method as method arguments to be consistent with other operations, e.g.
|
||||
* map-reduce.
|
||||
*
|
||||
* @author Mark Pollack
|
||||
*
|
||||
*/
|
||||
public class GroupBy {
|
||||
|
||||
private DBObject dboKeys;
|
||||
|
||||
private String keyFunction;
|
||||
|
||||
private String initial;
|
||||
|
||||
private DBObject initialDbObject;
|
||||
|
||||
private String reduce;
|
||||
|
||||
private String finalize;
|
||||
|
||||
public GroupBy(String... keys) {
|
||||
@@ -71,24 +66,22 @@ public class GroupBy {
|
||||
initial = initialDocument;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public GroupBy initialDocument(DBObject initialDocument) {
|
||||
initialDbObject = initialDocument;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public GroupBy reduceFunction(String reduceFunction) {
|
||||
reduce = reduceFunction;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public GroupBy finalizeFunction(String finalizeFunction) {
|
||||
finalize = finalizeFunction;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public DBObject getGroupByObject() {
|
||||
// return new GroupCommand(dbCollection, dboKeys, condition, initial, reduce, finalize);
|
||||
BasicDBObject dbo = new BasicDBObject();
|
||||
@@ -100,19 +93,15 @@ public class GroupBy {
|
||||
}
|
||||
|
||||
dbo.put("$reduce", reduce);
|
||||
|
||||
dbo.put("initial", initialDbObject);
|
||||
|
||||
dbo.put("initial", initialDbObject);
|
||||
if (initial != null) {
|
||||
dbo.put("initial", initial);
|
||||
}
|
||||
if (finalize != null) {
|
||||
dbo.put("finalize", finalize);
|
||||
}
|
||||
return dbo;
|
||||
return dbo;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -26,31 +26,27 @@ import com.mongodb.DBObject;
|
||||
* Collects the results of executing a group operation.
|
||||
*
|
||||
* @author Mark Pollack
|
||||
*
|
||||
* @param <T> The class in which the results are mapped onto, accessible via an interator.
|
||||
*/
|
||||
public class GroupByResults<T> implements Iterable<T> {
|
||||
|
||||
private final List<T> mappedResults;
|
||||
|
||||
private DBObject rawResults;
|
||||
|
||||
private final DBObject rawResults;
|
||||
|
||||
private double count;
|
||||
|
||||
private int keys;
|
||||
|
||||
private String serverUsed;
|
||||
|
||||
|
||||
public GroupByResults(List<T> mappedResults, DBObject rawResults) {
|
||||
Assert.notNull(mappedResults);
|
||||
Assert.notNull(rawResults);
|
||||
this.mappedResults = mappedResults;
|
||||
this.rawResults = rawResults;
|
||||
parseKeys();
|
||||
parseKeys();
|
||||
parseCount();
|
||||
parseServerUsed();
|
||||
}
|
||||
|
||||
|
||||
public double getCount() {
|
||||
return count;
|
||||
}
|
||||
@@ -58,36 +54,36 @@ public class GroupByResults<T> implements Iterable<T> {
|
||||
public int getKeys() {
|
||||
return keys;
|
||||
}
|
||||
|
||||
|
||||
public String getServerUsed() {
|
||||
return serverUsed;
|
||||
}
|
||||
|
||||
public Iterator<T> iterator() {
|
||||
return mappedResults.iterator();
|
||||
return mappedResults.iterator();
|
||||
}
|
||||
|
||||
|
||||
public DBObject getRawResults() {
|
||||
return rawResults;
|
||||
}
|
||||
|
||||
|
||||
private void parseCount() {
|
||||
Object object = rawResults.get("count");
|
||||
if (object instanceof Double) {
|
||||
count = (Double) object;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void parseKeys() {
|
||||
Object object = rawResults.get("keys");
|
||||
if (object instanceof Integer) {
|
||||
keys = (Integer) object;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void parseServerUsed() {
|
||||
//"serverUsed" : "127.0.0.1:27017"
|
||||
// "serverUsed" : "127.0.0.1:27017"
|
||||
Object object = rawResults.get("serverUsed");
|
||||
if (object instanceof String) {
|
||||
serverUsed = (String) object;
|
||||
|
||||
@@ -15,13 +15,14 @@
|
||||
*/
|
||||
package org.springframework.data.mongodb.core.mapreduce;
|
||||
|
||||
/**
|
||||
* @author Mark Pollack
|
||||
*/
|
||||
public class MapReduceCounts {
|
||||
|
||||
private int inputCount;
|
||||
|
||||
private int emitCount;
|
||||
|
||||
private int outputCount;
|
||||
private final int inputCount;
|
||||
private final int emitCount;
|
||||
private final int outputCount;
|
||||
|
||||
public MapReduceCounts(int inputCount, int emitCount, int outputCount) {
|
||||
super();
|
||||
@@ -42,12 +43,20 @@ public class MapReduceCounts {
|
||||
return outputCount;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#toString()
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MapReduceCounts [inputCount=" + inputCount + ", emitCount=" + emitCount + ", outputCount=" + outputCount
|
||||
+ "]";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#hashCode()
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
@@ -58,24 +67,31 @@ public class MapReduceCounts {
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see java.lang.Object#equals(java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
if (this == obj) {
|
||||
return true;
|
||||
if (obj == null)
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
MapReduceCounts other = (MapReduceCounts) obj;
|
||||
if (emitCount != other.emitCount)
|
||||
if (emitCount != other.emitCount) {
|
||||
return false;
|
||||
if (inputCount != other.inputCount)
|
||||
}
|
||||
if (inputCount != other.inputCount) {
|
||||
return false;
|
||||
if (outputCount != other.outputCount)
|
||||
}
|
||||
if (outputCount != other.outputCount) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -39,10 +39,9 @@ public class MapReduceOptions {
|
||||
private Boolean jsMode;
|
||||
|
||||
private Boolean verbose = true;
|
||||
|
||||
|
||||
private Map<String, Object> extraOptions = new HashMap<String, Object>();
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Static factory method to create a MapReduceOptions instance
|
||||
*
|
||||
@@ -189,12 +188,12 @@ public class MapReduceOptions {
|
||||
this.verbose = verbose;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add additional extra options that may not have a method on this class. This method will help if you use a
|
||||
* version of this client library with a server version that has added additional map-reduce options that do not
|
||||
* yet have an method for use in setting them.
|
||||
* options
|
||||
* Add additional extra options that may not have a method on this class. This method will help if you use a version
|
||||
* of this client library with a server version that has added additional map-reduce options that do not yet have an
|
||||
* method for use in setting them. options
|
||||
*
|
||||
* @param key The key option
|
||||
* @param value The value of the option
|
||||
* @return MapReduceOptions so that methods can be chained in a fluent API style
|
||||
@@ -203,40 +202,39 @@ public class MapReduceOptions {
|
||||
extraOptions.put(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public Map<String, Object> getExtraOptions() {
|
||||
return extraOptions;
|
||||
return extraOptions;
|
||||
}
|
||||
|
||||
|
||||
public String getFinalizeFunction() {
|
||||
return this.finalizeFunction;
|
||||
}
|
||||
|
||||
|
||||
public Boolean getJavaScriptMode() {
|
||||
return this.jsMode;
|
||||
}
|
||||
|
||||
|
||||
public String getOutputCollection() {
|
||||
return this.outputCollection;
|
||||
}
|
||||
|
||||
|
||||
public String getOutputDatabase() {
|
||||
return this.outputDatabase;
|
||||
}
|
||||
|
||||
|
||||
public Boolean getOutputSharded() {
|
||||
return this.outputSharded;
|
||||
}
|
||||
|
||||
|
||||
public MapReduceCommand.OutputType getOutputType() {
|
||||
return this.outputType;
|
||||
}
|
||||
|
||||
|
||||
public Map<String, Object> getScopeVariables() {
|
||||
return this.scopeVariables;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public DBObject getOptionsObject() {
|
||||
BasicDBObject cmd = new BasicDBObject();
|
||||
|
||||
@@ -253,7 +251,7 @@ public class MapReduceOptions {
|
||||
if (scopeVariables != null) {
|
||||
cmd.put("scope", scopeVariables);
|
||||
}
|
||||
|
||||
|
||||
if (!extraOptions.keySet().isEmpty()) {
|
||||
cmd.putAll(extraOptions);
|
||||
}
|
||||
|
||||
@@ -24,77 +24,77 @@ import com.mongodb.DBObject;
|
||||
|
||||
/**
|
||||
* Collects the results of performing a MapReduce operations.
|
||||
*
|
||||
* @author Mark Pollack
|
||||
*
|
||||
*
|
||||
* @param <T> The class in which the results are mapped onto, accessible via an interator.
|
||||
*/
|
||||
public class MapReduceResults<T> implements Iterable<T> {
|
||||
|
||||
private final List<T> mappedResults;
|
||||
|
||||
|
||||
private DBObject rawResults;
|
||||
|
||||
private MapReduceTiming mapReduceTiming;
|
||||
|
||||
|
||||
private MapReduceCounts mapReduceCounts;
|
||||
|
||||
|
||||
private String outputCollection;
|
||||
|
||||
|
||||
public MapReduceResults(List<T> mappedResults, DBObject rawResults) {
|
||||
Assert.notNull(mappedResults);
|
||||
Assert.notNull(rawResults);
|
||||
this.mappedResults = mappedResults;
|
||||
this.rawResults = rawResults;
|
||||
parseTiming(rawResults);
|
||||
parseCounts(rawResults);
|
||||
parseCounts(rawResults);
|
||||
if (rawResults.get("result") != null) {
|
||||
this.outputCollection = (String) rawResults.get("result");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public Iterator<T> iterator() {
|
||||
return mappedResults.iterator();
|
||||
return mappedResults.iterator();
|
||||
}
|
||||
|
||||
|
||||
public MapReduceTiming getTiming() {
|
||||
return mapReduceTiming;
|
||||
}
|
||||
|
||||
|
||||
public MapReduceCounts getCounts() {
|
||||
return mapReduceCounts;
|
||||
}
|
||||
|
||||
|
||||
public String getOutputCollection() {
|
||||
return outputCollection;
|
||||
}
|
||||
|
||||
|
||||
public DBObject getRawResults() {
|
||||
return rawResults;
|
||||
}
|
||||
|
||||
|
||||
protected void parseTiming(DBObject rawResults) {
|
||||
DBObject timing = (DBObject) rawResults.get("timing");
|
||||
if (timing != null) {
|
||||
if (timing.get("mapTime") != null && timing.get("emitLoop") != null && timing.get("total") != null) {
|
||||
mapReduceTiming = new MapReduceTiming( (Long)timing.get("mapTime"),
|
||||
(Integer)timing.get("emitLoop"),
|
||||
(Integer)timing.get("total"));
|
||||
mapReduceTiming = new MapReduceTiming((Long) timing.get("mapTime"), (Integer) timing.get("emitLoop"),
|
||||
(Integer) timing.get("total"));
|
||||
}
|
||||
} else {
|
||||
mapReduceTiming = new MapReduceTiming(-1,-1,-1);
|
||||
mapReduceTiming = new MapReduceTiming(-1, -1, -1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
protected void parseCounts(DBObject rawResults) {
|
||||
DBObject counts = (DBObject) rawResults.get("counts");
|
||||
if (counts != null) {
|
||||
if (counts.get("input") != null && counts.get("emit") != null && counts.get("output") != null) {
|
||||
mapReduceCounts = new MapReduceCounts( (Integer)counts.get("input"), (Integer)counts.get("emit"), (Integer)counts.get("output"));
|
||||
mapReduceCounts = new MapReduceCounts((Integer) counts.get("input"), (Integer) counts.get("emit"),
|
||||
(Integer) counts.get("output"));
|
||||
}
|
||||
} else {
|
||||
mapReduceCounts = new MapReduceCounts(-1,-1,-1);
|
||||
mapReduceCounts = new MapReduceCounts(-1, -1, -1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -18,15 +18,15 @@ package org.springframework.data.mongodb.core.mapreduce;
|
||||
public class MapReduceTiming {
|
||||
|
||||
private long mapTime;
|
||||
|
||||
|
||||
private long emitLoopTime;
|
||||
|
||||
|
||||
private long totalTime;
|
||||
|
||||
|
||||
public MapReduceTiming(long mapTime, long emitLoopTime, long totalTime) {
|
||||
this.mapTime = mapTime;
|
||||
this.emitLoopTime = emitLoopTime;
|
||||
this.totalTime = totalTime;
|
||||
this.totalTime = totalTime;
|
||||
}
|
||||
|
||||
public long getMapTime() {
|
||||
@@ -73,8 +73,5 @@ public class MapReduceTiming {
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Static factory method to create a Criteria using the provided key
|
||||
*
|
||||
*
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
@@ -79,7 +79,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Static factory method to create a Criteria using the provided key
|
||||
*
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public Criteria and(String key) {
|
||||
@@ -88,7 +88,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using equality
|
||||
*
|
||||
*
|
||||
* @param o
|
||||
* @return
|
||||
*/
|
||||
@@ -106,7 +106,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $ne operator
|
||||
*
|
||||
*
|
||||
* @param o
|
||||
* @return
|
||||
*/
|
||||
@@ -117,7 +117,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $lt operator
|
||||
*
|
||||
*
|
||||
* @param o
|
||||
* @return
|
||||
*/
|
||||
@@ -128,7 +128,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $lte operator
|
||||
*
|
||||
*
|
||||
* @param o
|
||||
* @return
|
||||
*/
|
||||
@@ -139,7 +139,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $gt operator
|
||||
*
|
||||
*
|
||||
* @param o
|
||||
* @return
|
||||
*/
|
||||
@@ -150,7 +150,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $gte operator
|
||||
*
|
||||
*
|
||||
* @param o
|
||||
* @return
|
||||
*/
|
||||
@@ -161,7 +161,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $in operator
|
||||
*
|
||||
*
|
||||
* @param o the values to match against
|
||||
* @return
|
||||
*/
|
||||
@@ -176,7 +176,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $in operator
|
||||
*
|
||||
*
|
||||
* @param c the collection containing the values to match against
|
||||
* @return
|
||||
*/
|
||||
@@ -187,7 +187,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $nin operator
|
||||
*
|
||||
*
|
||||
* @param o
|
||||
* @return
|
||||
*/
|
||||
@@ -202,7 +202,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $mod operator
|
||||
*
|
||||
*
|
||||
* @param value
|
||||
* @param remainder
|
||||
* @return
|
||||
@@ -217,7 +217,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $all operator
|
||||
*
|
||||
*
|
||||
* @param o
|
||||
* @return
|
||||
*/
|
||||
@@ -232,7 +232,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $size operator
|
||||
*
|
||||
*
|
||||
* @param s
|
||||
* @return
|
||||
*/
|
||||
@@ -243,7 +243,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $exists operator
|
||||
*
|
||||
*
|
||||
* @param b
|
||||
* @return
|
||||
*/
|
||||
@@ -254,7 +254,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $type operator
|
||||
*
|
||||
*
|
||||
* @param t
|
||||
* @return
|
||||
*/
|
||||
@@ -265,7 +265,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $not meta operator which affects the clause directly following
|
||||
*
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public Criteria not() {
|
||||
@@ -275,7 +275,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using a $regex
|
||||
*
|
||||
*
|
||||
* @param re
|
||||
* @return
|
||||
*/
|
||||
@@ -286,7 +286,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using a $regex and $options
|
||||
*
|
||||
*
|
||||
* @param re
|
||||
* @param options
|
||||
* @return
|
||||
@@ -301,7 +301,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a geospatial criterion using a $within $center operation. This is only available for Mongo 1.7 and higher.
|
||||
*
|
||||
*
|
||||
* @param circle must not be {@literal null}
|
||||
* @return
|
||||
*/
|
||||
@@ -320,7 +320,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a geospatial criterion using a $near operation
|
||||
*
|
||||
*
|
||||
* @param point must not be {@literal null}
|
||||
* @return
|
||||
*/
|
||||
@@ -332,7 +332,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a geospatial criterion using a $nearSphere operation. This is only available for Mongo 1.7 and higher.
|
||||
*
|
||||
*
|
||||
* @param point must not be {@literal null}
|
||||
* @return
|
||||
*/
|
||||
@@ -344,7 +344,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a geospatical criterion using a $maxDistance operation, for use with $near
|
||||
*
|
||||
*
|
||||
* @param maxDistance
|
||||
* @return
|
||||
*/
|
||||
@@ -355,7 +355,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a criterion using the $elemMatch operator
|
||||
*
|
||||
*
|
||||
* @param c
|
||||
* @return
|
||||
*/
|
||||
@@ -366,7 +366,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates an 'or' criteria using the $or operator for all of the provided criteria
|
||||
*
|
||||
*
|
||||
* @param criteria
|
||||
*/
|
||||
public Criteria orOperator(Criteria... criteria) {
|
||||
@@ -377,7 +377,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates a 'nor' criteria using the $nor operator for all of the provided criteria
|
||||
*
|
||||
*
|
||||
* @param criteria
|
||||
*/
|
||||
public Criteria norOperator(Criteria... criteria) {
|
||||
@@ -388,7 +388,7 @@ public class Criteria implements CriteriaDefinition {
|
||||
|
||||
/**
|
||||
* Creates an 'and' criteria using the $and operator for all of the provided criteria
|
||||
*
|
||||
*
|
||||
* @param criteria
|
||||
*/
|
||||
public Criteria andOperator(Criteria... criteria) {
|
||||
@@ -397,7 +397,6 @@ public class Criteria implements CriteriaDefinition {
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public String getKey() {
|
||||
return this.key;
|
||||
}
|
||||
@@ -462,11 +461,10 @@ public class Criteria implements CriteriaDefinition {
|
||||
Object existing = dbo.get(key);
|
||||
if (existing == null) {
|
||||
dbo.put(key, value);
|
||||
}
|
||||
else {
|
||||
throw new InvalidMongoDbApiUsageException("Due to limitations of the com.mongodb.BasicDBObject, " +
|
||||
"you can't add a second '" + key + "' expression specified as '" + key + " : " + value + "'. " +
|
||||
"Criteria already contains '" + key + " : " + existing + "'.");
|
||||
} else {
|
||||
throw new InvalidMongoDbApiUsageException("Due to limitations of the com.mongodb.BasicDBObject, "
|
||||
+ "you can't add a second '" + key + "' expression specified as '" + key + " : " + value + "'. "
|
||||
+ "Criteria already contains '" + key + " : " + existing + "'.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ public class Query {
|
||||
|
||||
/**
|
||||
* Static factory method to create a Query using the provided criteria
|
||||
*
|
||||
*
|
||||
* @param critera
|
||||
* @return
|
||||
*/
|
||||
@@ -56,11 +56,10 @@ public class Query {
|
||||
String key = criteria.getKey();
|
||||
if (existing == null) {
|
||||
this.criteria.put(key, criteria);
|
||||
}
|
||||
else {
|
||||
throw new InvalidMongoDbApiUsageException("Due to limitations of the com.mongodb.BasicDBObject, " +
|
||||
"you can't add a second '" + key + "' criteria. " +
|
||||
"Query already contains '" + existing.getCriteriaObject() + "'.");
|
||||
} else {
|
||||
throw new InvalidMongoDbApiUsageException("Due to limitations of the com.mongodb.BasicDBObject, "
|
||||
+ "you can't add a second '" + key + "' criteria. " + "Query already contains '"
|
||||
+ existing.getCriteriaObject() + "'.");
|
||||
}
|
||||
return this;
|
||||
}
|
||||
@@ -93,12 +92,12 @@ public class Query {
|
||||
this.hint = name;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public Sort sort() {
|
||||
if (this.sort == null) {
|
||||
this.sort = new Sort();
|
||||
}
|
||||
|
||||
|
||||
return this.sort;
|
||||
}
|
||||
|
||||
@@ -137,7 +136,7 @@ public class Query {
|
||||
public String getHint() {
|
||||
return hint;
|
||||
}
|
||||
|
||||
|
||||
protected List<Criteria> getCriteria() {
|
||||
return new ArrayList<Criteria>(this.criteria.values());
|
||||
}
|
||||
|
||||
@@ -203,13 +203,13 @@ public abstract class AbstractMongoQuery implements RepositoryQuery {
|
||||
|
||||
/**
|
||||
* {@link Execution} to execute geo-near queries.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
class GeoNearExecution extends Execution {
|
||||
|
||||
|
||||
private final MongoParameterAccessor accessor;
|
||||
|
||||
|
||||
public GeoNearExecution(MongoParameterAccessor accessor) {
|
||||
this.accessor = accessor;
|
||||
}
|
||||
@@ -220,27 +220,28 @@ public abstract class AbstractMongoQuery implements RepositoryQuery {
|
||||
*/
|
||||
@Override
|
||||
Object execute(Query query) {
|
||||
|
||||
|
||||
Point nearLocation = accessor.getGeoNearLocation();
|
||||
NearQuery nearQuery = NearQuery.near(nearLocation);
|
||||
|
||||
|
||||
if (query != null) {
|
||||
nearQuery.query(query);
|
||||
}
|
||||
|
||||
|
||||
Distance maxDistance = accessor.getMaxDistance();
|
||||
if (maxDistance != null) {
|
||||
nearQuery.maxDistance(maxDistance);
|
||||
}
|
||||
|
||||
MongoEntityInformation<?,?> entityInformation = method.getEntityInformation();
|
||||
GeoResults<?> results = mongoOperations.geoNear(nearQuery, entityInformation.getJavaType(), entityInformation.getCollectionName());
|
||||
|
||||
|
||||
MongoEntityInformation<?, ?> entityInformation = method.getEntityInformation();
|
||||
GeoResults<?> results = mongoOperations.geoNear(nearQuery, entityInformation.getJavaType(),
|
||||
entityInformation.getCollectionName());
|
||||
|
||||
return isListOfGeoResult() ? results.getContent() : results;
|
||||
}
|
||||
|
||||
|
||||
private boolean isListOfGeoResult() {
|
||||
|
||||
|
||||
TypeInformation<?> returnType = method.getReturnType();
|
||||
return returnType.getType().equals(List.class) && GeoResult.class.equals(returnType.getComponentType());
|
||||
}
|
||||
|
||||
@@ -42,10 +42,10 @@ public class ConvertingParameterAccessor implements MongoParameterAccessor {
|
||||
* @param delegate must not be {@literal null}.
|
||||
*/
|
||||
public ConvertingParameterAccessor(MongoWriter<?> writer, MongoParameterAccessor delegate) {
|
||||
|
||||
|
||||
Assert.notNull(writer);
|
||||
Assert.notNull(delegate);
|
||||
|
||||
|
||||
this.writer = writer;
|
||||
this.delegate = delegate;
|
||||
}
|
||||
@@ -92,7 +92,7 @@ public class ConvertingParameterAccessor implements MongoParameterAccessor {
|
||||
public Distance getMaxDistance() {
|
||||
return delegate.getMaxDistance();
|
||||
}
|
||||
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.springframework.data.mongodb.repository.MongoParameterAccessor#getGeoNearLocation()
|
||||
*/
|
||||
|
||||
@@ -17,10 +17,9 @@ package org.springframework.data.mongodb.repository.query;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
|
||||
/**
|
||||
* Interface for components being able to provide {@link EntityInformationCreator} for a given {@link Class}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public interface EntityInformationCreator {
|
||||
|
||||
@@ -33,7 +33,7 @@ public interface MongoParameterAccessor extends ParameterAccessor {
|
||||
* at all or the given value for it was {@literal null}.
|
||||
*/
|
||||
Distance getMaxDistance();
|
||||
|
||||
|
||||
/**
|
||||
* Returns the {@link Point} to use for a geo-near query.
|
||||
*
|
||||
|
||||
@@ -35,7 +35,7 @@ public class MongoParameters extends Parameters {
|
||||
|
||||
private final Integer distanceIndex;
|
||||
private Integer nearIndex;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link MongoParameters} instance from the given {@link Method} and {@link MongoQueryMethod}.
|
||||
*
|
||||
@@ -43,55 +43,56 @@ public class MongoParameters extends Parameters {
|
||||
* @param queryMethod must not be {@literal null}.
|
||||
*/
|
||||
public MongoParameters(Method method, boolean isGeoNearMethod) {
|
||||
|
||||
|
||||
super(method);
|
||||
List<Class<?>> parameterTypes = Arrays.asList(method.getParameterTypes());
|
||||
this.distanceIndex = parameterTypes.indexOf(Distance.class);
|
||||
|
||||
|
||||
if (this.nearIndex == null && isGeoNearMethod) {
|
||||
this.nearIndex = getNearIndex(parameterTypes);
|
||||
} else if (this.nearIndex == null) {
|
||||
this.nearIndex = -1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private final int getNearIndex(List<Class<?>> parameterTypes) {
|
||||
|
||||
|
||||
for (Class<?> reference : Arrays.asList(Point.class, double[].class)) {
|
||||
|
||||
|
||||
int nearIndex = parameterTypes.indexOf(reference);
|
||||
|
||||
|
||||
if (nearIndex == -1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
if (nearIndex == parameterTypes.lastIndexOf(reference)) {
|
||||
return nearIndex;
|
||||
} else {
|
||||
throw new IllegalStateException("Multiple Point parameters found but none annotated with @Near!");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.repository.query.Parameters#createParameter(org.springframework.core.MethodParameter)
|
||||
*/
|
||||
@Override
|
||||
protected Parameter createParameter(MethodParameter parameter) {
|
||||
|
||||
|
||||
MongoParameter mongoParameter = new MongoParameter(parameter);
|
||||
|
||||
|
||||
// Detect manually annotated @Near Point and reject multiple annotated ones
|
||||
if (this.nearIndex == null && mongoParameter.isManuallyAnnotatedNearParameter()) {
|
||||
this.nearIndex = mongoParameter.getIndex();
|
||||
} else if (mongoParameter.isManuallyAnnotatedNearParameter()) {
|
||||
throw new IllegalStateException(String.format("Found multiple @Near annotations ond method %s! Only one allowed!", parameter.getMethod().toString()));
|
||||
throw new IllegalStateException(String.format(
|
||||
"Found multiple @Near annotations ond method %s! Only one allowed!", parameter.getMethod().toString()));
|
||||
}
|
||||
|
||||
|
||||
return mongoParameter;
|
||||
}
|
||||
|
||||
@@ -103,7 +104,7 @@ public class MongoParameters extends Parameters {
|
||||
public int getDistanceIndex() {
|
||||
return distanceIndex;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the index of the parameter to be used to start a geo-near query from.
|
||||
*
|
||||
@@ -112,16 +113,16 @@ public class MongoParameters extends Parameters {
|
||||
public int getNearIndex() {
|
||||
return nearIndex;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Custom {@link Parameter} implementation adding parameters of type {@link Distance} to the special ones.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
class MongoParameter extends Parameter {
|
||||
|
||||
|
||||
private final MethodParameter parameter;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link MongoParameter}.
|
||||
*
|
||||
@@ -130,7 +131,7 @@ public class MongoParameters extends Parameters {
|
||||
MongoParameter(MethodParameter parameter) {
|
||||
super(parameter);
|
||||
this.parameter = parameter;
|
||||
|
||||
|
||||
if (!isPoint() && hasNearAnnotation()) {
|
||||
throw new IllegalArgumentException("Near annotation is only allowed at Point parameter!");
|
||||
}
|
||||
@@ -142,23 +143,22 @@ public class MongoParameters extends Parameters {
|
||||
*/
|
||||
@Override
|
||||
public boolean isSpecialParameter() {
|
||||
return super.isSpecialParameter() || getType().equals(Distance.class)
|
||||
|| isNearParameter();
|
||||
return super.isSpecialParameter() || getType().equals(Distance.class) || isNearParameter();
|
||||
}
|
||||
|
||||
|
||||
private boolean isNearParameter() {
|
||||
Integer nearIndex = MongoParameters.this.nearIndex;
|
||||
return nearIndex != null && nearIndex.equals(getIndex());
|
||||
}
|
||||
|
||||
|
||||
private boolean isManuallyAnnotatedNearParameter() {
|
||||
return isPoint() && hasNearAnnotation();
|
||||
}
|
||||
|
||||
|
||||
private boolean isPoint() {
|
||||
return getType().equals(Point.class) || getType().equals(double[].class);
|
||||
}
|
||||
|
||||
|
||||
private boolean hasNearAnnotation() {
|
||||
return parameter.getParameterAnnotation(Near.class) != null;
|
||||
}
|
||||
|
||||
@@ -21,13 +21,13 @@ import org.springframework.data.repository.query.ParametersParameterAccessor;
|
||||
|
||||
/**
|
||||
* Mongo-specific {@link ParametersParameterAccessor} to allow access to the {@link Distance} parameter.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class MongoParametersParameterAccessor extends ParametersParameterAccessor implements MongoParameterAccessor {
|
||||
|
||||
private final MongoQueryMethod method;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link MongoParametersParameterAccessor}.
|
||||
*
|
||||
@@ -47,25 +47,25 @@ public class MongoParametersParameterAccessor extends ParametersParameterAccesso
|
||||
int index = method.getParameters().getDistanceIndex();
|
||||
return index == -1 ? null : (Distance) getValue(index);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.mongodb.repository.MongoParameterAccessor#getGeoNearLocation()
|
||||
*/
|
||||
public Point getGeoNearLocation() {
|
||||
|
||||
|
||||
int nearIndex = method.getParameters().getNearIndex();
|
||||
|
||||
|
||||
if (nearIndex == -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
Object value = getValue(nearIndex);
|
||||
|
||||
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
if (value instanceof double[]) {
|
||||
double[] typedValue = (double[]) value;
|
||||
if (typedValue.length != 2) {
|
||||
@@ -74,7 +74,7 @@ public class MongoParametersParameterAccessor extends ParametersParameterAccesso
|
||||
return new Point(typedValue[0], typedValue[1]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return (Point) value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ public class StringBasedMongoQuery extends AbstractMongoQuery {
|
||||
} else {
|
||||
query = new BasicQuery(queryString);
|
||||
}
|
||||
|
||||
|
||||
QueryUtils.applySorting(query, accessor.getSort());
|
||||
|
||||
if (LOG.isDebugEnabled()) {
|
||||
|
||||
@@ -25,7 +25,8 @@ import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Simple {@link EntityInformationCreator} to to create {@link MongoEntityInformation} instances based on a {@link MappingContext}.
|
||||
* Simple {@link EntityInformationCreator} to to create {@link MongoEntityInformation} instances based on a
|
||||
* {@link MappingContext}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
|
||||
@@ -44,7 +44,7 @@ class IndexEnsuringQueryCreationListener implements QueryCreationListener<PartTr
|
||||
|
||||
private static final Set<Type> GEOSPATIAL_TYPES = new HashSet<Type>(Arrays.asList(Type.NEAR, Type.WITHIN));
|
||||
private static final Log LOG = LogFactory.getLog(IndexEnsuringQueryCreationListener.class);
|
||||
|
||||
|
||||
private final MongoOperations operations;
|
||||
|
||||
/**
|
||||
|
||||
@@ -61,12 +61,10 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements Paging
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.repository.Repository#save(java.lang.Object)
|
||||
* @see org.springframework.data.repository.CrudRepository#save(java.lang.Object)
|
||||
*/
|
||||
public T save(T entity) {
|
||||
|
||||
|
||||
Assert.notNull(entity, "Entity must not be null!");
|
||||
|
||||
mongoOperations.save(entity, entityInformation.getCollectionName());
|
||||
@@ -75,14 +73,12 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements Paging
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.repository.Repository#save(java.lang.Iterable)
|
||||
* @see org.springframework.data.repository.CrudRepository#save(java.lang.Iterable)
|
||||
*/
|
||||
public List<T> save(Iterable<? extends T> entities) {
|
||||
|
||||
Assert.notNull(entities, "The given Iterable of entities not be null!");
|
||||
|
||||
|
||||
List<T> result = new ArrayList<T>();
|
||||
|
||||
for (T entity : entities) {
|
||||
@@ -95,10 +91,7 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements Paging
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.repository.Repository#findById(java.io.Serializable
|
||||
* )
|
||||
* @see org.springframework.data.repository.CrudRepository#findOne(java.io.Serializable)
|
||||
*/
|
||||
public T findOne(ID id) {
|
||||
Assert.notNull(id, "The given id must not be null!");
|
||||
@@ -115,10 +108,7 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements Paging
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.repository.Repository#exists(java.io.Serializable
|
||||
* )
|
||||
* @see org.springframework.data.repository.CrudRepository#exists(java.io.Serializable)
|
||||
*/
|
||||
public boolean exists(ID id) {
|
||||
|
||||
@@ -129,8 +119,7 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements Paging
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.repository.Repository#count()
|
||||
* @see org.springframework.data.repository.CrudRepository#count()
|
||||
*/
|
||||
public long count() {
|
||||
|
||||
@@ -139,7 +128,7 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements Paging
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.repository.Repository#delete(java.io.Serializable)
|
||||
* @see org.springframework.data.repository.CrudRepository#delete(java.io.Serializable)
|
||||
*/
|
||||
public void delete(ID id) {
|
||||
Assert.notNull(id, "The given id must not be null!");
|
||||
@@ -148,9 +137,7 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements Paging
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.repository.Repository#delete(java.lang.Object)
|
||||
* @see org.springframework.data.repository.CrudRepository#delete(java.lang.Object)
|
||||
*/
|
||||
public void delete(T entity) {
|
||||
Assert.notNull(entity, "The given entity must not be null!");
|
||||
@@ -159,14 +146,12 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements Paging
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.repository.Repository#delete(java.lang.Iterable)
|
||||
* @see org.springframework.data.repository.CrudRepository#delete(java.lang.Iterable)
|
||||
*/
|
||||
public void delete(Iterable<? extends T> entities) {
|
||||
|
||||
Assert.notNull(entities, "The given Iterable of entities not be null!");
|
||||
|
||||
|
||||
for (T entity : entities) {
|
||||
delete(entity);
|
||||
}
|
||||
@@ -174,8 +159,7 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements Paging
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.repository.Repository#deleteAll()
|
||||
* @see org.springframework.data.repository.CrudRepository#deleteAll()
|
||||
*/
|
||||
public void deleteAll() {
|
||||
|
||||
@@ -184,8 +168,7 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements Paging
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.repository.Repository#findAll()
|
||||
* @see org.springframework.data.repository.CrudRepository#findAll()
|
||||
*/
|
||||
public List<T> findAll() {
|
||||
|
||||
@@ -194,10 +177,7 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements Paging
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.repository.PagingAndSortingRepository#findAll
|
||||
* (org.springframework.data.domain.Pageable)
|
||||
* @see org.springframework.data.repository.PagingAndSortingRepository#findAll(org.springframework.data.domain.Pageable)
|
||||
*/
|
||||
public Page<T> findAll(final Pageable pageable) {
|
||||
|
||||
@@ -209,43 +189,13 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements Paging
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.repository.PagingAndSortingRepository#findAll
|
||||
* (org.springframework.data.domain.Sort)
|
||||
* @see org.springframework.data.repository.PagingAndSortingRepository#findAll(org.springframework.data.domain.Sort)
|
||||
*/
|
||||
public List<T> findAll(final Sort sort) {
|
||||
|
||||
return findAll(QueryUtils.applySorting(new Query(), sort));
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.springframework.data.repository.Repository#findAll(java.lang.Iterable
|
||||
* )
|
||||
*/
|
||||
public List<T> findAll(Iterable<ID> ids) {
|
||||
|
||||
Query query = null;
|
||||
|
||||
//TODO: verify intent
|
||||
// for (ID id : ids) {
|
||||
// if (query == null) {
|
||||
// query = getIdQuery(id);
|
||||
// } else {
|
||||
// query = new Query().or(getIdQuery(id));
|
||||
// }
|
||||
// }
|
||||
List<ID> idList = new ArrayList<ID>();
|
||||
for (ID id : ids) {
|
||||
idList.add(id);
|
||||
}
|
||||
query = new Query(Criteria.where(entityInformation.getIdAttribute()).in(idList));
|
||||
return findAll(query);
|
||||
}
|
||||
|
||||
private List<T> findAll(Query query) {
|
||||
|
||||
if (query == null) {
|
||||
|
||||
@@ -42,10 +42,9 @@ import com.mongodb.DBObject;
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class MappingMongoConverterParserIntegrationTests {
|
||||
|
||||
|
||||
DefaultListableBeanFactory factory;
|
||||
|
||||
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
factory = new DefaultListableBeanFactory();
|
||||
@@ -55,26 +54,26 @@ public class MappingMongoConverterParserIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void allowsDbFactoryRefAttribute() {
|
||||
|
||||
|
||||
factory.getBeanDefinition("converter");
|
||||
factory.getBean("converter");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void scansForConverterAndSetsUpCustomConversionsAccordingly() {
|
||||
|
||||
|
||||
CustomConversions conversions = factory.getBean(CustomConversions.class);
|
||||
assertThat(conversions.hasCustomWriteTarget(Person.class), is(true));
|
||||
assertThat(conversions.hasCustomWriteTarget(Account.class), is(true));
|
||||
}
|
||||
|
||||
|
||||
@Component
|
||||
public static class SampleConverter implements Converter<Person, DBObject> {
|
||||
public DBObject convert(Person source) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Component
|
||||
public static class SampleConverterFactory implements GenericConverter {
|
||||
|
||||
|
||||
@@ -29,17 +29,17 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
/**
|
||||
* Integration tests for {@link MongoDbFactory}.
|
||||
*
|
||||
*
|
||||
* @author Thomas Risbergf
|
||||
*/
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration
|
||||
public class MongoDbFactoryNoDatabaseRunningTests {
|
||||
|
||||
|
||||
@Autowired
|
||||
MongoTemplate mongoTemplate;
|
||||
|
||||
|
||||
/**
|
||||
* @see DATADOC-139
|
||||
*/
|
||||
@@ -47,7 +47,7 @@ public class MongoDbFactoryNoDatabaseRunningTests {
|
||||
public void startsUpWithoutADatabaseRunning() {
|
||||
assertThat(mongoTemplate.getClass().getName(), is("org.springframework.data.mongodb.core.MongoTemplate"));
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = DataAccessResourceFailureException.class)
|
||||
public void failsDataAccessWithoutADatabaseRunning() {
|
||||
mongoTemplate.getCollectionNames();
|
||||
|
||||
@@ -40,14 +40,14 @@ import com.mongodb.WriteConcern;
|
||||
|
||||
/**
|
||||
* Integration tests for {@link MongoDbFactoryParser}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class MongoDbFactoryParserIntegrationTests {
|
||||
|
||||
|
||||
DefaultListableBeanFactory factory;
|
||||
BeanDefinitionReader reader;
|
||||
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
factory = new DefaultListableBeanFactory();
|
||||
@@ -61,29 +61,30 @@ public class MongoDbFactoryParserIntegrationTests {
|
||||
dbFactory.getDb();
|
||||
assertThat(WriteConcern.SAFE, is(dbFactory.getWriteConcern()));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void parsesWriteConcern() {
|
||||
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("namespace/db-factory-bean.xml");
|
||||
assertWriteConcern(ctx, WriteConcern.SAFE);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void parsesCustomWriteConcern() {
|
||||
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("namespace/db-factory-bean-custom-write-concern.xml");
|
||||
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
|
||||
"namespace/db-factory-bean-custom-write-concern.xml");
|
||||
assertWriteConcern(ctx, new WriteConcern("rack1"));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-331
|
||||
*/
|
||||
@Test
|
||||
public void readsReplicasWriteConcernCorrectly() {
|
||||
|
||||
|
||||
ApplicationContext ctx = new ClassPathXmlApplicationContext("namespace/db-factory-bean-custom-write-concern.xml");
|
||||
MongoDbFactory factory = ctx.getBean("second", MongoDbFactory.class);
|
||||
DB db = factory.getDb();
|
||||
|
||||
|
||||
assertThat(db.getWriteConcern(), is(WriteConcern.REPLICAS_SAFE));
|
||||
}
|
||||
|
||||
@@ -96,75 +97,72 @@ public class MongoDbFactoryParserIntegrationTests {
|
||||
MyWriteConcern myDbWriteConcern = new MyWriteConcern(db.getWriteConcern());
|
||||
MyWriteConcern myExpectedWriteConcern = new MyWriteConcern(expectedWriteConcern);
|
||||
|
||||
|
||||
assertThat(myDbFactoryWriteConcern, equalTo(myExpectedWriteConcern));
|
||||
assertThat(myDbWriteConcern, equalTo(myExpectedWriteConcern));
|
||||
assertThat(myDbWriteConcern, equalTo(myDbFactoryWriteConcern));
|
||||
}
|
||||
|
||||
//This test will fail since equals in WriteConcern uses == for _w and not .equals
|
||||
|
||||
// This test will fail since equals in WriteConcern uses == for _w and not .equals
|
||||
public void testWriteConcernEquality() {
|
||||
String s1 = new String("rack1");
|
||||
String s2 = new String("rack1");
|
||||
String s1 = new String("rack1");
|
||||
String s2 = new String("rack1");
|
||||
WriteConcern wc1 = new WriteConcern(s1);
|
||||
WriteConcern wc2 = new WriteConcern(s2);
|
||||
assertThat(wc1, equalTo(wc2));
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void createsDbFactoryBean() {
|
||||
|
||||
|
||||
reader.loadBeanDefinitions(new ClassPathResource("namespace/db-factory-bean.xml"));
|
||||
factory.getBean("first");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATADOC-280
|
||||
*/
|
||||
@Test
|
||||
public void parsesMaxAutoConnectRetryTimeCorrectly() {
|
||||
|
||||
|
||||
reader.loadBeanDefinitions(new ClassPathResource("namespace/db-factory-bean.xml"));
|
||||
Mongo mongo = factory.getBean(Mongo.class);
|
||||
assertThat(mongo.getMongoOptions().maxAutoConnectRetryTime, is(27L));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATADOC-295
|
||||
*/
|
||||
@Test
|
||||
public void setsUpMongoDbFactoryUsingAMongoUri() {
|
||||
|
||||
|
||||
reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-uri.xml"));
|
||||
BeanDefinition definition = factory.getBeanDefinition("mongoDbFactory");
|
||||
ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
|
||||
|
||||
|
||||
assertThat(constructorArguments.getArgumentCount(), is(1));
|
||||
ValueHolder argument = constructorArguments.getArgumentValue(0, MongoURI.class);
|
||||
assertThat(argument, is(notNullValue()));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATADOC-306
|
||||
*/
|
||||
@Test
|
||||
public void setsUpMongoDbFactoryUsingAMongoUriWithoutCredentials() {
|
||||
|
||||
|
||||
reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-uri-no-credentials.xml"));
|
||||
BeanDefinition definition = factory.getBeanDefinition("mongoDbFactory");
|
||||
ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
|
||||
|
||||
|
||||
assertThat(constructorArguments.getArgumentCount(), is(1));
|
||||
ValueHolder argument = constructorArguments.getArgumentValue(0, MongoURI.class);
|
||||
assertThat(argument, is(notNullValue()));
|
||||
|
||||
|
||||
MongoDbFactory dbFactory = factory.getBean("mongoDbFactory", MongoDbFactory.class);
|
||||
DB db = dbFactory.getDb();
|
||||
assertThat(db.getName(), is("database"));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATADOC-295
|
||||
*/
|
||||
|
||||
@@ -3,7 +3,7 @@ package org.springframework.data.mongodb.config;
|
||||
import com.mongodb.WriteConcern;
|
||||
|
||||
public class MyWriteConcern {
|
||||
|
||||
|
||||
public MyWriteConcern(WriteConcern wc) {
|
||||
this._w = wc.getWObject();
|
||||
this._continueOnErrorForInsert = wc.getContinueOnErrorForInsert();
|
||||
@@ -12,11 +12,12 @@ public class MyWriteConcern {
|
||||
this._wtimeout = wc.getWtimeout();
|
||||
}
|
||||
|
||||
Object _w = 0;
|
||||
int _wtimeout = 0;
|
||||
boolean _fsync = false;
|
||||
boolean _j = false;
|
||||
boolean _continueOnErrorForInsert = false;
|
||||
Object _w = 0;
|
||||
int _wtimeout = 0;
|
||||
boolean _fsync = false;
|
||||
boolean _j = false;
|
||||
boolean _continueOnErrorForInsert = false;
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
@@ -28,6 +29,7 @@ public class MyWriteConcern {
|
||||
result = prime * result + _wtimeout;
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
@@ -52,5 +54,5 @@ public class MyWriteConcern {
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -20,24 +20,23 @@ import java.lang.reflect.Field;
|
||||
|
||||
public class NamespaceTestSupport {
|
||||
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public static <T> T readField(String name, Object target) throws Exception {
|
||||
Field field = null;
|
||||
Class<?> clazz = target.getClass();
|
||||
do {
|
||||
try {
|
||||
field = clazz.getDeclaredField(name);
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public static <T> T readField(String name, Object target) throws Exception {
|
||||
Field field = null;
|
||||
Class<?> clazz = target.getClass();
|
||||
do {
|
||||
try {
|
||||
field = clazz.getDeclaredField(name);
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
clazz = clazz.getSuperclass();
|
||||
} while (field == null && !clazz.equals(Object.class));
|
||||
|
||||
clazz = clazz.getSuperclass();
|
||||
} while (field == null && !clazz.equals(Object.class));
|
||||
|
||||
if (field == null)
|
||||
throw new IllegalArgumentException("Cannot find field '" + name + "' in the class hierarchy of "
|
||||
+ target.getClass());
|
||||
field.setAccessible(true);
|
||||
return (T) field.get(target);
|
||||
}
|
||||
if (field == null)
|
||||
throw new IllegalArgumentException("Cannot find field '" + name + "' in the class hierarchy of "
|
||||
+ target.getClass());
|
||||
field.setAccessible(true);
|
||||
return (T) field.get(target);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
*/
|
||||
package org.springframework.data.mongodb.core;
|
||||
|
||||
|
||||
public class Friend {
|
||||
|
||||
private String id;
|
||||
|
||||
@@ -23,7 +23,7 @@ import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link MongoOptionsFactoryBean}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class MongoOptionsFactoryBeanUnitTests {
|
||||
@@ -33,11 +33,11 @@ public class MongoOptionsFactoryBeanUnitTests {
|
||||
*/
|
||||
@Test
|
||||
public void setsMaxConnectRetryTime() {
|
||||
|
||||
|
||||
MongoOptionsFactoryBean bean = new MongoOptionsFactoryBean();
|
||||
bean.setMaxAutoConnectRetryTime(27);
|
||||
bean.afterPropertiesSet();
|
||||
|
||||
|
||||
MongoOptions options = bean.getObject();
|
||||
assertThat(options.maxAutoConnectRetryTime, is(27L));
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ import com.mongodb.DBCursor;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link QueryCursorPreparer}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
@@ -41,18 +41,18 @@ public class QueryCursorPreparerUnitTests {
|
||||
MongoDbFactory factory;
|
||||
@Mock
|
||||
DBCursor cursor;
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-185
|
||||
*/
|
||||
@Test
|
||||
public void appliesHintsCorrectly() {
|
||||
|
||||
|
||||
Query query = query(where("foo").is("bar")).withHint("hint");
|
||||
|
||||
|
||||
CursorPreparer preparer = new MongoTemplate(factory).new QueryCursorPreparer(query);
|
||||
preparer.prepare(cursor);
|
||||
|
||||
|
||||
verify(cursor).hint("hint");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ public class SimpleMongoDbFactoryUnitTests {
|
||||
rejectsDatabaseName("foo.bar");
|
||||
rejectsDatabaseName("foo!bar");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATADOC-254
|
||||
*/
|
||||
@@ -66,16 +66,16 @@ public class SimpleMongoDbFactoryUnitTests {
|
||||
*/
|
||||
@Test
|
||||
public void mongoUriConstructor() throws UnknownHostException {
|
||||
|
||||
|
||||
MongoURI mongoURI = new MongoURI("mongodb://myUsername:myPassword@localhost/myDatabase.myCollection");
|
||||
MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoURI);
|
||||
|
||||
|
||||
assertThat(ReflectionTestUtils.getField(mongoDbFactory, "username").toString(), is("myUsername"));
|
||||
assertThat(ReflectionTestUtils.getField(mongoDbFactory, "password").toString(), is("myPassword"));
|
||||
assertThat(ReflectionTestUtils.getField(mongoDbFactory, "databaseName").toString(), is("myDatabase"));
|
||||
assertThat(ReflectionTestUtils.getField(mongoDbFactory, "databaseName").toString(), is("myDatabase"));
|
||||
}
|
||||
|
||||
|
||||
private void rejectsDatabaseName(String databaseName) {
|
||||
|
||||
try {
|
||||
|
||||
@@ -35,5 +35,4 @@ public class TestMongoConfiguration extends AbstractMongoConfiguration {
|
||||
converter.setCustomConversions(new CustomConversions(converters));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
|
||||
|
||||
/**
|
||||
* Test case to verify correct usage of custom {@link Converter} implementations to be used.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
* @see DATADOC-101
|
||||
*/
|
||||
@@ -65,9 +65,9 @@ public class CustomConvertersUnitTests {
|
||||
|
||||
when(barToDBObjectConverter.convert(any(Bar.class))).thenReturn(new BasicDBObject());
|
||||
when(dbObjectToBarConverter.convert(any(DBObject.class))).thenReturn(new Bar());
|
||||
|
||||
|
||||
CustomConversions conversions = new CustomConversions(Arrays.asList(barToDBObjectConverter, dbObjectToBarConverter));
|
||||
|
||||
|
||||
context = new MongoMappingContext();
|
||||
context.setInitialEntitySet(new HashSet<Class<?>>(Arrays.asList(Foo.class, Bar.class)));
|
||||
context.setSimpleTypeHolder(conversions.getSimpleTypeHolder());
|
||||
|
||||
@@ -175,7 +175,7 @@ public class DataDoc273Test {
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public class Shipment {
|
||||
|
||||
|
||||
Map boxes = new HashMap();
|
||||
|
||||
public Shipment(Map boxes) {
|
||||
|
||||
@@ -38,27 +38,27 @@ public class DefaultMongoTypeMapperUnitTests {
|
||||
|
||||
ConfigurableTypeInformationMapper configurableTypeInformationMapper;
|
||||
SimpleTypeInformationMapper simpleTypeInformationMapper;
|
||||
|
||||
|
||||
|
||||
DefaultMongoTypeMapper typeMapper;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
configurableTypeInformationMapper = new ConfigurableTypeInformationMapper(Collections.singletonMap(String.class, "1"));
|
||||
|
||||
configurableTypeInformationMapper = new ConfigurableTypeInformationMapper(Collections.singletonMap(String.class,
|
||||
"1"));
|
||||
simpleTypeInformationMapper = SimpleTypeInformationMapper.INSTANCE;
|
||||
|
||||
typeMapper = new DefaultMongoTypeMapper(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, Arrays.asList(
|
||||
configurableTypeInformationMapper));
|
||||
typeMapper = new DefaultMongoTypeMapper(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY,
|
||||
Arrays.asList(configurableTypeInformationMapper));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void defaultInstanceWritesClasses() {
|
||||
|
||||
|
||||
typeMapper = new DefaultMongoTypeMapper();
|
||||
writesTypeToField(new BasicDBObject(), String.class, String.class.getName());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void defaultInstanceReadsClasses() {
|
||||
typeMapper = new DefaultMongoTypeMapper();
|
||||
@@ -74,10 +74,10 @@ public class DefaultMongoTypeMapperUnitTests {
|
||||
|
||||
@Test
|
||||
public void writesClassNamesForUnmappedValuesIfConfigured() {
|
||||
|
||||
|
||||
typeMapper = new DefaultMongoTypeMapper(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, Arrays.asList(
|
||||
configurableTypeInformationMapper, simpleTypeInformationMapper));
|
||||
|
||||
|
||||
writesTypeToField(new BasicDBObject(), String.class, "1");
|
||||
writesTypeToField(new BasicDBObject(), Object.class, Object.class.getName());
|
||||
}
|
||||
@@ -90,10 +90,10 @@ public class DefaultMongoTypeMapperUnitTests {
|
||||
|
||||
@Test
|
||||
public void readsTypeLoadingClassesForUnmappedTypesIfConfigured() {
|
||||
|
||||
|
||||
typeMapper = new DefaultMongoTypeMapper(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, Arrays.asList(
|
||||
configurableTypeInformationMapper, simpleTypeInformationMapper));
|
||||
|
||||
|
||||
readsTypeFromField(new BasicDBObject(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, "1"), String.class);
|
||||
readsTypeFromField(new BasicDBObject(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, Object.class.getName()), Object.class);
|
||||
}
|
||||
|
||||
@@ -69,10 +69,10 @@ public class MappingMongoConverterUnitTests {
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
|
||||
mappingContext = new MongoMappingContext();
|
||||
mappingContext.afterPropertiesSet();
|
||||
|
||||
|
||||
converter = new MappingMongoConverter(factory, mappingContext);
|
||||
converter.afterPropertiesSet();
|
||||
}
|
||||
@@ -98,7 +98,7 @@ public class MappingMongoConverterUnitTests {
|
||||
List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
|
||||
converters.add(new LocalDateToDateConverter());
|
||||
converters.add(new DateToLocalDateConverter());
|
||||
|
||||
|
||||
CustomConversions conversions = new CustomConversions(converters);
|
||||
mappingContext.setSimpleTypeHolder(conversions.getSimpleTypeHolder());
|
||||
|
||||
@@ -189,36 +189,36 @@ public class MappingMongoConverterUnitTests {
|
||||
*/
|
||||
@Test
|
||||
public void writesEnumsCorrectly() {
|
||||
|
||||
|
||||
ClassWithEnumProperty value = new ClassWithEnumProperty();
|
||||
value.sampleEnum = SampleEnum.FIRST;
|
||||
|
||||
|
||||
DBObject result = new BasicDBObject();
|
||||
converter.write(value, result);
|
||||
|
||||
|
||||
assertThat(result.get("sampleEnum"), is(String.class));
|
||||
assertThat(result.get("sampleEnum").toString(), is("FIRST"));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-209
|
||||
*/
|
||||
@Test
|
||||
public void writesEnumCollectionCorrectly() {
|
||||
|
||||
|
||||
ClassWithEnumProperty value = new ClassWithEnumProperty();
|
||||
value.enums = Arrays.asList(SampleEnum.FIRST);
|
||||
|
||||
|
||||
DBObject result = new BasicDBObject();
|
||||
converter.write(value, result);
|
||||
|
||||
|
||||
assertThat(result.get("enums"), is(BasicDBList.class));
|
||||
|
||||
|
||||
BasicDBList enums = (BasicDBList) result.get("enums");
|
||||
assertThat(enums.size(), is(1));
|
||||
assertThat((String) enums.get(0), is("FIRST"));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-136
|
||||
*/
|
||||
@@ -226,55 +226,55 @@ public class MappingMongoConverterUnitTests {
|
||||
public void readsEnumsCorrectly() {
|
||||
DBObject dbObject = new BasicDBObject("sampleEnum", "FIRST");
|
||||
ClassWithEnumProperty result = converter.read(ClassWithEnumProperty.class, dbObject);
|
||||
|
||||
|
||||
assertThat(result.sampleEnum, is(SampleEnum.FIRST));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-209
|
||||
*/
|
||||
@Test
|
||||
public void readsEnumCollectionsCorrectly() {
|
||||
|
||||
|
||||
BasicDBList enums = new BasicDBList();
|
||||
enums.add("FIRST");
|
||||
DBObject dbObject = new BasicDBObject("enums", enums);
|
||||
|
||||
|
||||
ClassWithEnumProperty result = converter.read(ClassWithEnumProperty.class, dbObject);
|
||||
|
||||
|
||||
assertThat(result.enums, is(List.class));
|
||||
assertThat(result.enums.size(), is(1));
|
||||
assertThat(result.enums, hasItem(SampleEnum.FIRST));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-144
|
||||
*/
|
||||
@Test
|
||||
public void considersFieldNameWhenWriting() {
|
||||
|
||||
|
||||
Person person = new Person();
|
||||
person.firstname = "Oliver";
|
||||
|
||||
DBObject result = new BasicDBObject();
|
||||
converter.write(person, result);
|
||||
|
||||
|
||||
assertThat(result.containsField("foo"), is(true));
|
||||
assertThat(result.containsField("firstname"), is(false));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-144
|
||||
*/
|
||||
@Test
|
||||
public void considersFieldNameWhenReading() {
|
||||
|
||||
|
||||
DBObject dbObject = new BasicDBObject("foo", "Oliver");
|
||||
Person result = converter.read(Person.class, dbObject);
|
||||
|
||||
|
||||
assertThat(result.firstname, is("Oliver"));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-145
|
||||
*/
|
||||
@@ -283,13 +283,13 @@ public class MappingMongoConverterUnitTests {
|
||||
Person person = new Person();
|
||||
person.birthDate = new LocalDate();
|
||||
person.firstname = "Oliver";
|
||||
|
||||
|
||||
CollectionWrapper wrapper = new CollectionWrapper();
|
||||
wrapper.contacts = Arrays.asList((Contact) person);
|
||||
|
||||
|
||||
BasicDBObject dbObject = new BasicDBObject();
|
||||
converter.write(wrapper, dbObject);
|
||||
|
||||
|
||||
Object result = dbObject.get("contacts");
|
||||
assertThat(result, is(BasicDBList.class));
|
||||
BasicDBList contacts = (BasicDBList) result;
|
||||
@@ -297,165 +297,165 @@ public class MappingMongoConverterUnitTests {
|
||||
assertThat(personDbObject.get("foo").toString(), is("Oliver"));
|
||||
assertThat((String) personDbObject.get(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY), is(Person.class.getName()));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-145
|
||||
*/
|
||||
@Test
|
||||
public void readsCollectionWithInterfaceCorrectly() {
|
||||
|
||||
|
||||
BasicDBObject person = new BasicDBObject(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, Person.class.getName());
|
||||
person.put("foo", "Oliver");
|
||||
|
||||
|
||||
BasicDBList contacts = new BasicDBList();
|
||||
contacts.add(person);
|
||||
|
||||
|
||||
CollectionWrapper result = converter.read(CollectionWrapper.class, new BasicDBObject("contacts", contacts));
|
||||
assertThat(result.contacts, is(notNullValue()));
|
||||
assertThat(result.contacts.size(), is(1));
|
||||
Contact contact = result.contacts.get(0);
|
||||
assertThat(contact, is(Person.class));
|
||||
assertThat(((Person) contact).firstname, is("Oliver"));
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void convertsLocalesOutOfTheBox() {
|
||||
LocaleWrapper wrapper = new LocaleWrapper();
|
||||
wrapper.locale = Locale.US;
|
||||
|
||||
|
||||
DBObject dbObject = new BasicDBObject();
|
||||
converter.write(wrapper, dbObject);
|
||||
|
||||
|
||||
Object localeField = dbObject.get("locale");
|
||||
assertThat(localeField, is(String.class));
|
||||
assertThat((String) localeField, is("en_US"));
|
||||
|
||||
|
||||
LocaleWrapper read = converter.read(LocaleWrapper.class, dbObject);
|
||||
assertThat(read.locale, is(Locale.US));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-161
|
||||
*/
|
||||
@Test
|
||||
public void readsNestedMapsCorrectly() {
|
||||
|
||||
Map<String, String> secondLevel = new HashMap<String, String>();
|
||||
secondLevel.put("key1", "value1");
|
||||
secondLevel.put("key2", "value2");
|
||||
Map<String, String> secondLevel = new HashMap<String, String>();
|
||||
secondLevel.put("key1", "value1");
|
||||
secondLevel.put("key2", "value2");
|
||||
|
||||
Map<String, Map<String, String>> firstLevel = new HashMap<String, Map<String, String>>();
|
||||
firstLevel.put("level1", secondLevel);
|
||||
firstLevel.put("level2", secondLevel);
|
||||
|
||||
ClassWithNestedMaps maps = new ClassWithNestedMaps();
|
||||
maps.nestedMaps = new LinkedHashMap<String, Map<String, Map<String, String>>>();
|
||||
maps.nestedMaps.put("afield", firstLevel);
|
||||
|
||||
DBObject dbObject = new BasicDBObject();
|
||||
converter.write(maps, dbObject);
|
||||
|
||||
ClassWithNestedMaps result = converter.read(ClassWithNestedMaps.class, dbObject);
|
||||
Map<String, Map<String, Map<String, String>>> nestedMap = result.nestedMaps;
|
||||
assertThat(nestedMap, is(notNullValue()));
|
||||
assertThat(nestedMap.get("afield"), is(firstLevel));
|
||||
Map<String, Map<String, String>> firstLevel = new HashMap<String, Map<String, String>>();
|
||||
firstLevel.put("level1", secondLevel);
|
||||
firstLevel.put("level2", secondLevel);
|
||||
|
||||
ClassWithNestedMaps maps = new ClassWithNestedMaps();
|
||||
maps.nestedMaps = new LinkedHashMap<String, Map<String, Map<String, String>>>();
|
||||
maps.nestedMaps.put("afield", firstLevel);
|
||||
|
||||
DBObject dbObject = new BasicDBObject();
|
||||
converter.write(maps, dbObject);
|
||||
|
||||
ClassWithNestedMaps result = converter.read(ClassWithNestedMaps.class, dbObject);
|
||||
Map<String, Map<String, Map<String, String>>> nestedMap = result.nestedMaps;
|
||||
assertThat(nestedMap, is(notNullValue()));
|
||||
assertThat(nestedMap.get("afield"), is(firstLevel));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATACMNS-42, DATAMONGO-171
|
||||
*/
|
||||
@Test
|
||||
public void writesClassWithBigDecimal() {
|
||||
|
||||
|
||||
BigDecimalContainer container = new BigDecimalContainer();
|
||||
container.value = BigDecimal.valueOf(2.5d);
|
||||
container.map = Collections.singletonMap("foo", container.value);
|
||||
|
||||
|
||||
DBObject dbObject = new BasicDBObject();
|
||||
converter.write(container, dbObject);
|
||||
|
||||
|
||||
assertThat(dbObject.get("value"), is(instanceOf(String.class)));
|
||||
assertThat((String) dbObject.get("value"), is("2.5"));
|
||||
assertThat(((DBObject) dbObject.get("map")).get("foo"), is(instanceOf(String.class)));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATACMNS-42, DATAMONGO-171
|
||||
*/
|
||||
@Test
|
||||
public void readsClassWithBigDecimal() {
|
||||
|
||||
|
||||
DBObject dbObject = new BasicDBObject("value", "2.5");
|
||||
dbObject.put("map", new BasicDBObject("foo", "2.5"));
|
||||
|
||||
|
||||
BasicDBList list = new BasicDBList();
|
||||
list.add("2.5");
|
||||
dbObject.put("collection", list);
|
||||
BigDecimalContainer result = converter.read(BigDecimalContainer.class, dbObject);
|
||||
|
||||
|
||||
assertThat(result.value, is(BigDecimal.valueOf(2.5d)));
|
||||
assertThat(result.map.get("foo"), is(BigDecimal.valueOf(2.5d)));
|
||||
assertThat(result.collection.get(0), is(BigDecimal.valueOf(2.5d)));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void writesNestedCollectionsCorrectly() {
|
||||
|
||||
|
||||
CollectionWrapper wrapper = new CollectionWrapper();
|
||||
wrapper.strings = Arrays.asList(Arrays.asList("Foo"));
|
||||
|
||||
|
||||
DBObject dbObject = new BasicDBObject();
|
||||
converter.write(wrapper, dbObject);
|
||||
|
||||
|
||||
Object outerStrings = dbObject.get("strings");
|
||||
assertThat(outerStrings, is(instanceOf(BasicDBList.class)));
|
||||
|
||||
|
||||
BasicDBList typedOuterString = (BasicDBList) outerStrings;
|
||||
assertThat(typedOuterString.size(), is(1));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-192
|
||||
*/
|
||||
@Test
|
||||
public void readsEmptySetsCorrectly() {
|
||||
|
||||
|
||||
Person person = new Person();
|
||||
person.addresses = Collections.emptySet();
|
||||
|
||||
|
||||
DBObject dbObject = new BasicDBObject();
|
||||
converter.write(person, dbObject);
|
||||
converter.read(Person.class, dbObject);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void convertsObjectIdStringsToObjectIdCorrectly() {
|
||||
PersonPojoStringId p1 = new PersonPojoStringId("1234567890", "Text-1");
|
||||
DBObject dbo1 = new BasicDBObject();
|
||||
|
||||
|
||||
converter.write(p1, dbo1);
|
||||
assertThat(dbo1.get("_id"), is(String.class));
|
||||
|
||||
|
||||
PersonPojoStringId p2 = new PersonPojoStringId(new ObjectId().toString(), "Text-1");
|
||||
DBObject dbo2 = new BasicDBObject();
|
||||
|
||||
|
||||
converter.write(p2, dbo2);
|
||||
assertThat(dbo2.get("_id"), is(ObjectId.class));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-207
|
||||
*/
|
||||
@Test
|
||||
public void convertsCustomEmptyMapCorrectly() {
|
||||
|
||||
|
||||
DBObject map = new BasicDBObject();
|
||||
DBObject wrapper = new BasicDBObject("map", map);
|
||||
|
||||
|
||||
ClassWithSortedMap result = converter.read(ClassWithSortedMap.class, wrapper);
|
||||
|
||||
|
||||
assertThat(result, is(ClassWithSortedMap.class));
|
||||
assertThat(result.map, is(SortedMap.class));
|
||||
}
|
||||
@@ -467,145 +467,145 @@ public class MappingMongoConverterUnitTests {
|
||||
public void maybeConvertHandlesNullValuesCorrectly() {
|
||||
assertThat(converter.convertToMongoType(null), is(nullValue()));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void writesGenericTypeCorrectly() {
|
||||
|
||||
|
||||
GenericType<Address> type = new GenericType<Address>();
|
||||
type.content = new Address();
|
||||
type.content.city = "London";
|
||||
|
||||
|
||||
BasicDBObject result = new BasicDBObject();
|
||||
converter.write(type, result);
|
||||
|
||||
|
||||
DBObject content = (DBObject) result.get("content");
|
||||
assertThat(content.get("_class"), is(notNullValue()));
|
||||
assertThat(content.get("city"), is(notNullValue()));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void readsGenericTypeCorrectly() {
|
||||
|
||||
|
||||
DBObject address = new BasicDBObject("_class", Address.class.getName());
|
||||
address.put("city", "London");
|
||||
|
||||
|
||||
GenericType<?> result = converter.read(GenericType.class, new BasicDBObject("content", address));
|
||||
assertThat(result.content, is(instanceOf(Address.class)));
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-228
|
||||
*/
|
||||
@Test
|
||||
public void writesNullValuesForMaps() {
|
||||
|
||||
|
||||
ClassWithMapProperty foo = new ClassWithMapProperty();
|
||||
foo.map = Collections.singletonMap(Locale.US, null);
|
||||
|
||||
|
||||
DBObject result = new BasicDBObject();
|
||||
converter.write(foo, result);
|
||||
|
||||
|
||||
Object map = result.get("map");
|
||||
assertThat(map, is(instanceOf(DBObject.class)));
|
||||
assertThat(((DBObject) map).keySet(), hasItem("en_US"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void writesBigIntegerIdCorrectly() {
|
||||
|
||||
|
||||
ClassWithBigIntegerId foo = new ClassWithBigIntegerId();
|
||||
foo.id = BigInteger.valueOf(23L);
|
||||
|
||||
|
||||
DBObject result = new BasicDBObject();
|
||||
converter.write(foo, result);
|
||||
|
||||
|
||||
assertThat(result.get("_id"), is(instanceOf(String.class)));
|
||||
}
|
||||
|
||||
|
||||
public void convertsObjectsIfNecessary() {
|
||||
|
||||
|
||||
ObjectId id = new ObjectId();
|
||||
assertThat(converter.convertToMongoType(id), is((Object) id));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-235
|
||||
*/
|
||||
@Test
|
||||
public void writesMapOfListsCorrectly() {
|
||||
|
||||
|
||||
ClassWithMapProperty input = new ClassWithMapProperty();
|
||||
input.mapOfLists = Collections.singletonMap("Foo", Arrays.asList("Bar"));
|
||||
|
||||
|
||||
BasicDBObject result = new BasicDBObject();
|
||||
converter.write(input, result);
|
||||
|
||||
|
||||
Object field = result.get("mapOfLists");
|
||||
assertThat(field, is(instanceOf(DBObject.class)));
|
||||
|
||||
|
||||
DBObject map = (DBObject) field;
|
||||
Object foo = map.get("Foo");
|
||||
assertThat(foo, is(instanceOf(BasicDBList.class)));
|
||||
|
||||
|
||||
BasicDBList value = (BasicDBList) foo;
|
||||
assertThat(value.size(), is(1));
|
||||
assertThat((String) value.get(0), is("Bar"));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-235
|
||||
*/
|
||||
@Test
|
||||
public void readsMapListValuesCorrectly() {
|
||||
|
||||
|
||||
BasicDBList list = new BasicDBList();
|
||||
list.add("Bar");
|
||||
DBObject source = new BasicDBObject("mapOfLists", new BasicDBObject("Foo", list));
|
||||
|
||||
|
||||
ClassWithMapProperty result = converter.read(ClassWithMapProperty.class, source);
|
||||
assertThat(result.mapOfLists, is(not(nullValue())));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-235
|
||||
*/
|
||||
@Test
|
||||
public void writesMapsOfObjectsCorrectly() {
|
||||
|
||||
|
||||
ClassWithMapProperty input = new ClassWithMapProperty();
|
||||
input.mapOfObjects = new HashMap<String, Object>();
|
||||
input.mapOfObjects.put("Foo", Arrays.asList("Bar"));
|
||||
|
||||
|
||||
BasicDBObject result = new BasicDBObject();
|
||||
converter.write(input, result);
|
||||
|
||||
|
||||
Object field = result.get("mapOfObjects");
|
||||
assertThat(field, is(instanceOf(DBObject.class)));
|
||||
|
||||
|
||||
DBObject map = (DBObject) field;
|
||||
Object foo = map.get("Foo");
|
||||
assertThat(foo, is(instanceOf(BasicDBList.class)));
|
||||
|
||||
|
||||
BasicDBList value = (BasicDBList) foo;
|
||||
assertThat(value.size(), is(1));
|
||||
assertThat((String) value.get(0), is("Bar"));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-235
|
||||
*/
|
||||
@Test
|
||||
public void readsMapOfObjectsListValuesCorrectly() {
|
||||
|
||||
|
||||
BasicDBList list = new BasicDBList();
|
||||
list.add("Bar");
|
||||
DBObject source = new BasicDBObject("mapOfObjects", new BasicDBObject("Foo", list));
|
||||
|
||||
|
||||
ClassWithMapProperty result = converter.read(ClassWithMapProperty.class, source);
|
||||
assertThat(result.mapOfObjects, is(not(nullValue())));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-245
|
||||
*/
|
||||
@@ -623,7 +623,6 @@ public class MappingMongoConverterUnitTests {
|
||||
assertThat(firstObjectInFoo, is(instanceOf(Map.class)));
|
||||
assertThat((String) ((Map<?, ?>) firstObjectInFoo).get("Hello"), is(equalTo("World")));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-245
|
||||
@@ -666,46 +665,46 @@ public class MappingMongoConverterUnitTests {
|
||||
assertThat(doublyNestedObject, is(instanceOf(Map.class)));
|
||||
assertThat((String) ((Map<?, ?>) doublyNestedObject).get("Hello"), is(equalTo("World")));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-259
|
||||
*/
|
||||
@Test
|
||||
public void writesListOfMapsCorrectly() {
|
||||
|
||||
|
||||
Map<String, Locale> map = Collections.singletonMap("Foo", Locale.ENGLISH);
|
||||
|
||||
|
||||
CollectionWrapper wrapper = new CollectionWrapper();
|
||||
wrapper.listOfMaps = new ArrayList<Map<String, Locale>>();
|
||||
wrapper.listOfMaps.add(map);
|
||||
|
||||
|
||||
DBObject result = new BasicDBObject();
|
||||
converter.write(wrapper, result);
|
||||
|
||||
|
||||
BasicDBList list = (BasicDBList) result.get("listOfMaps");
|
||||
assertThat(list, is(notNullValue()));
|
||||
assertThat(list.size(), is(1));
|
||||
|
||||
|
||||
DBObject dbObject = (DBObject) list.get(0);
|
||||
assertThat(dbObject.containsField("Foo"), is(true));
|
||||
assertThat((String) dbObject.get("Foo"), is(Locale.ENGLISH.toString()));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-259
|
||||
*/
|
||||
@Test
|
||||
public void readsListOfMapsCorrectly() {
|
||||
|
||||
|
||||
DBObject map = new BasicDBObject("Foo", "en");
|
||||
|
||||
|
||||
BasicDBList list = new BasicDBList();
|
||||
list.add(map);
|
||||
|
||||
|
||||
DBObject wrapperSource = new BasicDBObject("listOfMaps", list);
|
||||
|
||||
|
||||
CollectionWrapper wrapper = converter.read(CollectionWrapper.class, wrapperSource);
|
||||
|
||||
|
||||
assertThat(wrapper.listOfMaps, is(notNullValue()));
|
||||
assertThat(wrapper.listOfMaps.size(), is(1));
|
||||
assertThat(wrapper.listOfMaps.get(0), is(notNullValue()));
|
||||
@@ -721,13 +720,13 @@ public class MappingMongoConverterUnitTests {
|
||||
Map<String, List<Locale>> map = Collections.singletonMap("Foo", Arrays.asList(Locale.US));
|
||||
DBObject result = new BasicDBObject();
|
||||
converter.write(map, result);
|
||||
|
||||
|
||||
assertThat(result.containsField("Foo"), is(true));
|
||||
assertThat(result.get("Foo"), is(notNullValue()));
|
||||
assertThat(result.get("Foo"), is(BasicDBList.class));
|
||||
|
||||
|
||||
BasicDBList list = (BasicDBList) result.get("Foo");
|
||||
|
||||
|
||||
assertThat(list.size(), is(1));
|
||||
assertThat(list.get(0), is((Object) Locale.US.toString()));
|
||||
}
|
||||
@@ -738,7 +737,7 @@ public class MappingMongoConverterUnitTests {
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void testSaveMapWithACollectionAsValue() {
|
||||
|
||||
|
||||
Map<String, Object> keyValues = new HashMap<String, Object>();
|
||||
keyValues.put("string", "hello");
|
||||
List<String> list = new ArrayList<String>();
|
||||
@@ -766,63 +765,63 @@ public class MappingMongoConverterUnitTests {
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public void writesArraysAsMapValuesCorrectly() {
|
||||
|
||||
|
||||
ClassWithMapProperty wrapper = new ClassWithMapProperty();
|
||||
wrapper.mapOfObjects = new HashMap<String, Object>();
|
||||
wrapper.mapOfObjects.put("foo", new String[] { "bar" });
|
||||
|
||||
|
||||
DBObject result = new BasicDBObject();
|
||||
converter.write(wrapper, result);
|
||||
|
||||
|
||||
Object mapObject = result.get("mapOfObjects");
|
||||
assertThat(mapObject, is(BasicDBObject.class));
|
||||
|
||||
|
||||
DBObject map = (DBObject) mapObject;
|
||||
Object valueObject = map.get("foo");
|
||||
assertThat(valueObject, is(BasicDBList.class));
|
||||
|
||||
|
||||
List<Object> list = (List<Object>) valueObject;
|
||||
assertThat(list.size(), is(1));
|
||||
assertThat(list, hasItem((Object) "bar"));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-324
|
||||
*/
|
||||
@Test
|
||||
public void writesDbObjectCorrectly() {
|
||||
|
||||
|
||||
DBObject dbObject = new BasicDBObject();
|
||||
dbObject.put("foo", "bar");
|
||||
|
||||
|
||||
DBObject result = new BasicDBObject();
|
||||
|
||||
|
||||
converter.write(dbObject, result);
|
||||
|
||||
|
||||
result.removeField(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY);
|
||||
assertThat(dbObject, is(result));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-324
|
||||
*/
|
||||
@Test
|
||||
public void readsDbObjectCorrectly() {
|
||||
|
||||
|
||||
DBObject dbObject = new BasicDBObject();
|
||||
dbObject.put("foo", "bar");
|
||||
|
||||
|
||||
DBObject result = converter.read(DBObject.class, dbObject);
|
||||
|
||||
|
||||
assertThat(result, is(dbObject));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-329
|
||||
*/
|
||||
@Test
|
||||
public void writesMapAsGenericFieldCorrectly() {
|
||||
|
||||
|
||||
Map<String, A<String>> objectToSave = new HashMap<String, A<String>>();
|
||||
objectToSave.put("test", new A<String>("testValue"));
|
||||
|
||||
@@ -830,78 +829,77 @@ public class MappingMongoConverterUnitTests {
|
||||
DBObject result = new BasicDBObject();
|
||||
|
||||
converter.write(a, result);
|
||||
|
||||
|
||||
assertThat((String) result.get(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY), is(A.class.getName()));
|
||||
assertThat((String) result.get("valueType"), is(HashMap.class.getName()));
|
||||
|
||||
|
||||
DBObject object = (DBObject) result.get("value");
|
||||
assertThat(object, is(notNullValue()));
|
||||
|
||||
|
||||
DBObject inner = (DBObject) object.get("test");
|
||||
assertThat(inner, is(notNullValue()));
|
||||
assertThat((String) inner.get(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY), is(A.class.getName()));
|
||||
assertThat((String) inner.get("valueType"), is(String.class.getName()));
|
||||
assertThat((String) inner.get("value"), is("testValue"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void writesIntIdCorrectly() {
|
||||
|
||||
|
||||
ClassWithIntId value = new ClassWithIntId();
|
||||
value.id = 5;
|
||||
|
||||
|
||||
DBObject result = new BasicDBObject();
|
||||
converter.write(value, result);
|
||||
|
||||
|
||||
assertThat(result.get("_id"), is((Object) 5));
|
||||
}
|
||||
|
||||
|
||||
class GenericType<T> {
|
||||
T content;
|
||||
}
|
||||
|
||||
|
||||
class ClassWithEnumProperty {
|
||||
|
||||
|
||||
SampleEnum sampleEnum;
|
||||
List<SampleEnum> enums;
|
||||
}
|
||||
|
||||
|
||||
enum SampleEnum {
|
||||
FIRST {
|
||||
@Override
|
||||
void method() {
|
||||
}
|
||||
}
|
||||
},
|
||||
SECOND {
|
||||
@Override
|
||||
void method() {
|
||||
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
abstract void method();
|
||||
}
|
||||
|
||||
|
||||
class Address {
|
||||
String street;
|
||||
String city;
|
||||
}
|
||||
|
||||
|
||||
interface Contact {
|
||||
|
||||
}
|
||||
|
||||
public static class Person implements Contact {
|
||||
LocalDate birthDate;
|
||||
|
||||
|
||||
@Field("foo")
|
||||
String firstname;
|
||||
|
||||
|
||||
Set<Address> addresses;
|
||||
|
||||
|
||||
public Person() {
|
||||
|
||||
|
||||
}
|
||||
|
||||
@PersistenceConstructor
|
||||
@@ -913,7 +911,7 @@ public class MappingMongoConverterUnitTests {
|
||||
class ClassWithSortedMap {
|
||||
SortedMap<String, String> map;
|
||||
}
|
||||
|
||||
|
||||
class ClassWithMapProperty {
|
||||
Map<Locale, String> map;
|
||||
Map<String, List<String>> mapOfLists;
|
||||
@@ -923,17 +921,17 @@ public class MappingMongoConverterUnitTests {
|
||||
class ClassWithNestedMaps {
|
||||
Map<String, Map<String, Map<String, String>>> nestedMaps;
|
||||
}
|
||||
|
||||
|
||||
class BirthDateContainer {
|
||||
LocalDate birthDate;
|
||||
}
|
||||
|
||||
|
||||
class BigDecimalContainer {
|
||||
BigDecimal value;
|
||||
Map<String, BigDecimal> map;
|
||||
List<BigDecimal> collection;
|
||||
}
|
||||
|
||||
|
||||
class CollectionWrapper {
|
||||
List<Contact> contacts;
|
||||
List<List<String>> strings;
|
||||
@@ -943,7 +941,7 @@ public class MappingMongoConverterUnitTests {
|
||||
class LocaleWrapper {
|
||||
Locale locale;
|
||||
}
|
||||
|
||||
|
||||
class ClassWithBigIntegerId {
|
||||
@Id
|
||||
BigInteger id;
|
||||
@@ -961,11 +959,11 @@ public class MappingMongoConverterUnitTests {
|
||||
}
|
||||
|
||||
class ClassWithIntId {
|
||||
|
||||
|
||||
@Id
|
||||
int id;
|
||||
}
|
||||
|
||||
|
||||
private class LocalDateToDateConverter implements Converter<LocalDate, Date> {
|
||||
|
||||
public Date convert(LocalDate source) {
|
||||
|
||||
@@ -27,18 +27,18 @@ import org.springframework.data.mongodb.core.convert.MongoConverters.StringToBig
|
||||
|
||||
/**
|
||||
* Unit tests for {@link MongoConverters}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class MongoConvertersUnitTests {
|
||||
|
||||
@Test
|
||||
public void convertsBigDecimalToStringAndBackCorrectly() {
|
||||
|
||||
|
||||
BigDecimal bigDecimal = BigDecimal.valueOf(254, 1);
|
||||
String value = BigDecimalToStringConverter.INSTANCE.convert(bigDecimal);
|
||||
assertThat(value, is("25.4"));
|
||||
|
||||
|
||||
BigDecimal reference = StringToBigDecimalConverter.INSTANCE.convert(value);
|
||||
assertThat(reference, is(bigDecimal));
|
||||
}
|
||||
|
||||
@@ -24,26 +24,26 @@ import org.springframework.data.mongodb.core.geo.Point;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link Box}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class BoxUnitTests {
|
||||
|
||||
|
||||
Box first = new Box(new Point(1d, 1d), new Point(2d, 2d));
|
||||
Box second = new Box(new Point(1d, 1d), new Point(2d, 2d));
|
||||
Box third = new Box(new Point(3d, 3d), new Point(1d, 1d));
|
||||
|
||||
@Test
|
||||
public void equalsWorksCorrectly() {
|
||||
|
||||
|
||||
assertThat(first.equals(second), is(true));
|
||||
assertThat(second.equals(first), is(true));
|
||||
assertThat(first.equals(third), is(false));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void hashCodeWorksCorrectly() {
|
||||
|
||||
|
||||
assertThat(first.hashCode(), is(second.hashCode()));
|
||||
assertThat(first.hashCode(), is(not(third.hashCode())));
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link Circle}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class CircleUnitTests {
|
||||
@@ -31,23 +31,23 @@ public class CircleUnitTests {
|
||||
public void rejectsNullOrigin() {
|
||||
new Circle(null, 0);
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNegativeRadius() {
|
||||
new Circle(1, 1, -1);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void considersTwoCirclesEqualCorrectly() {
|
||||
|
||||
|
||||
Circle left = new Circle(1, 1, 1);
|
||||
Circle right = new Circle(1, 1, 1);
|
||||
|
||||
|
||||
assertThat(left, is(right));
|
||||
assertThat(right, is(left));
|
||||
|
||||
right = new Circle(new Point(1,1), 1);
|
||||
|
||||
|
||||
right = new Circle(new Point(1, 1), 1);
|
||||
|
||||
assertThat(left, is(right));
|
||||
assertThat(right, is(left));
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ import org.junit.Test;
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class DistanceUnitTests {
|
||||
|
||||
|
||||
@Test
|
||||
public void defaultsMetricToNeutralOne() {
|
||||
assertThat(new Distance(2.5).getMetric(), is((Metric) Metrics.NEUTRAL));
|
||||
@@ -40,7 +40,7 @@ public class DistanceUnitTests {
|
||||
Distance right = new Distance(2.5, KILOMETERS);
|
||||
assertThat(left.add(right), is(new Distance(5.0, KILOMETERS)));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void addsDistancesWithExplicitMetric() {
|
||||
Distance left = new Distance(2.5, KILOMETERS);
|
||||
|
||||
@@ -21,11 +21,11 @@ import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link GeoResult}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class GeoResultUnitTests {
|
||||
|
||||
|
||||
GeoResult<String> first = new GeoResult<String>("Foo", new Distance(2.5));
|
||||
GeoResult<String> second = new GeoResult<String>("Foo", new Distance(2.5));
|
||||
GeoResult<String> third = new GeoResult<String>("Bar", new Distance(2.5));
|
||||
@@ -33,10 +33,10 @@ public class GeoResultUnitTests {
|
||||
|
||||
@Test
|
||||
public void considersSameInstanceEqual() {
|
||||
|
||||
|
||||
assertThat(first.equals(first), is(true));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void considersSameValuesAsEqual() {
|
||||
assertThat(first.equals(second), is(true));
|
||||
@@ -46,7 +46,7 @@ public class GeoResultUnitTests {
|
||||
assertThat(first.equals(fourth), is(false));
|
||||
assertThat(fourth.equals(first), is(false));
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullContent() {
|
||||
|
||||
@@ -24,7 +24,7 @@ import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link GeoResults}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class GeoResultsUnitTests {
|
||||
@@ -32,11 +32,11 @@ public class GeoResultsUnitTests {
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void calculatesAverageForGivenGeoResults() {
|
||||
|
||||
|
||||
GeoResult<Object> first = new GeoResult<Object>(new Object(), new Distance(2));
|
||||
GeoResult<Object> second = new GeoResult<Object>(new Object(), new Distance(5));
|
||||
GeoResults<Object> geoResults = new GeoResults<Object>(Arrays.asList(first, second));
|
||||
|
||||
|
||||
assertThat(geoResults.getAverageDistance(), is(new Distance(3.5)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,14 +17,14 @@ public class PointUnitTests {
|
||||
public void rejectsNullforCopyConstructor() {
|
||||
new Point(null);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void equalsIsImplementedCorrectly() {
|
||||
assertThat(new Point(1.5, 1.5), is(equalTo(new Point(1.5, 1.5))));
|
||||
assertThat(new Point(1.5, 1.5), is(not(equalTo(new Point(2.0, 2.0)))));
|
||||
assertThat(new Point(2.0, 2.0), is(not(equalTo(new Point(1.5, 1.5)))));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void invokingToStringWorksCorrectly() {
|
||||
new Point(1.5, 1.5).toString();
|
||||
|
||||
@@ -35,19 +35,19 @@ public class PolygonUnitTests {
|
||||
public void rejectsNullPoints() {
|
||||
new Polygon(null, null, null);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void createsSimplePolygon() {
|
||||
Polygon polygon = new Polygon(third, second, first);
|
||||
assertThat(polygon, is(notNullValue()));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void isEqualForSamePoints() {
|
||||
|
||||
|
||||
Polygon left = new Polygon(third, second, first);
|
||||
Polygon right = new Polygon(third, second, first);
|
||||
|
||||
|
||||
assertThat(left, is(right));
|
||||
assertThat(right, is(left));
|
||||
}
|
||||
|
||||
@@ -36,13 +36,13 @@ import com.mongodb.MongoException;
|
||||
|
||||
/**
|
||||
* Integration tests for index handling.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration("classpath:infrastructure.xml")
|
||||
public class IndexingIntegrationTests {
|
||||
|
||||
|
||||
@Autowired
|
||||
MongoOperations operations;
|
||||
|
||||
@@ -50,25 +50,24 @@ public class IndexingIntegrationTests {
|
||||
public void tearDown() {
|
||||
operations.dropCollection(IndexedPerson.class);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @see DATADOC-237
|
||||
*/
|
||||
@Test
|
||||
public void createsIndexWithFieldName() {
|
||||
|
||||
|
||||
operations.save(new IndexedPerson());
|
||||
assertThat(hasIndex("_firstname", IndexedPerson.class), is(true));
|
||||
}
|
||||
|
||||
|
||||
class IndexedPerson {
|
||||
|
||||
|
||||
@Field("_firstname")
|
||||
@Indexed
|
||||
String firstname;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns whether an index with the given name exists for the given entity type.
|
||||
*
|
||||
@@ -77,7 +76,7 @@ public class IndexingIntegrationTests {
|
||||
* @return
|
||||
*/
|
||||
private boolean hasIndex(final String indexName, Class<?> entityType) {
|
||||
|
||||
|
||||
return operations.execute(entityType, new CollectionCallback<Boolean>() {
|
||||
public Boolean doInCollection(DBCollection collection) throws MongoException, DataAccessException {
|
||||
for (DBObject indexInfo : collection.getIndexInfo()) {
|
||||
|
||||
@@ -28,7 +28,7 @@ import org.springframework.data.util.ClassTypeInformation;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link BasicMongoPersistentEntity}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
@@ -36,59 +36,61 @@ public class BasicMongoPersistentEntityUnitTests {
|
||||
|
||||
@Mock
|
||||
ApplicationContext context;
|
||||
|
||||
|
||||
@Test
|
||||
public void subclassInheritsAtDocumentAnnotation() {
|
||||
|
||||
|
||||
BasicMongoPersistentEntity<Person> entity = new BasicMongoPersistentEntity<Person>(
|
||||
ClassTypeInformation.from(Person.class));
|
||||
assertThat(entity.getCollection(), is("contacts"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void evaluatesSpELExpression() {
|
||||
|
||||
MongoPersistentEntity<Company> entity = new BasicMongoPersistentEntity<Company>(ClassTypeInformation.from(Company.class));
|
||||
|
||||
MongoPersistentEntity<Company> entity = new BasicMongoPersistentEntity<Company>(
|
||||
ClassTypeInformation.from(Company.class));
|
||||
assertThat(entity.getCollection(), is("35"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void collectionAllowsReferencingSpringBean() {
|
||||
|
||||
|
||||
CollectionProvider provider = new CollectionProvider();
|
||||
provider.collectionName = "reference";
|
||||
|
||||
|
||||
when(context.getBean("myBean")).thenReturn(provider);
|
||||
when(context.containsBean("myBean")).thenReturn(true);
|
||||
|
||||
BasicMongoPersistentEntity<DynamicallyMapped> entity = new BasicMongoPersistentEntity<DynamicallyMapped>(ClassTypeInformation.from(DynamicallyMapped.class));
|
||||
|
||||
BasicMongoPersistentEntity<DynamicallyMapped> entity = new BasicMongoPersistentEntity<DynamicallyMapped>(
|
||||
ClassTypeInformation.from(DynamicallyMapped.class));
|
||||
entity.setApplicationContext(context);
|
||||
|
||||
|
||||
assertThat(entity.getCollection(), is("reference"));
|
||||
}
|
||||
|
||||
|
||||
@Document(collection = "contacts")
|
||||
class Contact {
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
class Person extends Contact {
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Document(collection = "#{35}")
|
||||
class Company {
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Document(collection = "#{myBean.collectionName}")
|
||||
class DynamicallyMapped {
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
class CollectionProvider {
|
||||
String collectionName;
|
||||
|
||||
|
||||
public String getCollectionName() {
|
||||
return collectionName;
|
||||
}
|
||||
|
||||
@@ -36,9 +36,9 @@ import org.springframework.util.ReflectionUtils;
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class BasicMongoPersistentPropertyUnitTests {
|
||||
|
||||
|
||||
MongoPersistentEntity<Person> entity;
|
||||
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
entity = new BasicMongoPersistentEntity<Person>(ClassTypeInformation.from(Person.class));
|
||||
@@ -46,11 +46,11 @@ public class BasicMongoPersistentPropertyUnitTests {
|
||||
|
||||
@Test
|
||||
public void usesAnnotatedFieldName() {
|
||||
|
||||
|
||||
Field field = ReflectionUtils.findField(Person.class, "firstname");
|
||||
assertThat(getPropertyFor(field).getFieldName(), is("foo"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void returns_IdForIdProperty() {
|
||||
Field field = ReflectionUtils.findField(Person.class, "id");
|
||||
@@ -58,32 +58,32 @@ public class BasicMongoPersistentPropertyUnitTests {
|
||||
assertThat(property.isIdProperty(), is(true));
|
||||
assertThat(property.getFieldName(), is("_id"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void returnsPropertyNameForUnannotatedProperties() {
|
||||
|
||||
|
||||
Field field = ReflectionUtils.findField(Person.class, "lastname");
|
||||
assertThat(getPropertyFor(field).getFieldName(), is("lastname"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void preventsNegativeOrder() {
|
||||
getPropertyFor(ReflectionUtils.findField(Person.class, "ssn"));
|
||||
}
|
||||
|
||||
|
||||
private MongoPersistentProperty getPropertyFor(Field field) {
|
||||
return new BasicMongoPersistentProperty(field, null, entity, new SimpleTypeHolder());
|
||||
}
|
||||
|
||||
|
||||
class Person {
|
||||
|
||||
|
||||
@Id
|
||||
String id;
|
||||
|
||||
|
||||
@org.springframework.data.mongodb.core.mapping.Field("foo")
|
||||
String firstname;
|
||||
String lastname;
|
||||
|
||||
|
||||
@org.springframework.data.mongodb.core.mapping.Field(order = -20)
|
||||
String ssn;
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ public class GenericMappingTests {
|
||||
|
||||
MongoMappingContext context;
|
||||
MongoConverter converter;
|
||||
|
||||
|
||||
@Mock
|
||||
MongoDbFactory factory;
|
||||
|
||||
|
||||
@@ -25,9 +25,9 @@ public class GeoIndexedAppConfig extends AbstractMongoConfiguration {
|
||||
public String getMappingBasePackage() {
|
||||
return "org.springframework.data.mongodb.core.core.mapping";
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LoggingEventListener mappingEventsListener() {
|
||||
return new LoggingEventListener();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LoggingEventListener mappingEventsListener() {
|
||||
return new LoggingEventListener();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ import com.mongodb.MongoException;
|
||||
*/
|
||||
public class GeoIndexedTests {
|
||||
|
||||
private final String[] collectionsToDrop = new String[] { GeoIndexedAppConfig.GEO_COLLECTION, "Person"};
|
||||
private final String[] collectionsToDrop = new String[] { GeoIndexedAppConfig.GEO_COLLECTION, "Person" };
|
||||
|
||||
ApplicationContext applicationContext;
|
||||
MongoTemplate template;
|
||||
|
||||
@@ -58,7 +58,7 @@ import org.springframework.test.util.ReflectionTestUtils;
|
||||
public class MappingTests {
|
||||
|
||||
private static final Log LOGGER = LogFactory.getLog(MongoDbUtils.class);
|
||||
private final String[] collectionsToDrop = new String[]{
|
||||
private final String[] collectionsToDrop = new String[] {
|
||||
MongoCollectionUtils.getPreferredCollectionName(Person.class),
|
||||
MongoCollectionUtils.getPreferredCollectionName(PersonMapProperty.class),
|
||||
MongoCollectionUtils.getPreferredCollectionName(PersonWithObjectId.class),
|
||||
@@ -72,8 +72,8 @@ public class MappingTests {
|
||||
MongoCollectionUtils.getPreferredCollectionName(PersonWithLongDBRef.class),
|
||||
MongoCollectionUtils.getPreferredCollectionName(PersonNullProperties.class),
|
||||
MongoCollectionUtils.getPreferredCollectionName(Account.class),
|
||||
MongoCollectionUtils.getPreferredCollectionName(PrimitiveId.class),
|
||||
"foobar", "geolocation", "person1", "person2", "account"};
|
||||
MongoCollectionUtils.getPreferredCollectionName(PrimitiveId.class), "foobar", "geolocation", "person1",
|
||||
"person2", "account" };
|
||||
|
||||
ApplicationContext applicationContext;
|
||||
Mongo mongo;
|
||||
@@ -110,7 +110,8 @@ public class MappingTests {
|
||||
LOGGER.info("done inserting");
|
||||
assertNotNull(p.getId());
|
||||
|
||||
List<PersonWithObjectId> result = template.find(new Query(Criteria.where("ssn").is(12345)), PersonWithObjectId.class);
|
||||
List<PersonWithObjectId> result = template.find(new Query(Criteria.where("ssn").is(12345)),
|
||||
PersonWithObjectId.class);
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result.get(0).getSsn(), is(12345));
|
||||
}
|
||||
@@ -166,11 +167,11 @@ public class MappingTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void testWriteEntity() {
|
||||
|
||||
Address addr = new Address();
|
||||
addr.setLines(new String[]{"1234 W. 1st Street", "Apt. 12"});
|
||||
addr.setLines(new String[] { "1234 W. 1st Street", "Apt. 12" });
|
||||
addr.setCity("Anytown");
|
||||
addr.setPostalCode(12345);
|
||||
addr.setCountry("USA");
|
||||
@@ -202,10 +203,10 @@ public class MappingTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void testUniqueIndex() {
|
||||
Address addr = new Address();
|
||||
addr.setLines(new String[]{"1234 W. 1st Street", "Apt. 12"});
|
||||
addr.setLines(new String[] { "1234 W. 1st Street", "Apt. 12" });
|
||||
addr.setCity("Anytown");
|
||||
addr.setPostalCode(12345);
|
||||
addr.setCountry("USA");
|
||||
@@ -229,17 +230,17 @@ public class MappingTests {
|
||||
persons.add(new PersonCustomCollection2(66666, "Person", "Two"));
|
||||
template.insertAll(persons);
|
||||
|
||||
List<PersonCustomCollection1> p1Results = template.find(new Query(Criteria.where("ssn").is(55555)), PersonCustomCollection1.class,
|
||||
"person1");
|
||||
List<PersonCustomCollection2> p2Results = template.find(new Query(Criteria.where("ssn").is(66666)), PersonCustomCollection2.class,
|
||||
"person2");
|
||||
List<PersonCustomCollection1> p1Results = template.find(new Query(Criteria.where("ssn").is(55555)),
|
||||
PersonCustomCollection1.class, "person1");
|
||||
List<PersonCustomCollection2> p2Results = template.find(new Query(Criteria.where("ssn").is(66666)),
|
||||
PersonCustomCollection2.class, "person2");
|
||||
assertThat(p1Results.size(), is(1));
|
||||
assertThat(p2Results.size(), is(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPrimitivesAndCustomCollectionName() {
|
||||
Location loc = new Location(new double[]{1.0, 2.0}, new int[]{1, 2, 3, 4}, new float[]{1.0f, 2.0f});
|
||||
Location loc = new Location(new double[] { 1.0, 2.0 }, new int[] { 1, 2, 3, 4 }, new float[] { 1.0f, 2.0f });
|
||||
template.insert(loc);
|
||||
|
||||
List<Location> result = template.find(new Query(Criteria.where("_id").is(loc.getId())), Location.class, "places");
|
||||
@@ -255,7 +256,8 @@ public class MappingTests {
|
||||
public Boolean doInCollection(DBCollection collection) throws MongoException, DataAccessException {
|
||||
List<DBObject> indexes = collection.getIndexInfo();
|
||||
for (DBObject dbo : indexes) {
|
||||
if (dbo.get("name") != null && dbo.get("name") instanceof String && ((String)dbo.get("name")).startsWith("name")) {
|
||||
if (dbo.get("name") != null && dbo.get("name") instanceof String
|
||||
&& ((String) dbo.get("name")).startsWith("name")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -271,7 +273,8 @@ public class MappingTests {
|
||||
public Boolean doInCollection(DBCollection collection) throws MongoException, DataAccessException {
|
||||
List<DBObject> indexes = collection.getIndexInfo();
|
||||
for (DBObject dbo : indexes) {
|
||||
if (dbo.get("name") != null && dbo.get("name") instanceof String && ((String)dbo.get("name")).startsWith("name")) {
|
||||
if (dbo.get("name") != null && dbo.get("name") instanceof String
|
||||
&& ((String) dbo.get("name")).startsWith("name")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -282,8 +285,8 @@ public class MappingTests {
|
||||
|
||||
@Test
|
||||
public void testMultiDimensionalArrayProperties() {
|
||||
String[][] grid = new String[][]{new String[]{"1", "2", "3", "4"}, new String[]{"5", "6", "7", "8"},
|
||||
new String[]{"9", "10", "11", "12"}};
|
||||
String[][] grid = new String[][] { new String[] { "1", "2", "3", "4" }, new String[] { "5", "6", "7", "8" },
|
||||
new String[] { "9", "10", "11", "12" } };
|
||||
PersonMultiDimArrays p = new PersonMultiDimArrays(123, "Multi", "Dimensional", grid);
|
||||
|
||||
template.insert(p);
|
||||
@@ -316,7 +319,7 @@ public class MappingTests {
|
||||
|
||||
@Test
|
||||
public void testDbRef() {
|
||||
double[] pos = new double[]{37.0625, -95.677068};
|
||||
double[] pos = new double[] { 37.0625, -95.677068 };
|
||||
GeoLocation geo = new GeoLocation(pos);
|
||||
template.insert(geo);
|
||||
|
||||
@@ -340,7 +343,7 @@ public class MappingTests {
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public void testQueryUpdate() {
|
||||
Address addr = new Address();
|
||||
addr.setLines(new String[]{"1234 W. 1st Street", "Apt. 12"});
|
||||
addr.setLines(new String[] { "1234 W. 1st Street", "Apt. 12" });
|
||||
addr.setCity("Anytown");
|
||||
addr.setPostalCode(12345);
|
||||
addr.setCountry("USA");
|
||||
@@ -354,31 +357,33 @@ public class MappingTests {
|
||||
Person p2 = template.findOne(query(where("ssn").is(1111)), Person.class);
|
||||
assertThat(p2.getAddress().getCity(), is("New Town"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void testUpsert() {
|
||||
Address addr = new Address();
|
||||
addr.setLines(new String[]{"1234 W. 1st Street", "Apt. 12"});
|
||||
addr.setLines(new String[] { "1234 W. 1st Street", "Apt. 12" });
|
||||
addr.setCity("Anytown");
|
||||
addr.setPostalCode(12345);
|
||||
addr.setCountry("USA");
|
||||
|
||||
Person p2 = template.findOne(query(where("ssn").is(1111)), Person.class);
|
||||
assertNull(p2);
|
||||
|
||||
template.upsert(query(where("ssn").is(1111).and("firstName").is("Query").and("lastName").is("Update")), update("address", addr), Person.class);
|
||||
|
||||
template.upsert(query(where("ssn").is(1111).and("firstName").is("Query").and("lastName").is("Update")),
|
||||
update("address", addr), Person.class);
|
||||
|
||||
p2 = template.findOne(query(where("ssn").is(1111)), Person.class);
|
||||
assertThat(p2.getAddress().getCity(), is("Anytown"));
|
||||
|
||||
|
||||
template.dropCollection(Person.class);
|
||||
template.upsert(query(where("ssn").is(1111).and("firstName").is("Query").and("lastName").is("Update")), update("address", addr), "person");
|
||||
template.upsert(query(where("ssn").is(1111).and("firstName").is("Query").and("lastName").is("Update")),
|
||||
update("address", addr), "person");
|
||||
p2 = template.findOne(query(where("ssn").is(1111)), Person.class);
|
||||
assertThat(p2.getAddress().getCity(), is("Anytown"));
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testOrQuery() {
|
||||
PersonWithObjectId p1 = new PersonWithObjectId(1, "first", "");
|
||||
@@ -386,8 +391,8 @@ public class MappingTests {
|
||||
PersonWithObjectId p2 = new PersonWithObjectId(2, "second", "");
|
||||
template.save(p2);
|
||||
|
||||
List<PersonWithObjectId> results = template.find(new Query(
|
||||
new Criteria().orOperator(where("ssn").is(1), where("ssn").is(2))), PersonWithObjectId.class);
|
||||
List<PersonWithObjectId> results = template.find(
|
||||
new Query(new Criteria().orOperator(where("ssn").is(1), where("ssn").is(2))), PersonWithObjectId.class);
|
||||
|
||||
assertNotNull(results);
|
||||
assertThat(results.size(), is(2));
|
||||
@@ -426,42 +431,35 @@ public class MappingTests {
|
||||
public void testNoMappingAnnotationsUsingLongAsId() {
|
||||
PersonPojoLongId p = new PersonPojoLongId(1, "Text");
|
||||
template.insert(p);
|
||||
template.updateFirst(query(where("id").is(1)), update("text", "New Text"),
|
||||
PersonPojoLongId.class);
|
||||
template.updateFirst(query(where("id").is(1)), update("text", "New Text"), PersonPojoLongId.class);
|
||||
|
||||
PersonPojoLongId p2 = template.findOne(query(where("id").is(1)),
|
||||
PersonPojoLongId.class);
|
||||
PersonPojoLongId p2 = template.findOne(query(where("id").is(1)), PersonPojoLongId.class);
|
||||
assertEquals("New Text", p2.getText());
|
||||
|
||||
p.setText("Different Text");
|
||||
template.save(p);
|
||||
|
||||
PersonPojoLongId p3 = template.findOne(query(where("id").is(1)),
|
||||
PersonPojoLongId.class);
|
||||
PersonPojoLongId p3 = template.findOne(query(where("id").is(1)), PersonPojoLongId.class);
|
||||
assertEquals("Different Text", p3.getText());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoMappingAnnotationsUsingStringAsId() {
|
||||
//Assign the String Id in code
|
||||
// Assign the String Id in code
|
||||
PersonPojoStringId p = new PersonPojoStringId("1", "Text");
|
||||
template.insert(p);
|
||||
template.updateFirst(query(where("id").is("1")), update("text", "New Text"),
|
||||
PersonPojoStringId.class);
|
||||
template.updateFirst(query(where("id").is("1")), update("text", "New Text"), PersonPojoStringId.class);
|
||||
|
||||
PersonPojoStringId p2 = template.findOne(query(where("id").is("1")),
|
||||
PersonPojoStringId.class);
|
||||
PersonPojoStringId p2 = template.findOne(query(where("id").is("1")), PersonPojoStringId.class);
|
||||
assertEquals("New Text", p2.getText());
|
||||
|
||||
p.setText("Different Text");
|
||||
template.save(p);
|
||||
|
||||
PersonPojoStringId p3 = template.findOne(query(where("id").is("1")),
|
||||
PersonPojoStringId.class);
|
||||
PersonPojoStringId p3 = template.findOne(query(where("id").is("1")), PersonPojoStringId.class);
|
||||
assertEquals("Different Text", p3.getText());
|
||||
|
||||
|
||||
PersonPojoStringId p4 = new PersonPojoStringId("2", "Text-2");
|
||||
template.insert(p4);
|
||||
|
||||
@@ -513,7 +511,6 @@ public class MappingTests {
|
||||
assertThat(result.items.get(0).id, is(items.id));
|
||||
}
|
||||
|
||||
|
||||
class Container {
|
||||
|
||||
@Id
|
||||
|
||||
@@ -24,7 +24,7 @@ import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link MongoMappingContext}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class MongoMappingContextUnitTests {
|
||||
|
||||
@@ -18,31 +18,31 @@ import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link MongoPersistentPropertyComparator}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MongoPersistentPropertyComparatorUnitTests {
|
||||
|
||||
|
||||
@Mock
|
||||
MongoPersistentProperty firstName;
|
||||
|
||||
|
||||
@Mock
|
||||
MongoPersistentProperty lastName;
|
||||
|
||||
|
||||
@Mock
|
||||
MongoPersistentProperty ssn;
|
||||
|
||||
@Test
|
||||
public void ordersPropertiesCorrectly() {
|
||||
|
||||
|
||||
when(ssn.getFieldOrder()).thenReturn(10);
|
||||
when(firstName.getFieldOrder()).thenReturn(20);
|
||||
when(lastName.getFieldOrder()).thenReturn(Integer.MAX_VALUE);
|
||||
|
||||
|
||||
List<MongoPersistentProperty> properties = Arrays.asList(firstName, lastName, ssn);
|
||||
Collections.sort(properties, MongoPersistentPropertyComparator.INSTANCE);
|
||||
|
||||
|
||||
assertThat(properties.get(0), is(ssn));
|
||||
assertThat(properties.get(1), is(firstName));
|
||||
assertThat(properties.get(2), is(lastName));
|
||||
|
||||
@@ -17,10 +17,10 @@ public class SimpleMappingContextUnitTests {
|
||||
|
||||
@Test
|
||||
public void returnsIdPropertyCorrectly() {
|
||||
|
||||
|
||||
SimpleMongoMappingContext context = new SimpleMongoMappingContext();
|
||||
SimpleMongoPersistentEntity<?> entity = context.getPersistentEntity(Person.class);
|
||||
|
||||
|
||||
MongoPersistentProperty idProperty = entity.getIdProperty();
|
||||
assertThat(idProperty, is(notNullValue()));
|
||||
assertThat(idProperty.getName(), is("id"));
|
||||
|
||||
@@ -29,37 +29,37 @@ import com.mongodb.DBObject;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link AbstractMongoEventListener}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class AbstractMongoEventListenerUnitTests {
|
||||
|
||||
|
||||
@Test
|
||||
public void invokesCallbackForEventForPerson() {
|
||||
|
||||
|
||||
MongoMappingEvent<Person> event = new BeforeConvertEvent<Person>(new Person("Dave", "Matthews"));
|
||||
SamplePersonEventListener listener = new SamplePersonEventListener();
|
||||
listener.onApplicationEvent(event);
|
||||
assertThat(listener.invokedOnBeforeConvert, is(true));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void dropsEventIfNotForCorrectDomainType() {
|
||||
|
||||
|
||||
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
|
||||
context.refresh();
|
||||
|
||||
SamplePersonEventListener listener = new SamplePersonEventListener();
|
||||
context.addApplicationListener(listener);
|
||||
|
||||
|
||||
context.publishEvent(new BeforeConvertEvent<Person>(new Person("Dave", "Matthews")));
|
||||
assertThat(listener.invokedOnBeforeConvert, is(true));
|
||||
|
||||
|
||||
listener.invokedOnBeforeConvert = false;
|
||||
context.publishEvent(new BeforeConvertEvent<String>("Test"));
|
||||
assertThat(listener.invokedOnBeforeConvert, is(false));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATADOC-289
|
||||
*/
|
||||
@@ -115,14 +115,14 @@ public class AbstractMongoEventListenerUnitTests {
|
||||
assertThat(personListener.invokedOnAfterLoad, is(false));
|
||||
assertThat(contactListener.invokedOnAfterLoad, is(true));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATADOC-333
|
||||
*/
|
||||
@Test
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public void handlesUntypedImplementations() {
|
||||
|
||||
|
||||
UntypedEventListener listener = new UntypedEventListener();
|
||||
listener.onApplicationEvent(new MongoMappingEvent(new Object(), new BasicDBObject()));
|
||||
}
|
||||
@@ -131,12 +131,12 @@ public class AbstractMongoEventListenerUnitTests {
|
||||
|
||||
boolean invokedOnBeforeConvert;
|
||||
boolean invokedOnAfterLoad;
|
||||
|
||||
|
||||
@Override
|
||||
public void onBeforeConvert(Person source) {
|
||||
invokedOnBeforeConvert = true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void onAfterLoad(DBObject dbo) {
|
||||
invokedOnAfterLoad = true;
|
||||
@@ -177,6 +177,6 @@ public class AbstractMongoEventListenerUnitTests {
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
class UntypedEventListener extends AbstractMongoEventListener {
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,46 +65,47 @@ public class ApplicationContextEventTests {
|
||||
db.getCollection(coll).drop();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void beforeSaveEvent() {
|
||||
PersonBeforeSaveListener personBeforeSaveListener = applicationContext.getBean(PersonBeforeSaveListener.class);
|
||||
AfterSaveListener afterSaveListener = applicationContext.getBean(AfterSaveListener.class);
|
||||
SimpleMappingEventListener simpleMappingEventListener = applicationContext.getBean(SimpleMappingEventListener.class);
|
||||
|
||||
SimpleMappingEventListener simpleMappingEventListener = applicationContext
|
||||
.getBean(SimpleMappingEventListener.class);
|
||||
|
||||
assertEquals(0, personBeforeSaveListener.seenEvents.size());
|
||||
assertEquals(0, afterSaveListener.seenEvents.size());
|
||||
|
||||
|
||||
assertEquals(0, simpleMappingEventListener.onBeforeSaveEvents.size());
|
||||
assertEquals(0, simpleMappingEventListener.onAfterSaveEvents.size());
|
||||
|
||||
|
||||
|
||||
PersonPojoStringId p = new PersonPojoStringId("1", "Text");
|
||||
template.insert(p);
|
||||
|
||||
|
||||
assertEquals(1, personBeforeSaveListener.seenEvents.size());
|
||||
assertEquals(1, afterSaveListener.seenEvents.size());
|
||||
|
||||
|
||||
assertEquals(1, simpleMappingEventListener.onBeforeSaveEvents.size());
|
||||
assertEquals(1, simpleMappingEventListener.onAfterSaveEvents.size());
|
||||
|
||||
Assert.assertTrue(personBeforeSaveListener.seenEvents.get(0) instanceof BeforeSaveEvent<?>);
|
||||
Assert.assertTrue(afterSaveListener.seenEvents.get(0) instanceof AfterSaveEvent<?>);
|
||||
|
||||
BeforeSaveEvent<PersonPojoStringId> beforeSaveEvent = (BeforeSaveEvent<PersonPojoStringId>)personBeforeSaveListener.seenEvents.get(0);
|
||||
BeforeSaveEvent<PersonPojoStringId> beforeSaveEvent = (BeforeSaveEvent<PersonPojoStringId>) personBeforeSaveListener.seenEvents
|
||||
.get(0);
|
||||
PersonPojoStringId p2 = beforeSaveEvent.getSource();
|
||||
DBObject dbo = beforeSaveEvent.getDBObject();
|
||||
|
||||
|
||||
comparePersonAndDbo(p, p2, dbo);
|
||||
|
||||
AfterSaveEvent<Object> afterSaveEvent = (AfterSaveEvent<Object>)afterSaveListener.seenEvents.get(0);
|
||||
|
||||
AfterSaveEvent<Object> afterSaveEvent = (AfterSaveEvent<Object>) afterSaveListener.seenEvents.get(0);
|
||||
Assert.assertTrue(afterSaveEvent.getSource() instanceof PersonPojoStringId);
|
||||
p2 = (PersonPojoStringId)afterSaveEvent.getSource();
|
||||
p2 = (PersonPojoStringId) afterSaveEvent.getSource();
|
||||
dbo = beforeSaveEvent.getDBObject();
|
||||
|
||||
|
||||
comparePersonAndDbo(p, p2, dbo);
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void comparePersonAndDbo(PersonPojoStringId p, PersonPojoStringId p2, DBObject dbo) {
|
||||
|
||||
@@ -39,12 +39,12 @@ public class ApplicationContextEventTestsAppConfig extends AbstractMongoConfigur
|
||||
public PersonBeforeSaveListener personBeforeSaveListener() {
|
||||
return new PersonBeforeSaveListener();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public AfterSaveListener afterSaveListener() {
|
||||
return new AfterSaveListener();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public SimpleMappingEventListener simpleMappingEventListener() {
|
||||
return new SimpleMappingEventListener();
|
||||
|
||||
@@ -19,7 +19,6 @@ import java.util.ArrayList;
|
||||
|
||||
import com.mongodb.DBObject;
|
||||
|
||||
|
||||
public class SimpleMappingEventListener extends AbstractMongoEventListener<Object> {
|
||||
|
||||
public final ArrayList<BeforeConvertEvent<Object>> onBeforeConvertEvents = new ArrayList<BeforeConvertEvent<Object>>();
|
||||
@@ -27,7 +26,7 @@ public class SimpleMappingEventListener extends AbstractMongoEventListener<Objec
|
||||
public final ArrayList<AfterSaveEvent<Object>> onAfterSaveEvents = new ArrayList<AfterSaveEvent<Object>>();
|
||||
public final ArrayList<AfterLoadEvent<Object>> onAfterLoadEvents = new ArrayList<AfterLoadEvent<Object>>();
|
||||
public final ArrayList<AfterConvertEvent<Object>> onAfterConvertEvents = new ArrayList<AfterConvertEvent<Object>>();
|
||||
|
||||
|
||||
@Override
|
||||
public void onBeforeConvert(Object source) {
|
||||
onBeforeConvertEvents.add(new BeforeConvertEvent<Object>(source));
|
||||
|
||||
@@ -3,17 +3,17 @@ package org.springframework.data.mongodb.core.mapreduce;
|
||||
public class ContentAndVersion {
|
||||
|
||||
private String id;
|
||||
|
||||
|
||||
private String document_id;
|
||||
|
||||
|
||||
private String content;
|
||||
|
||||
|
||||
private String author;
|
||||
|
||||
private Long version;
|
||||
|
||||
|
||||
private Long value;
|
||||
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
@@ -38,7 +38,6 @@ public class ContentAndVersion {
|
||||
this.document_id = documentId;
|
||||
}
|
||||
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
@@ -68,6 +67,5 @@ public class ContentAndVersion {
|
||||
return "ContentAndVersion [id=" + id + ", document_id=" + document_id + ", content=" + content + ", author="
|
||||
+ author + ", version=" + version + ", value=" + value + "]";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -46,33 +46,30 @@ public class GroupByTests {
|
||||
|
||||
@Autowired
|
||||
MongoDbFactory factory;
|
||||
|
||||
|
||||
@Autowired
|
||||
ApplicationContext applicationContext;
|
||||
|
||||
//@Autowired
|
||||
//MongoTemplate mongoTemplate;
|
||||
|
||||
|
||||
|
||||
// @Autowired
|
||||
// MongoTemplate mongoTemplate;
|
||||
|
||||
MongoTemplate mongoTemplate;
|
||||
|
||||
@Autowired
|
||||
@SuppressWarnings("unchecked")
|
||||
public void setMongo(Mongo mongo) throws Exception {
|
||||
|
||||
|
||||
MongoMappingContext mappingContext = new MongoMappingContext();
|
||||
mappingContext.setInitialEntitySet(new HashSet<Class<?>>(Arrays.asList(XObject.class)));
|
||||
mappingContext.afterPropertiesSet();
|
||||
|
||||
MappingMongoConverter mappingConverter = new MappingMongoConverter(factory, mappingContext);
|
||||
MappingMongoConverter mappingConverter = new MappingMongoConverter(factory, mappingContext);
|
||||
mappingConverter.afterPropertiesSet();
|
||||
this.mongoTemplate = new MongoTemplate(factory, mappingConverter);
|
||||
mongoTemplate.setApplicationContext(applicationContext);
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
cleanDb();
|
||||
@@ -87,92 +84,95 @@ public class GroupByTests {
|
||||
mongoTemplate.dropCollection(mongoTemplate.getCollectionName(XObject.class));
|
||||
mongoTemplate.dropCollection("group_test_collection");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void singleKeyCreation() {
|
||||
DBObject gc = new GroupBy("a").getGroupByObject();
|
||||
//String expected = "{ \"group\" : { \"ns\" : \"test\" , \"key\" : { \"a\" : 1} , \"cond\" : null , \"$reduce\" : null , \"initial\" : null }}";
|
||||
String expected = "{ \"key\" : { \"a\" : 1} , \"$reduce\" : null , \"initial\" : null }";
|
||||
Assert.assertEquals(expected, gc.toString());
|
||||
public void singleKeyCreation() {
|
||||
DBObject gc = new GroupBy("a").getGroupByObject();
|
||||
// String expected =
|
||||
// "{ \"group\" : { \"ns\" : \"test\" , \"key\" : { \"a\" : 1} , \"cond\" : null , \"$reduce\" : null , \"initial\" : null }}";
|
||||
String expected = "{ \"key\" : { \"a\" : 1} , \"$reduce\" : null , \"initial\" : null }";
|
||||
Assert.assertEquals(expected, gc.toString());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void multipleKeyCreation() {
|
||||
DBObject gc = GroupBy.key("a","b").getGroupByObject();
|
||||
//String expected = "{ \"group\" : { \"ns\" : \"test\" , \"key\" : { \"a\" : 1 , \"b\" : 1} , \"cond\" : null , \"$reduce\" : null , \"initial\" : null }}";
|
||||
String expected = "{ \"key\" : { \"a\" : 1 , \"b\" : 1} , \"$reduce\" : null , \"initial\" : null }";
|
||||
Assert.assertEquals(expected, gc.toString());
|
||||
DBObject gc = GroupBy.key("a", "b").getGroupByObject();
|
||||
// String expected =
|
||||
// "{ \"group\" : { \"ns\" : \"test\" , \"key\" : { \"a\" : 1 , \"b\" : 1} , \"cond\" : null , \"$reduce\" : null , \"initial\" : null }}";
|
||||
String expected = "{ \"key\" : { \"a\" : 1 , \"b\" : 1} , \"$reduce\" : null , \"initial\" : null }";
|
||||
Assert.assertEquals(expected, gc.toString());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void keyFunctionCreation() {
|
||||
DBObject gc = GroupBy.keyFunction("classpath:keyFunction.js").getGroupByObject();
|
||||
String expected = "{ \"$keyf\" : \"classpath:keyFunction.js\" , \"$reduce\" : null , \"initial\" : null }";
|
||||
Assert.assertEquals(expected, gc.toString());
|
||||
DBObject gc = GroupBy.keyFunction("classpath:keyFunction.js").getGroupByObject();
|
||||
String expected = "{ \"$keyf\" : \"classpath:keyFunction.js\" , \"$reduce\" : null , \"initial\" : null }";
|
||||
Assert.assertEquals(expected, gc.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void SimpleGroup() {
|
||||
createGroupByData();
|
||||
GroupByResults<XObject> results;
|
||||
|
||||
results = mongoTemplate.group("group_test_collection",
|
||||
GroupBy.key("x").initialDocument(new BasicDBObject("count", 0)).reduceFunction("function(doc, prev) { prev.count += 1 }"), XObject.class);
|
||||
|
||||
|
||||
results = mongoTemplate.group(
|
||||
"group_test_collection",
|
||||
GroupBy.key("x").initialDocument(new BasicDBObject("count", 0))
|
||||
.reduceFunction("function(doc, prev) { prev.count += 1 }"), XObject.class);
|
||||
|
||||
assertMapReduceResults(results);
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void SimpleGroupWithKeyFunction() {
|
||||
createGroupByData();
|
||||
GroupByResults<XObject> results;
|
||||
|
||||
results = mongoTemplate.group("group_test_collection",
|
||||
GroupBy.keyFunction("function(doc) { return { x : doc.x }; }").initialDocument("{ count: 0 }").reduceFunction("function(doc, prev) { prev.count += 1 }"), XObject.class);
|
||||
|
||||
assertMapReduceResults(results);
|
||||
|
||||
results = mongoTemplate.group(
|
||||
"group_test_collection",
|
||||
GroupBy.keyFunction("function(doc) { return { x : doc.x }; }").initialDocument("{ count: 0 }")
|
||||
.reduceFunction("function(doc, prev) { prev.count += 1 }"), XObject.class);
|
||||
|
||||
assertMapReduceResults(results);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void SimpleGroupWithFunctionsAsResources() {
|
||||
createGroupByData();
|
||||
GroupByResults<XObject> results;
|
||||
|
||||
results = mongoTemplate.group("group_test_collection",
|
||||
GroupBy.keyFunction("classpath:keyFunction.js").initialDocument("{ count: 0 }").reduceFunction("classpath:groupReduce.js"), XObject.class);
|
||||
|
||||
assertMapReduceResults(results);
|
||||
|
||||
results = mongoTemplate.group("group_test_collection", GroupBy.keyFunction("classpath:keyFunction.js")
|
||||
.initialDocument("{ count: 0 }").reduceFunction("classpath:groupReduce.js"), XObject.class);
|
||||
|
||||
assertMapReduceResults(results);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void SimpleGroupWithQueryAndFunctionsAsResources() {
|
||||
createGroupByData();
|
||||
GroupByResults<XObject> results;
|
||||
|
||||
results = mongoTemplate.group(where("x").gt(0),
|
||||
"group_test_collection",
|
||||
keyFunction("classpath:keyFunction.js").initialDocument("{ count: 0 }").reduceFunction("classpath:groupReduce.js"), XObject.class);
|
||||
|
||||
assertMapReduceResults(results);
|
||||
|
||||
results = mongoTemplate.group(where("x").gt(0), "group_test_collection", keyFunction("classpath:keyFunction.js")
|
||||
.initialDocument("{ count: 0 }").reduceFunction("classpath:groupReduce.js"), XObject.class);
|
||||
|
||||
assertMapReduceResults(results);
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void assertMapReduceResults(GroupByResults<XObject> results) {
|
||||
DBObject dboRawResults = results.getRawResults();
|
||||
String expected = "{ \"serverUsed\" : \"127.0.0.1:27017\" , \"retval\" : [ { \"x\" : 1.0 , \"count\" : 2.0} , { \"x\" : 2.0 , \"count\" : 1.0} , { \"x\" : 3.0 , \"count\" : 3.0}] , \"count\" : 6.0 , \"keys\" : 3 , \"ok\" : 1.0}";
|
||||
Assert.assertEquals(expected, dboRawResults.toString());
|
||||
|
||||
|
||||
int numResults = 0;
|
||||
for (XObject xObject : results) {
|
||||
if (xObject.getX() == 1) {
|
||||
if (xObject.getX() == 1) {
|
||||
Assert.assertEquals(2, xObject.getCount(), 0.001);
|
||||
}
|
||||
if (xObject.getX() == 2) {
|
||||
if (xObject.getX() == 2) {
|
||||
Assert.assertEquals(1, xObject.getCount(), 0.001);
|
||||
}
|
||||
if (xObject.getX() == 3) {
|
||||
if (xObject.getX() == 3) {
|
||||
Assert.assertEquals(3, xObject.getCount(), 0.001);
|
||||
}
|
||||
numResults++;
|
||||
@@ -182,7 +182,6 @@ public class GroupByTests {
|
||||
Assert.assertEquals(3, results.getKeys());
|
||||
}
|
||||
|
||||
|
||||
private void createGroupByData() {
|
||||
DBCollection c = mongoTemplate.getDb().getCollection("group_test_collection");
|
||||
c.save(new BasicDBObject("x", 1));
|
||||
|
||||
@@ -19,7 +19,6 @@ import org.junit.Test;
|
||||
|
||||
public class MapReduceOptionsTests {
|
||||
|
||||
|
||||
@Test
|
||||
public void testFinalize() {
|
||||
new MapReduceOptions().finalizeFunction("code");
|
||||
|
||||
@@ -112,10 +112,10 @@ public class MapReduceTests {
|
||||
String reduce = "function (key, values) { return Math.max.apply(Math, values); }";
|
||||
MapReduceResults<ContentAndVersion> results = mongoTemplate.mapReduce("jmr2", map, reduce,
|
||||
new MapReduceOptions().outputCollection("jmr2_out"), ContentAndVersion.class);
|
||||
|
||||
|
||||
int size = 0;
|
||||
for (ContentAndVersion cv : results) {
|
||||
if (cv.getId().equals("Resume")) {
|
||||
if (cv.getId().equals("Resume")) {
|
||||
assertEquals(6, cv.getValue().longValue());
|
||||
}
|
||||
if (cv.getId().equals("Schema")) {
|
||||
@@ -126,7 +126,7 @@ public class MapReduceTests {
|
||||
}
|
||||
size++;
|
||||
}
|
||||
assertEquals(3,size);
|
||||
assertEquals(3, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -134,11 +134,11 @@ public class MapReduceTests {
|
||||
createNumberAndVersionData();
|
||||
String map = "function () { emit(this.number, this.version); }";
|
||||
String reduce = "function (key, values) { return Math.max.apply(Math, values); }";
|
||||
MapReduceResults<NumberAndVersion> results =
|
||||
mongoTemplate.mapReduce("jmr2", map, reduce, new MapReduceOptions().outputCollection("jmr2_out"), NumberAndVersion.class);
|
||||
int size = 0;
|
||||
MapReduceResults<NumberAndVersion> results = mongoTemplate.mapReduce("jmr2", map, reduce,
|
||||
new MapReduceOptions().outputCollection("jmr2_out"), NumberAndVersion.class);
|
||||
int size = 0;
|
||||
for (NumberAndVersion nv : results) {
|
||||
if (nv.getId().equals("1")) {
|
||||
if (nv.getId().equals("1")) {
|
||||
assertEquals(2, nv.getValue().longValue());
|
||||
}
|
||||
if (nv.getId().equals("2")) {
|
||||
@@ -149,7 +149,7 @@ public class MapReduceTests {
|
||||
}
|
||||
size++;
|
||||
}
|
||||
assertEquals(3,size);
|
||||
assertEquals(3, size);
|
||||
}
|
||||
|
||||
private void createNumberAndVersionData() {
|
||||
|
||||
@@ -6,35 +6,42 @@ public class NumberAndVersion {
|
||||
private Long number;
|
||||
private Long version;
|
||||
private Long value;
|
||||
|
||||
|
||||
public Long getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(Long value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
public void setNumber(Long number) {
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
public Long getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public void setVersion(Long version) {
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "NumberAndVersion [id=" + id + ", number=" + number + ", version=" + version + ", value=" + value + "]";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ package org.springframework.data.mongodb.core.mapreduce;
|
||||
public class ValueObject {
|
||||
|
||||
private String id;
|
||||
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
@@ -22,5 +22,5 @@ public class ValueObject {
|
||||
public String toString() {
|
||||
return "ValueObject [id=" + id + ", value=" + value + "]";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -3,33 +3,28 @@ package org.springframework.data.mongodb.core.mapreduce;
|
||||
public class XObject {
|
||||
|
||||
private float x;
|
||||
|
||||
private float count;
|
||||
|
||||
private float count;
|
||||
|
||||
public float getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
|
||||
public void setX(float x) {
|
||||
this.x = x;
|
||||
}
|
||||
|
||||
|
||||
public float getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
|
||||
public void setCount(float count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "XObject [x=" + x + " count = " + count + "]";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -26,11 +26,11 @@ import com.mongodb.DBObject;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link BasicQuery}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class BasicQueryUnitTests {
|
||||
|
||||
|
||||
@Test
|
||||
public void createsQueryFromPlainJson() {
|
||||
Query q = new BasicQuery("{ \"name\" : \"Thomas\"}");
|
||||
@@ -45,14 +45,14 @@ public class BasicQueryUnitTests {
|
||||
reference.put("age", new BasicDBObject("$lt", 80));
|
||||
assertThat(q.getQueryObject(), is(reference));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void overridesSortCorrectly() {
|
||||
|
||||
|
||||
BasicQuery query = new BasicQuery("{}");
|
||||
query.setSortObject(new BasicDBObject("name", -1));
|
||||
query.sort().on("lastname", Order.ASCENDING);
|
||||
|
||||
|
||||
DBObject sortReference = new BasicDBObject("name", -1);
|
||||
sortReference.put("lastname", 1);
|
||||
assertThat(query.getSortObject(), is(sortReference));
|
||||
|
||||
@@ -71,7 +71,7 @@ public class IndexTests {
|
||||
|
||||
@Test
|
||||
public void ensuresPropertyOrder() {
|
||||
|
||||
|
||||
Index on = new Index("foo", Order.ASCENDING).on("bar", Order.ASCENDING);
|
||||
assertThat(on.getIndexKeys().toString(), is("{ \"foo\" : 1 , \"bar\" : 1}"));
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import org.junit.Test;
|
||||
import org.springframework.data.mongodb.core.geo.Metrics;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class NearQueryUnitTests {
|
||||
@@ -16,28 +16,28 @@ public class NearQueryUnitTests {
|
||||
public void rejectsNullPoint() {
|
||||
NearQuery.near(null);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void settingUpNearWithMetricRecalculatesDistance() {
|
||||
|
||||
|
||||
NearQuery query = NearQuery.near(2.5, 2.5, Metrics.KILOMETERS).maxDistance(150);
|
||||
|
||||
|
||||
assertThat((Double) query.toDBObject().get("maxDistance"), is(0.02351783914331097));
|
||||
assertThat((Boolean) query.toDBObject().get("spherical"), is(true));
|
||||
assertThat((Double) query.toDBObject().get("distanceMultiplier"), is(Metrics.KILOMETERS.getMultiplier()));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void settingMetricRecalculatesMaxDistance() {
|
||||
|
||||
|
||||
NearQuery query = NearQuery.near(2.5, 2.5, Metrics.KILOMETERS).maxDistance(150);
|
||||
|
||||
|
||||
assertThat((Double) query.toDBObject().get("maxDistance"), is(0.02351783914331097));
|
||||
assertThat((Double) query.toDBObject().get("distanceMultiplier"), is(Metrics.KILOMETERS.getMultiplier()));
|
||||
|
||||
|
||||
query.inMiles();
|
||||
assertThat((Double) query.toDBObject().get("distanceMultiplier"), is(Metrics.MILES.getMultiplier()));
|
||||
|
||||
|
||||
NearQuery.near(2.5, 2.5).maxDistance(150).inKilometers();
|
||||
assertThat((Double) query.toDBObject().get("maxDistance"), is(0.02351783914331097));
|
||||
}
|
||||
|
||||
@@ -52,19 +52,19 @@ import com.mongodb.QueryBuilder;
|
||||
public class QueryMapperUnitTests {
|
||||
|
||||
QueryMapper mapper;
|
||||
MongoMappingContext context;
|
||||
MongoMappingContext context;
|
||||
|
||||
@Mock
|
||||
MongoDbFactory factory;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
|
||||
context = new MongoMappingContext();
|
||||
|
||||
|
||||
MappingMongoConverter converter = new MappingMongoConverter(factory, context);
|
||||
converter.afterPropertiesSet();
|
||||
|
||||
|
||||
mapper = new QueryMapper(converter);
|
||||
}
|
||||
|
||||
@@ -86,39 +86,39 @@ public class QueryMapperUnitTests {
|
||||
DBObject result = mapper.getMappedObject(query, null);
|
||||
assertThat(result.get("_id"), is(ObjectId.class));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void handlesBigIntegerIdsCorrectly() {
|
||||
|
||||
|
||||
DBObject dbObject = new BasicDBObject("id", new BigInteger("1"));
|
||||
DBObject result = mapper.getMappedObject(dbObject, null);
|
||||
assertThat(result.get("_id"), is((Object) "1"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void handlesObjectIdCapableBigIntegerIdsCorrectly() {
|
||||
|
||||
|
||||
ObjectId id = new ObjectId();
|
||||
DBObject dbObject = new BasicDBObject("id", new BigInteger(id.toString(), 16));
|
||||
DBObject result = mapper.getMappedObject(dbObject, null);
|
||||
assertThat(result.get("_id"), is((Object) id));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-278
|
||||
*/
|
||||
@Test
|
||||
public void translates$NeCorrectly() {
|
||||
|
||||
|
||||
Criteria criteria = where("foo").ne(new ObjectId().toString());
|
||||
|
||||
|
||||
DBObject result = mapper.getMappedObject(criteria.getCriteriaObject(), context.getPersistentEntity(Sample.class));
|
||||
Object object = result.get("_id");
|
||||
assertThat(object, is(DBObject.class));
|
||||
DBObject dbObject = (DBObject) object;
|
||||
assertThat(dbObject.get("$ne"), is(ObjectId.class));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-326
|
||||
*/
|
||||
@@ -126,11 +126,10 @@ public class QueryMapperUnitTests {
|
||||
public void handlesEnumsCorrectly() {
|
||||
Query query = query(where("foo").is(Enum.INSTANCE));
|
||||
DBObject result = mapper.getMappedObject(query.getQueryObject(), null);
|
||||
|
||||
|
||||
Object object = result.get("foo");
|
||||
assertThat(object, is(String.class));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void handlesEnumsInNotEqualCorrectly() {
|
||||
|
||||
@@ -48,7 +48,8 @@ public class QueryTests {
|
||||
|
||||
@Test
|
||||
public void testOrQuery() {
|
||||
Query q = new Query(new Criteria().orOperator(where("name").is("Sven").and("age").lt(50), where("age").lt(50), where("name").is("Thomas")));
|
||||
Query q = new Query(new Criteria().orOperator(where("name").is("Sven").and("age").lt(50), where("age").lt(50),
|
||||
where("name").is("Thomas")));
|
||||
String expected = "{ \"$or\" : [ { \"name\" : \"Sven\" , \"age\" : { \"$lt\" : 50}} , { \"age\" : { \"$lt\" : 50}} , { \"name\" : \"Thomas\"}]}";
|
||||
Assert.assertEquals(expected, q.getQueryObject().toString());
|
||||
}
|
||||
@@ -62,7 +63,8 @@ public class QueryTests {
|
||||
|
||||
@Test
|
||||
public void testNorQuery() {
|
||||
Query q = new Query(new Criteria().norOperator(where("name").is("Sven"), where("age").lt(50), where("name").is("Thomas")));
|
||||
Query q = new Query(new Criteria().norOperator(where("name").is("Sven"), where("age").lt(50),
|
||||
where("name").is("Thomas")));
|
||||
String expected = "{ \"$nor\" : [ { \"name\" : \"Sven\"} , { \"age\" : { \"$lt\" : 50}} , { \"name\" : \"Thomas\"}]}";
|
||||
Assert.assertEquals(expected, q.getQueryObject().toString());
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ public class SortTests {
|
||||
Sort s = new Sort().on("name", DESCENDING);
|
||||
assertEquals("{ \"name\" : -1}", s.getSortObject().toString());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see DATADOC-177
|
||||
*/
|
||||
|
||||
@@ -31,11 +31,12 @@ public class UpdateTests {
|
||||
Assert.assertEquals("{ \"$set\" : { \"directory\" : \"/Users/Test/Desktop\"}}", u.getUpdateObject().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetSet() {
|
||||
Update u = new Update().set("directory", "/Users/Test/Desktop").set("size", 0);
|
||||
Assert.assertEquals("{ \"$set\" : { \"directory\" : \"/Users/Test/Desktop\" , \"size\" : 0}}", u.getUpdateObject().toString());
|
||||
}
|
||||
@Test
|
||||
public void testSetSet() {
|
||||
Update u = new Update().set("directory", "/Users/Test/Desktop").set("size", 0);
|
||||
Assert.assertEquals("{ \"$set\" : { \"directory\" : \"/Users/Test/Desktop\" , \"size\" : 0}}", u.getUpdateObject()
|
||||
.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInc() {
|
||||
@@ -43,11 +44,11 @@ public class UpdateTests {
|
||||
Assert.assertEquals("{ \"$inc\" : { \"size\" : 1}}", u.getUpdateObject().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIncInc() {
|
||||
Update u = new Update().inc("size", 1).inc("count", 1);
|
||||
Assert.assertEquals("{ \"$inc\" : { \"size\" : 1 , \"count\" : 1}}", u.getUpdateObject().toString());
|
||||
}
|
||||
@Test
|
||||
public void testIncInc() {
|
||||
Update u = new Update().inc("size", 1).inc("count", 1);
|
||||
Assert.assertEquals("{ \"$inc\" : { \"size\" : 1 , \"count\" : 1}}", u.getUpdateObject().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIncAndSet() {
|
||||
|
||||
@@ -266,7 +266,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void findsPeopleByLocationWithinPolygon() {
|
||||
|
||||
|
||||
Point point = new Point(-73.99171, 40.738868);
|
||||
dave.setLocation(point);
|
||||
repository.save(dave);
|
||||
@@ -371,9 +371,9 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
|
||||
*/
|
||||
@Test
|
||||
public void considersSortForAnnotatedQuery() {
|
||||
|
||||
|
||||
List<Person> result = repository.findByAgeLessThan(60, new Sort("firstname"));
|
||||
|
||||
|
||||
assertThat(result.size(), is(7));
|
||||
assertThat(result.get(0), is(alicia));
|
||||
assertThat(result.get(1), is(boyd));
|
||||
|
||||
@@ -50,8 +50,7 @@ public class Address {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param street
|
||||
* the street to set
|
||||
* @param street the street to set
|
||||
*/
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
@@ -65,8 +64,7 @@ public class Address {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param zipCode
|
||||
* the zipCode to set
|
||||
* @param zipCode the zipCode to set
|
||||
*/
|
||||
public void setZipCode(String zipCode) {
|
||||
this.zipCode = zipCode;
|
||||
@@ -80,8 +78,7 @@ public class Address {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param city
|
||||
* the city to set
|
||||
* @param city the city to set
|
||||
*/
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
|
||||
@@ -21,7 +21,7 @@ import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
/**
|
||||
* Sample contactt domain class.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@Document
|
||||
|
||||
@@ -33,7 +33,7 @@ public class Person extends Contact {
|
||||
public enum Sex {
|
||||
MALE, FEMALE;
|
||||
}
|
||||
|
||||
|
||||
private String firstname;
|
||||
private String lastname;
|
||||
@Indexed(unique = true, dropDups = true)
|
||||
@@ -62,9 +62,9 @@ public class Person extends Contact {
|
||||
|
||||
this(firstname, lastname, age, Sex.MALE);
|
||||
}
|
||||
|
||||
|
||||
public Person(String firstname, String lastname, Integer age, Sex sex) {
|
||||
|
||||
|
||||
super();
|
||||
this.firstname = firstname;
|
||||
this.lastname = lastname;
|
||||
@@ -82,8 +82,7 @@ public class Person extends Contact {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param firstname
|
||||
* the firstname to set
|
||||
* @param firstname the firstname to set
|
||||
*/
|
||||
public void setFirstname(String firstname) {
|
||||
|
||||
@@ -99,8 +98,7 @@ public class Person extends Contact {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param lastname
|
||||
* the lastname to set
|
||||
* @param lastname the lastname to set
|
||||
*/
|
||||
public void setLastname(String lastname) {
|
||||
|
||||
@@ -113,14 +111,14 @@ public class Person extends Contact {
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param email the email to set
|
||||
*/
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return the age
|
||||
*/
|
||||
@@ -130,8 +128,7 @@ public class Person extends Contact {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param age
|
||||
* the age to set
|
||||
* @param age the age to set
|
||||
*/
|
||||
public void setAge(Integer age) {
|
||||
|
||||
@@ -146,8 +143,7 @@ public class Person extends Contact {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param location
|
||||
* the location to set
|
||||
* @param location the location to set
|
||||
*/
|
||||
public void setLocation(Point location) {
|
||||
this.location = location;
|
||||
@@ -161,8 +157,7 @@ public class Person extends Contact {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param address
|
||||
* the address to set
|
||||
* @param address the address to set
|
||||
*/
|
||||
public void setAddress(Address address) {
|
||||
this.address = address;
|
||||
@@ -176,8 +171,7 @@ public class Person extends Contact {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param addresses
|
||||
* the addresses to set
|
||||
* @param addresses the addresses to set
|
||||
*/
|
||||
public void setShippingAddresses(Set<Address> addresses) {
|
||||
this.shippingAddresses = addresses;
|
||||
|
||||
@@ -44,7 +44,7 @@ public interface PersonRepository extends MongoRepository<Person, String>, Query
|
||||
* @return
|
||||
*/
|
||||
List<Person> findByLastname(String lastname);
|
||||
|
||||
|
||||
/**
|
||||
* Returns all {@link Person}s with the given lastname ordered by their firstname.
|
||||
*
|
||||
@@ -70,9 +70,9 @@ public interface PersonRepository extends MongoRepository<Person, String>, Query
|
||||
* @return
|
||||
*/
|
||||
List<Person> findByFirstnameLike(String firstname);
|
||||
|
||||
|
||||
List<Person> findByFirstnameLikeOrderByLastnameAsc(String firstname, Sort sort);
|
||||
|
||||
|
||||
@Query("{'age' : { '$lt' : ?0 } }")
|
||||
List<Person> findByAgeLessThan(int age, Sort sort);
|
||||
|
||||
@@ -87,7 +87,7 @@ public interface PersonRepository extends MongoRepository<Person, String>, Query
|
||||
|
||||
@Query("{ 'lastname' : { '$regex' : ?0, '$options' : ''}}")
|
||||
Page<Person> findByLastnameLikeWithPageable(String lastname, Pageable pageable);
|
||||
|
||||
|
||||
/**
|
||||
* Returns all {@link Person}s with a firstname contained in the given varargs.
|
||||
*
|
||||
@@ -140,12 +140,12 @@ public interface PersonRepository extends MongoRepository<Person, String>, Query
|
||||
List<Person> findByLocationWithin(Circle circle);
|
||||
|
||||
List<Person> findByLocationWithin(Box box);
|
||||
|
||||
|
||||
List<Person> findByLocationWithin(Polygon polygon);
|
||||
|
||||
|
||||
List<Person> findBySex(Sex sex);
|
||||
|
||||
|
||||
List<Person> findByNamedQuery(String firstname);
|
||||
|
||||
|
||||
GeoResults<Person> findByLocationNear(Point point, Distance maxDistance);
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ public class MongoNamespaceIntegrationTests extends AbstractPersonRepositoryInte
|
||||
|
||||
DefaultListableBeanFactory factory;
|
||||
BeanDefinitionReader reader;
|
||||
|
||||
|
||||
@Before
|
||||
@Override
|
||||
public void setUp() {
|
||||
@@ -31,12 +31,11 @@ public class MongoNamespaceIntegrationTests extends AbstractPersonRepositoryInte
|
||||
factory = new DefaultListableBeanFactory();
|
||||
reader = new XmlBeanDefinitionReader(factory);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void assertDefaultMappingContextIsWired() {
|
||||
|
||||
reader.loadBeanDefinitions(new ClassPathResource("MongoNamespaceIntegrationTests-context.xml",
|
||||
getClass()));
|
||||
reader.loadBeanDefinitions(new ClassPathResource("MongoNamespaceIntegrationTests-context.xml", getClass()));
|
||||
BeanDefinition definition = factory.getBeanDefinition("personRepository");
|
||||
assertThat(definition, is(notNullValue()));
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ import com.mongodb.BasicDBList;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link ConvertingParameterAccessor}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
@@ -43,37 +43,37 @@ public class ConvertingParameterAccessorUnitTests {
|
||||
MongoDbFactory factory;
|
||||
@Mock
|
||||
MongoParameterAccessor accessor;
|
||||
|
||||
|
||||
MongoMappingContext context;
|
||||
MappingMongoConverter converter;
|
||||
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
context = new MongoMappingContext();
|
||||
converter = new MappingMongoConverter(factory, context);
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullWriter() {
|
||||
new MappingMongoConverter(null, context);
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullContext() {
|
||||
new MappingMongoConverter(factory, null);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void convertsCollectionUponAccess() {
|
||||
|
||||
|
||||
when(accessor.getBindableValue(0)).thenReturn(Arrays.asList("Foo"));
|
||||
|
||||
|
||||
ConvertingParameterAccessor parameterAccessor = new ConvertingParameterAccessor(converter, accessor);
|
||||
Object result = parameterAccessor.getBindableValue(0);
|
||||
|
||||
|
||||
BasicDBList reference = new BasicDBList();
|
||||
reference.add("Foo");
|
||||
|
||||
|
||||
assertThat(result, is((Object) reference));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ public class MongoParametersUnitTests {
|
||||
Method method = PersonRepository.class.getMethod("findByLocationNearAndOtherLocation", Point.class, Point.class);
|
||||
new MongoParameters(method, true);
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void rejectsMultipleDoubleArraysForGeoNearMethod() throws Exception {
|
||||
Method method = PersonRepository.class.getMethod("invalidDoubleArrays", double[].class, double[].class);
|
||||
@@ -92,7 +92,7 @@ public class MongoParametersUnitTests {
|
||||
MongoParameters parameters = new MongoParameters(method, true);
|
||||
assertThat(parameters.getNearIndex(), is(1));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void findsAnnotatedDoubleArrayForGeoNearQuery() throws Exception {
|
||||
Method method = PersonRepository.class.getMethod("validDoubleArrays", double[].class, double[].class);
|
||||
@@ -105,13 +105,13 @@ public class MongoParametersUnitTests {
|
||||
List<Person> findByLocationNear(Point point, Distance distance);
|
||||
|
||||
GeoResults<Person> findByLocationNearAndOtherLocation(Point point, Point anotherLocation);
|
||||
|
||||
|
||||
GeoResults<Person> invalidDoubleArrays(double[] first, double[] second);
|
||||
|
||||
List<Person> someOtherMethod(Point first, Point second);
|
||||
|
||||
GeoResults<Person> findByOtherLocationAndLocationNear(Point point, @Near Point anotherLocation);
|
||||
|
||||
|
||||
GeoResults<Person> validDoubleArrays(double[] first, @Near double[] second);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ public class MongoQueryMethodUnitTests {
|
||||
MongoQueryMethod queryMethod = queryMethod("findByLocationNear", Point.class, Distance.class, Pageable.class);
|
||||
assertThat(queryMethod.isGeoNearQuery(), is(true));
|
||||
assertThat(queryMethod.isPageQuery(), is(true));
|
||||
|
||||
|
||||
queryMethod = queryMethod("findByFirstname", String.class, Point.class);
|
||||
assertThat(queryMethod.isGeoNearQuery(), is(true));
|
||||
assertThat(queryMethod.isPageQuery(), is(false));
|
||||
@@ -107,7 +107,7 @@ public class MongoQueryMethodUnitTests {
|
||||
Method method = PersonRepository.class.getMethod("findByFirstname", String.class, Point.class);
|
||||
new MongoQueryMethod(method, new DefaultRepositoryMetadata(PersonRepository.class), null);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void considersMethodReturningGeoPageAsPagingMethod() throws Exception {
|
||||
MongoQueryMethod method = queryMethod("findByLocationNear", Point.class, Distance.class, Pageable.class);
|
||||
|
||||
@@ -106,25 +106,25 @@ public class StringBasedMongoQueryUnitTests {
|
||||
|
||||
@Test
|
||||
public void bindsMultipleParametersCorrectly() throws SecurityException, NoSuchMethodException {
|
||||
|
||||
|
||||
Method method = SampleRepository.class.getMethod("findByLastnameAndAddress", String.class, Address.class);
|
||||
MongoQueryMethod queryMethod = new MongoQueryMethod(method, metadata, creator);
|
||||
StringBasedMongoQuery mongoQuery = new StringBasedMongoQuery(queryMethod, template);
|
||||
|
||||
|
||||
Address address = new Address("Foo", "0123", "Bar");
|
||||
ConvertingParameterAccessor accesor = StubParameterAccessor.getAccessor(converter, "Matthews", address);
|
||||
|
||||
|
||||
DBObject addressDbObject = new BasicDBObject();
|
||||
converter.write(address, addressDbObject);
|
||||
addressDbObject.removeField(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY);
|
||||
|
||||
|
||||
DBObject reference = new BasicDBObject("address", addressDbObject);
|
||||
reference.put("lastname", "Matthews");
|
||||
|
||||
org.springframework.data.mongodb.core.query.Query query = mongoQuery.createQuery(accesor);
|
||||
assertThat(query.getQueryObject(), is(reference));
|
||||
}
|
||||
|
||||
|
||||
private interface SampleRepository {
|
||||
|
||||
@Query("{ 'lastname' : ?0 }")
|
||||
@@ -132,7 +132,7 @@ public class StringBasedMongoQueryUnitTests {
|
||||
|
||||
@Query("{ 'address' : ?0 }")
|
||||
Person findByAddress(Address address);
|
||||
|
||||
|
||||
@Query("{ 'lastname' : ?0, 'address' : ?1 }")
|
||||
Person findByLastnameAndAddress(String lastname, Address address);
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ class StubParameterAccessor implements MongoParameterAccessor {
|
||||
public Sort getSort() {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.mongodb.repository.MongoParameterAccessor#getMaxDistance()
|
||||
|
||||
@@ -33,7 +33,7 @@ import com.mysema.query.mongodb.MongodbQuery;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link QuerydslRepositorySupport}.
|
||||
*
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@@ -43,18 +43,19 @@ public class QuerydslRepositorySupportUnitTests {
|
||||
@Autowired
|
||||
MongoOperations operations;
|
||||
Person person;
|
||||
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
operations.remove(new Query(), Person.class);
|
||||
person = new Person("Dave", "Matthews");
|
||||
operations.save(person);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void providesMongoQuery() {
|
||||
QPerson p = QPerson.person;
|
||||
QuerydslRepositorySupport support = new QuerydslRepositorySupport(operations) {};
|
||||
QuerydslRepositorySupport support = new QuerydslRepositorySupport(operations) {
|
||||
};
|
||||
MongodbQuery<Person> query = support.from(p).where(p.lastname.eq("Matthews"));
|
||||
assertThat(query.uniqueResult(), is(person));
|
||||
}
|
||||
|
||||
@@ -42,51 +42,51 @@ import com.mysema.query.types.path.StringPath;
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class SpringDataMongodbSerializerUnitTests {
|
||||
|
||||
|
||||
@Mock
|
||||
MongoDbFactory dbFactory;
|
||||
MongoConverter converter;
|
||||
SpringDataMongodbSerializer serializer;
|
||||
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
MongoMappingContext context = new MongoMappingContext();
|
||||
converter = new MappingMongoConverter(dbFactory, context);
|
||||
serializer = new QueryDslMongoRepository.SpringDataMongodbSerializer(converter);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void uses_idAsKeyForIdProperty() {
|
||||
|
||||
StringPath path = QPerson.person.id;
|
||||
assertThat(serializer.getKeyForPath(path, path.getMetadata()), is("_id"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void buildsNestedKeyCorrectly() {
|
||||
StringPath path = QPerson.person.address.street;
|
||||
assertThat(serializer.getKeyForPath(path, path.getMetadata()), is("street"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void convertsComplexObjectOnSerializing() {
|
||||
|
||||
|
||||
Address address = new Address();
|
||||
address.street = "Foo";
|
||||
address.zipCode = "01234";
|
||||
|
||||
|
||||
DBObject result = serializer.asDBObject("foo", address);
|
||||
assertThat(result, is(BasicDBObject.class));
|
||||
BasicDBObject dbObject = (BasicDBObject) result;
|
||||
|
||||
|
||||
Object value = dbObject.get("foo");
|
||||
assertThat(value, is(notNullValue()));
|
||||
assertThat(value, is(BasicDBObject.class));
|
||||
|
||||
|
||||
Object reference = converter.convertToMongoType(address);
|
||||
assertThat(value, is(reference));
|
||||
}
|
||||
|
||||
|
||||
class Address {
|
||||
String street;
|
||||
@Field("zip_code")
|
||||
|
||||
Reference in New Issue
Block a user