Minor FindBugs polishing.
- removed obsolete property in MongoTemplate - removed obsolete Exception declaration in MongoOoptionsFactoryBean - use HashMap instead of LinkedHashMap as property in UpdateBuilder - renamed local variable in MongoEntityinformation not to shadow a field - reduced visibility of MongoSynchronization and fixed generics - reduced visibility of MongoDbUtils and make it an abstract non-instantiateable class - eliminate nested if-clause in MongoDbUtils - removed obsolete class FluentDbObject - added serialVersionUID to CannotGetMongoDbConnectionException - created static inner enum for ObjectId-to-String converter - added generics to Portfolio test entity - polished SimpleMongoConverterTests and MvcAnalyticsTest - removed some unnecessary imports and modifiers
This commit is contained in:
@@ -19,6 +19,8 @@ import org.springframework.dao.DataAccessResourceFailureException;
|
|||||||
|
|
||||||
public class CannotGetMongoDbConnectionException extends DataAccessResourceFailureException {
|
public class CannotGetMongoDbConnectionException extends DataAccessResourceFailureException {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = 1172099106475265589L;
|
||||||
|
|
||||||
public CannotGetMongoDbConnectionException(String msg, Throwable cause) {
|
public CannotGetMongoDbConnectionException(String msg, Throwable cause) {
|
||||||
super(msg, cause);
|
super(msg, cause);
|
||||||
}
|
}
|
||||||
@@ -26,5 +28,4 @@ public class CannotGetMongoDbConnectionException extends DataAccessResourceFailu
|
|||||||
public CannotGetMongoDbConnectionException(String msg) {
|
public CannotGetMongoDbConnectionException(String msg) {
|
||||||
super(msg);
|
super(msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
package org.springframework.data.document.mongodb;
|
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import com.mongodb.BasicDBObject;
|
|
||||||
import com.mongodb.DBObject;
|
|
||||||
|
|
||||||
public class FluentDbObject {
|
|
||||||
|
|
||||||
public static DBObject DbObject(Tuple... entries) {
|
|
||||||
BasicDBObject map = new BasicDBObject();
|
|
||||||
|
|
||||||
for (Tuple entry : entries) {
|
|
||||||
map.put(entry.t1, entry.t2);
|
|
||||||
}
|
|
||||||
|
|
||||||
return map;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static Tuple pair(String o1, Object o2) {
|
|
||||||
return new Tuple(o1, o2);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static class Tuple {
|
|
||||||
private String t1;
|
|
||||||
private Object t2;
|
|
||||||
|
|
||||||
public Tuple(String t1, Object t2) {
|
|
||||||
this.t1 = t1;
|
|
||||||
this.t2 = t2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -38,12 +38,20 @@ import com.mongodb.MongoException.Network;
|
|||||||
*
|
*
|
||||||
* @author Thomas Risberg
|
* @author Thomas Risberg
|
||||||
* @author Graeme Rocher
|
* @author Graeme Rocher
|
||||||
|
* @author Oliver Gierke
|
||||||
*
|
*
|
||||||
* @since 1.0
|
* @since 1.0
|
||||||
*/
|
*/
|
||||||
public class MongoDbUtils {
|
abstract class MongoDbUtils {
|
||||||
|
|
||||||
static final Log logger = LogFactory.getLog(MongoDbUtils.class);
|
private static final Log LOGGER = LogFactory.getLog(MongoDbUtils.class);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Private constructor to prevent instantiation.
|
||||||
|
*/
|
||||||
|
private MongoDbUtils() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert the given runtime exception to an appropriate exception from the
|
* Convert the given runtime exception to an appropriate exception from the
|
||||||
@@ -112,7 +120,7 @@ public class MongoDbUtils {
|
|||||||
// Spring transaction management is active ->
|
// Spring transaction management is active ->
|
||||||
db = dbHolder.getDB();
|
db = dbHolder.getDB();
|
||||||
if (db != null && !dbHolder.isSynchronizedWithTransaction()) {
|
if (db != null && !dbHolder.isSynchronizedWithTransaction()) {
|
||||||
logger.debug("Registering Spring transaction synchronization for existing Mongo DB");
|
LOGGER.debug("Registering Spring transaction synchronization for existing Mongo DB");
|
||||||
TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(dbHolder, mongo));
|
TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(dbHolder, mongo));
|
||||||
dbHolder.setSynchronizedWithTransaction(true);
|
dbHolder.setSynchronizedWithTransaction(true);
|
||||||
}
|
}
|
||||||
@@ -122,18 +130,19 @@ public class MongoDbUtils {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.debug("Opening Mongo DB");
|
LOGGER.debug("Opening Mongo DB");
|
||||||
DB db = mongo.getDB(databaseName);
|
DB db = mongo.getDB(databaseName);
|
||||||
if(username != null && password != null) {
|
boolean creadentialsGiven = username != null && password != null;
|
||||||
if(!db.authenticate(username, password)) {
|
|
||||||
throw new CannotGetMongoDbConnectionException("Failed to authenticate with Mongo using the given credentials");
|
if(creadentialsGiven && !db.authenticate(username, password)) {
|
||||||
}
|
throw new CannotGetMongoDbConnectionException("Failed to authenticate with Mongo using the given credentials");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use same Session for further Mongo actions within the transaction.
|
// Use same Session for further Mongo actions within the transaction.
|
||||||
// Thread object will get removed by synchronization at transaction completion.
|
// Thread object will get removed by synchronization at transaction completion.
|
||||||
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||||
// We're within a Spring-managed transaction, possibly from JtaTransactionManager.
|
// We're within a Spring-managed transaction, possibly from JtaTransactionManager.
|
||||||
logger.debug("Registering Spring transaction synchronization for new Hibernate Session");
|
LOGGER.debug("Registering Spring transaction synchronization for new Hibernate Session");
|
||||||
DBHolder holderToUse = dbHolder;
|
DBHolder holderToUse = dbHolder;
|
||||||
if (holderToUse == null) {
|
if (holderToUse == null) {
|
||||||
holderToUse = new DBHolder(db);
|
holderToUse = new DBHolder(db);
|
||||||
@@ -182,12 +191,12 @@ public class MongoDbUtils {
|
|||||||
*/
|
*/
|
||||||
public static void closeDB(DB db) {
|
public static void closeDB(DB db) {
|
||||||
if (db != null) {
|
if (db != null) {
|
||||||
logger.debug("Closing Mongo DB object");
|
LOGGER.debug("Closing Mongo DB object");
|
||||||
try {
|
try {
|
||||||
db.requestDone();
|
db.requestDone();
|
||||||
}
|
}
|
||||||
catch (Throwable ex) {
|
catch (Throwable ex) {
|
||||||
logger.debug("Unexpected exception on closing Mongo DB object", ex);
|
LOGGER.debug("Unexpected exception on closing Mongo DB object", ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ public class MongoOptionsFactoryBean implements FactoryBean<MongoOptions>, Initi
|
|||||||
this.autoConnectRetry = autoConnectRetry;
|
this.autoConnectRetry = autoConnectRetry;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void afterPropertiesSet() throws Exception {
|
public void afterPropertiesSet() {
|
||||||
MONGO_OPTIONS.connectionsPerHost = connectionsPerHost;
|
MONGO_OPTIONS.connectionsPerHost = connectionsPerHost;
|
||||||
MONGO_OPTIONS.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
|
MONGO_OPTIONS.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
|
||||||
MONGO_OPTIONS.maxWaitTime = maxWaitTime;
|
MONGO_OPTIONS.maxWaitTime = maxWaitTime;
|
||||||
@@ -122,7 +122,7 @@ public class MongoOptionsFactoryBean implements FactoryBean<MongoOptions>, Initi
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public MongoOptions getObject() throws Exception {
|
public MongoOptions getObject() {
|
||||||
return MONGO_OPTIONS;
|
return MONGO_OPTIONS;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,14 +2,11 @@ package org.springframework.data.document.mongodb;
|
|||||||
|
|
||||||
import org.springframework.transaction.support.ResourceHolder;
|
import org.springframework.transaction.support.ResourceHolder;
|
||||||
import org.springframework.transaction.support.ResourceHolderSynchronization;
|
import org.springframework.transaction.support.ResourceHolderSynchronization;
|
||||||
import org.springframework.transaction.support.TransactionSynchronization;
|
|
||||||
|
|
||||||
public class MongoSynchronization extends ResourceHolderSynchronization
|
class MongoSynchronization extends ResourceHolderSynchronization<ResourceHolder, Object> {
|
||||||
implements TransactionSynchronization {
|
|
||||||
|
|
||||||
public MongoSynchronization(ResourceHolder resourceHolder,
|
public MongoSynchronization(ResourceHolder resourceHolder,
|
||||||
Object resourceKey) {
|
Object resourceKey) {
|
||||||
super(resourceHolder, resourceKey);
|
super(resourceHolder, resourceKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,14 +59,8 @@ public class MongoTemplate implements InitializingBean, MongoOperations {
|
|||||||
private final Mongo mongo;
|
private final Mongo mongo;
|
||||||
|
|
||||||
private String defaultCollectionName;
|
private String defaultCollectionName;
|
||||||
|
|
||||||
//TODO expose configuration...
|
|
||||||
private CollectionOptions defaultCollectionOptions;
|
|
||||||
|
|
||||||
private String databaseName;
|
private String databaseName;
|
||||||
|
|
||||||
private String username;
|
private String username;
|
||||||
|
|
||||||
private String password;
|
private String password;
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import java.util.HashSet;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@@ -118,11 +119,7 @@ public class SimpleMongoConverter implements MongoConverter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected void initializeConverters() {
|
protected void initializeConverters() {
|
||||||
conversionService.addConverter(new Converter<ObjectId, String>() {
|
conversionService.addConverter(ObjectIdToStringConverter.INSTANCE);
|
||||||
public String convert(ObjectId id) {
|
|
||||||
return id.toString();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -158,8 +155,8 @@ public class SimpleMongoConverter implements MongoConverter {
|
|||||||
}
|
}
|
||||||
else if (value != null && "_id".equals(keyToUse) && String.class.isAssignableFrom(pd.getPropertyType())) {
|
else if (value != null && "_id".equals(keyToUse) && String.class.isAssignableFrom(pd.getPropertyType())) {
|
||||||
try {
|
try {
|
||||||
ObjectId _id = new ObjectId((String)value);
|
ObjectId id = new ObjectId((String)value);
|
||||||
writeValue(dbo, keyToUse, _id);
|
writeValue(dbo, keyToUse, id);
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException iae) {
|
catch (IllegalArgumentException iae) {
|
||||||
logger.debug("Unable to convert the String " + value
|
logger.debug("Unable to convert the String " + value
|
||||||
@@ -295,7 +292,7 @@ public class SimpleMongoConverter implements MongoConverter {
|
|||||||
int i = 0;
|
int i = 0;
|
||||||
for (Object o : (Object[])value) {
|
for (Object o : (Object[])value) {
|
||||||
if (o instanceof DBObject) {
|
if (o instanceof DBObject) {
|
||||||
Class type;
|
Class<?> type;
|
||||||
if (pd.getPropertyType().isArray()) {
|
if (pd.getPropertyType().isArray()) {
|
||||||
type = pd.getPropertyType().getComponentType();
|
type = pd.getPropertyType().getComponentType();
|
||||||
}
|
}
|
||||||
@@ -334,7 +331,7 @@ public class SimpleMongoConverter implements MongoConverter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Object readCompoundValue(PropertyDescriptor pd, DBObject dbo) {
|
private Object readCompoundValue(PropertyDescriptor pd, DBObject dbo) {
|
||||||
Class propertyClazz = pd.getPropertyType();
|
Class<?> propertyClazz = pd.getPropertyType();
|
||||||
if (Map.class.isAssignableFrom(propertyClazz)) {
|
if (Map.class.isAssignableFrom(propertyClazz)) {
|
||||||
//TODO assure is assignable to BasicDBObject
|
//TODO assure is assignable to BasicDBObject
|
||||||
return readMap(pd, (BasicDBObject)dbo, getGenericParameterClass(pd.getWriteMethod()).get(1) );
|
return readMap(pd, (BasicDBObject)dbo, getGenericParameterClass(pd.getWriteMethod()).get(1) );
|
||||||
@@ -346,24 +343,23 @@ public class SimpleMongoConverter implements MongoConverter {
|
|||||||
return read(propertyClazz, dbo);
|
return read(propertyClazz, dbo);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Map createMap() {
|
protected Map<String, Object> createMap() {
|
||||||
return new HashMap();
|
return new HashMap<String, Object>();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Map readMap(PropertyDescriptor pd, BasicDBObject dbo, Class valueClazz) {
|
protected Map<?, ?> readMap(PropertyDescriptor pd, BasicDBObject dbo, Class<?> valueClazz) {
|
||||||
Class propertyClazz = pd.getPropertyType();
|
Map<String, Object> map = createMap();
|
||||||
Map map = createMap();
|
for (Entry<String, Object> entry : dbo.entrySet()) {
|
||||||
for (Map.Entry entry : dbo.entrySet()) {
|
|
||||||
Object entryValue = entry.getValue();
|
Object entryValue = entry.getValue();
|
||||||
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(entryValue);
|
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(entryValue);
|
||||||
initBeanWrapper(bw);
|
initBeanWrapper(bw);
|
||||||
|
|
||||||
if (!isSimpleType(entryValue.getClass())) {
|
if (!isSimpleType(entryValue.getClass())) {
|
||||||
map.put((String)entry.getKey(), read(valueClazz, (DBObject) entryValue));
|
map.put(entry.getKey(), read(valueClazz, (DBObject) entryValue));
|
||||||
//Can do some reflection tricks here -
|
//Can do some reflection tricks here -
|
||||||
//throw new RuntimeException("User types not supported yet as values for Maps");
|
//throw new RuntimeException("User types not supported yet as values for Maps");
|
||||||
} else {
|
} else {
|
||||||
map.put((String)entry.getKey(), entryValue );
|
map.put(entry.getKey(), entryValue );
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
@@ -390,9 +386,10 @@ public class SimpleMongoConverter implements MongoConverter {
|
|||||||
descriptor.getWriteMethod() != null);
|
descriptor.getWriteMethod() != null);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected boolean isSimpleType(Class propertyType) {
|
protected boolean isSimpleType(Class<?> propertyType) {
|
||||||
if (propertyType == null)
|
if (propertyType == null) {
|
||||||
return false;
|
return false;
|
||||||
|
}
|
||||||
if (propertyType.isArray()) {
|
if (propertyType.isArray()) {
|
||||||
return isSimpleType(propertyType.getComponentType());
|
return isSimpleType(propertyType.getComponentType());
|
||||||
}
|
}
|
||||||
@@ -404,8 +401,14 @@ public class SimpleMongoConverter implements MongoConverter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public List<Class> getGenericParameterClass(Method setMethod) {
|
/**
|
||||||
List<Class> actualGenericParameterTypes = new ArrayList<Class>();
|
* TODO - should that be factored out into a utility class?
|
||||||
|
*
|
||||||
|
* @param setMethod
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public List<Class<?>> getGenericParameterClass(Method setMethod) {
|
||||||
|
List<Class<?>> actualGenericParameterTypes = new ArrayList<Class<?>>();
|
||||||
Type[] genericParameterTypes = setMethod.getGenericParameterTypes();
|
Type[] genericParameterTypes = setMethod.getGenericParameterTypes();
|
||||||
|
|
||||||
for(Type genericParameterType : genericParameterTypes){
|
for(Type genericParameterType : genericParameterTypes){
|
||||||
@@ -415,19 +418,19 @@ public class SimpleMongoConverter implements MongoConverter {
|
|||||||
for(Type parameterArgType : parameterArgTypes){
|
for(Type parameterArgType : parameterArgTypes){
|
||||||
if (parameterArgType instanceof GenericArrayType)
|
if (parameterArgType instanceof GenericArrayType)
|
||||||
{
|
{
|
||||||
Class arrayType = (Class) ((GenericArrayType) parameterArgType).getGenericComponentType();
|
Class<?> arrayType = (Class<?>) ((GenericArrayType) parameterArgType).getGenericComponentType();
|
||||||
actualGenericParameterTypes.add(Array.newInstance(arrayType, 0).getClass());
|
actualGenericParameterTypes.add(Array.newInstance(arrayType, 0).getClass());
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
if (parameterArgType instanceof ParameterizedType) {
|
if (parameterArgType instanceof ParameterizedType) {
|
||||||
ParameterizedType paramTypeArgs = (ParameterizedType) parameterArgType;
|
ParameterizedType paramTypeArgs = (ParameterizedType) parameterArgType;
|
||||||
actualGenericParameterTypes.add((Class)paramTypeArgs.getRawType());
|
actualGenericParameterTypes.add((Class<?>)paramTypeArgs.getRawType());
|
||||||
} else {
|
} else {
|
||||||
if (parameterArgType instanceof TypeVariable) {
|
if (parameterArgType instanceof TypeVariable) {
|
||||||
throw new RuntimeException("Can not map " + ((TypeVariable) parameterArgType).getName());
|
throw new RuntimeException("Can not map " + ((TypeVariable<?>) parameterArgType).getName());
|
||||||
} else {
|
} else {
|
||||||
if (parameterArgType instanceof Class) {
|
if (parameterArgType instanceof Class) {
|
||||||
actualGenericParameterTypes.add((Class) parameterArgType);
|
actualGenericParameterTypes.add((Class<?>) parameterArgType);
|
||||||
} else {
|
} else {
|
||||||
throw new RuntimeException("Can not map " + parameterArgType);
|
throw new RuntimeException("Can not map " + parameterArgType);
|
||||||
}
|
}
|
||||||
@@ -442,4 +445,22 @@ public class SimpleMongoConverter implements MongoConverter {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simple singleton to convert {@link ObjectId}s to their {@link String} representation.
|
||||||
|
*
|
||||||
|
* @author Oliver Gierke
|
||||||
|
*/
|
||||||
|
private static enum ObjectIdToStringConverter implements Converter<ObjectId, String> {
|
||||||
|
|
||||||
|
INSTANCE;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* (non-Javadoc)
|
||||||
|
*
|
||||||
|
* @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object)
|
||||||
|
*/
|
||||||
|
public String convert(ObjectId id) {
|
||||||
|
return id.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@
|
|||||||
package org.springframework.data.document.mongodb;
|
package org.springframework.data.document.mongodb;
|
||||||
|
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
|
|
||||||
import com.mongodb.BasicDBObject;
|
import com.mongodb.BasicDBObject;
|
||||||
@@ -27,7 +28,7 @@ public class UpdateBuilder {
|
|||||||
LAST, FIRST
|
LAST, FIRST
|
||||||
}
|
}
|
||||||
|
|
||||||
private LinkedHashMap<String, Object> criteria = new LinkedHashMap<String, Object>();
|
private HashMap<String, Object> criteria = new LinkedHashMap<String, Object>();
|
||||||
|
|
||||||
public UpdateBuilder set(String key, Object value) {
|
public UpdateBuilder set(String key, Object value) {
|
||||||
criteria.put("$set", Collections.singletonMap(key, value));
|
criteria.put("$set", Collections.singletonMap(key, value));
|
||||||
|
|||||||
@@ -45,11 +45,11 @@ class MongoEntityInformation implements IsNewAware, IdAware {
|
|||||||
|
|
||||||
for (String name : FIELD_NAMES) {
|
for (String name : FIELD_NAMES) {
|
||||||
|
|
||||||
Field field = ReflectionUtils.findField(domainClass, name);
|
Field candidate = ReflectionUtils.findField(domainClass, name);
|
||||||
|
|
||||||
if (field != null) {
|
if (candidate != null) {
|
||||||
ReflectionUtils.makeAccessible(field);
|
ReflectionUtils.makeAccessible(candidate);
|
||||||
this.field = field;
|
this.field = candidate;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,11 +18,10 @@ package org.springframework.data.document.mongodb.repository;
|
|||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||||
import org.springframework.data.repository.Repository;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mongo specific {@link Repository} interface.
|
* Mongo specific {@link org.springframework.data.repository.Repository} interface.
|
||||||
*
|
*
|
||||||
* @author Oliver Gierke
|
* @author Oliver Gierke
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ package org.springframework.data.document.mongodb.repository;
|
|||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
|
|
||||||
import org.springframework.beans.factory.FactoryBean;
|
|
||||||
import org.springframework.data.document.mongodb.MongoOperations;
|
import org.springframework.data.document.mongodb.MongoOperations;
|
||||||
import org.springframework.data.repository.Repository;
|
import org.springframework.data.repository.Repository;
|
||||||
import org.springframework.data.repository.query.QueryLookupStrategy;
|
import org.springframework.data.repository.query.QueryLookupStrategy;
|
||||||
@@ -32,7 +31,7 @@ import org.springframework.util.Assert;
|
|||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@link FactoryBean} to create {@link MongoRepository} instances.
|
* {@link org.springframework.beans.factory.FactoryBean} to create {@link MongoRepository} instances.
|
||||||
*
|
*
|
||||||
* @author Oliver Gierke
|
* @author Oliver Gierke
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package org.springframework.data.document.mongodb.repository.config;
|
package org.springframework.data.document.mongodb.repository.config;
|
||||||
|
|
||||||
import org.springframework.data.document.mongodb.MongoTemplate;
|
|
||||||
import org.springframework.data.document.mongodb.repository.MongoRepository;
|
import org.springframework.data.document.mongodb.repository.MongoRepository;
|
||||||
import org.springframework.data.document.mongodb.repository.MongoRepositoryFactoryBean;
|
import org.springframework.data.document.mongodb.repository.MongoRepositoryFactoryBean;
|
||||||
import org.springframework.data.repository.config.AutomaticRepositoryConfigInformation;
|
import org.springframework.data.repository.config.AutomaticRepositoryConfigInformation;
|
||||||
@@ -40,7 +39,7 @@ public class SimpleMongoRepositoryConfiguration
|
|||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the bean name of the {@link MongoTemplate} to be referenced.
|
* Returns the bean name of the {@link org.springframework.data.document.mongodb.MongoTemplate} to be referenced.
|
||||||
*
|
*
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
@@ -97,7 +96,7 @@ public class SimpleMongoRepositoryConfiguration
|
|||||||
*
|
*
|
||||||
* @author Oliver Gierke
|
* @author Oliver Gierke
|
||||||
*/
|
*/
|
||||||
public static interface MongoRepositoryConfiguration
|
public interface MongoRepositoryConfiguration
|
||||||
extends
|
extends
|
||||||
SingleRepositoryConfigInformation<SimpleMongoRepositoryConfiguration> {
|
SingleRepositoryConfigInformation<SimpleMongoRepositoryConfiguration> {
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ public class Portfolio {
|
|||||||
|
|
||||||
private String portfolioName;
|
private String portfolioName;
|
||||||
private User user;
|
private User user;
|
||||||
private List trades;
|
private List<Trade> trades;
|
||||||
private Map<String, Integer> positions;
|
private Map<String, Integer> positions;
|
||||||
private Map<String, Person> portfolioManagers;
|
private Map<String, Person> portfolioManagers;
|
||||||
|
|
||||||
@@ -40,7 +40,7 @@ public class Portfolio {
|
|||||||
this.positions = positions;
|
this.positions = positions;
|
||||||
}
|
}
|
||||||
public Portfolio() {
|
public Portfolio() {
|
||||||
trades = new ArrayList();
|
trades = new ArrayList<Trade>();
|
||||||
}
|
}
|
||||||
public String getPortfolioName() {
|
public String getPortfolioName() {
|
||||||
return portfolioName;
|
return portfolioName;
|
||||||
@@ -48,10 +48,10 @@ public class Portfolio {
|
|||||||
public void setPortfolioName(String portfolioName) {
|
public void setPortfolioName(String portfolioName) {
|
||||||
this.portfolioName = portfolioName;
|
this.portfolioName = portfolioName;
|
||||||
}
|
}
|
||||||
public List getTrades() {
|
public List<Trade> getTrades() {
|
||||||
return trades;
|
return trades;
|
||||||
}
|
}
|
||||||
public void setTrades(List trades) {
|
public void setTrades(List<Trade> trades) {
|
||||||
this.trades = trades;
|
this.trades = trades;
|
||||||
}
|
}
|
||||||
public User getUser() {
|
public User getUser() {
|
||||||
@@ -60,7 +60,4 @@ public class Portfolio {
|
|||||||
public void setUser(User user) {
|
public void setUser(User user) {
|
||||||
this.user = user;
|
this.user = user;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,21 +15,17 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.data.document.mongodb;
|
package org.springframework.data.document.mongodb;
|
||||||
|
|
||||||
import java.lang.reflect.Array;
|
import static org.hamcrest.CoreMatchers.*;
|
||||||
import java.lang.reflect.GenericArrayType;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.lang.reflect.ParameterizedType;
|
|
||||||
import java.lang.reflect.Type;
|
|
||||||
import java.lang.reflect.TypeVariable;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.springframework.data.document.mongodb.SimpleMongoConverter;
|
|
||||||
import org.springframework.data.document.mongodb.SomeEnumTest.NumberEnum;
|
import org.springframework.data.document.mongodb.SomeEnumTest.NumberEnum;
|
||||||
import org.springframework.data.document.mongodb.SomeEnumTest.StringEnum;
|
import org.springframework.data.document.mongodb.SomeEnumTest.StringEnum;
|
||||||
import org.springframework.util.ReflectionUtils;
|
import org.springframework.util.ReflectionUtils;
|
||||||
@@ -38,66 +34,65 @@ import com.mongodb.BasicDBObject;
|
|||||||
import com.mongodb.DBObject;
|
import com.mongodb.DBObject;
|
||||||
|
|
||||||
public class SimpleMongoConverterTests {
|
public class SimpleMongoConverterTests {
|
||||||
|
|
||||||
|
SimpleMongoConverter converter;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() {
|
||||||
|
converter = new SimpleMongoConverter();
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void notNestedObject() {
|
public void notNestedObject() {
|
||||||
User user = new User();
|
User user = new User();
|
||||||
user.setAccountName("My Account");
|
user.setAccountName("My Account");
|
||||||
user.setUserName("Mark");
|
user.setUserName("Mark");
|
||||||
SimpleMongoConverter converter = createConverter();
|
|
||||||
DBObject dbo = new BasicDBObject();
|
DBObject dbo = new BasicDBObject();
|
||||||
converter.write(user, dbo);
|
converter.write(user, dbo);
|
||||||
Assert.assertEquals("My Account", dbo.get("accountName"));
|
assertEquals("My Account", dbo.get("accountName"));
|
||||||
Assert.assertEquals("Mark", dbo.get("userName"));
|
assertEquals("Mark", dbo.get("userName"));
|
||||||
|
|
||||||
User u = (User) converter.read(User.class, dbo);
|
User u = (User) converter.read(User.class, dbo);
|
||||||
|
|
||||||
Assert.assertEquals("My Account", u.getAccountName());
|
assertEquals("My Account", u.getAccountName());
|
||||||
Assert.assertEquals("Mark", u.getUserName());
|
assertEquals("Mark", u.getUserName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void nestedObject() {
|
public void nestedObject() {
|
||||||
Portfolio p = createPortfolioWithNoTrades();
|
Portfolio p = createPortfolioWithNoTrades();
|
||||||
SimpleMongoConverter converter = createConverter();
|
|
||||||
DBObject dbo = new BasicDBObject();
|
DBObject dbo = new BasicDBObject();
|
||||||
converter.write(p, dbo);
|
converter.write(p, dbo);
|
||||||
Assert.assertEquals("High Risk Trading Account",
|
|
||||||
dbo.get("portfolioName"));
|
assertEquals("High Risk Trading Account", dbo.get("portfolioName"));
|
||||||
Assert.assertTrue(dbo.containsField("user"));
|
assertTrue(dbo.containsField("user"));
|
||||||
|
|
||||||
Portfolio cp = (Portfolio) converter.read(Portfolio.class, dbo);
|
Portfolio cp = (Portfolio) converter.read(Portfolio.class, dbo);
|
||||||
Assert.assertEquals("High Risk Trading Account", cp.getPortfolioName());
|
|
||||||
Assert.assertEquals("Joe Trader", cp.getUser().getUserName());
|
assertEquals("High Risk Trading Account", cp.getPortfolioName());
|
||||||
Assert.assertEquals("ACCT-123", cp.getUser().getAccountName());
|
assertEquals("Joe Trader", cp.getUser().getUserName());
|
||||||
|
assertEquals("ACCT-123", cp.getUser().getAccountName());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void objectWithMap() {
|
public void objectWithMap() {
|
||||||
Portfolio p = createPortfolioWithPositions();
|
Portfolio p = createPortfolioWithPositions();
|
||||||
SimpleMongoConverter converter = createConverter();
|
|
||||||
DBObject dbo = new BasicDBObject();
|
DBObject dbo = new BasicDBObject();
|
||||||
converter.write(p, dbo);
|
converter.write(p, dbo);
|
||||||
|
|
||||||
Portfolio cp = (Portfolio) converter.read(Portfolio.class, dbo);
|
Portfolio cp = (Portfolio) converter.read(Portfolio.class, dbo);
|
||||||
Assert.assertEquals("High Risk Trading Account", cp.getPortfolioName());
|
assertEquals("High Risk Trading Account", cp.getPortfolioName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void objectWithMapContainingNonPrimitiveTypeAsValue() {
|
public void objectWithMapContainingNonPrimitiveTypeAsValue() {
|
||||||
Portfolio p = createPortfolioWithManagers();
|
Portfolio p = createPortfolioWithManagers();
|
||||||
SimpleMongoConverter converter = createConverter();
|
|
||||||
DBObject dbo = new BasicDBObject();
|
DBObject dbo = new BasicDBObject();
|
||||||
converter.write(p, dbo);
|
converter.write(p, dbo);
|
||||||
|
|
||||||
Portfolio cp = (Portfolio) converter.read(Portfolio.class, dbo);
|
Portfolio cp = (Portfolio) converter.read(Portfolio.class, dbo);
|
||||||
Assert.assertEquals("High Risk Trading Account", cp.getPortfolioName());
|
assertEquals("High Risk Trading Account", cp.getPortfolioName());
|
||||||
}
|
|
||||||
|
|
||||||
private SimpleMongoConverter createConverter() {
|
|
||||||
SimpleMongoConverter converter = new SimpleMongoConverter();
|
|
||||||
return converter;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Portfolio createPortfolioWithPositions() {
|
protected Portfolio createPortfolioWithPositions() {
|
||||||
@@ -135,17 +130,16 @@ public class SimpleMongoConverterTests {
|
|||||||
@Test
|
@Test
|
||||||
public void objectWithArrayContainingNonPrimitiveType() {
|
public void objectWithArrayContainingNonPrimitiveType() {
|
||||||
TradeBatch b = createTradeBatch();
|
TradeBatch b = createTradeBatch();
|
||||||
SimpleMongoConverter converter = createConverter();
|
|
||||||
DBObject dbo = new BasicDBObject();
|
DBObject dbo = new BasicDBObject();
|
||||||
converter.write(b, dbo);
|
converter.write(b, dbo);
|
||||||
|
|
||||||
TradeBatch b2 = (TradeBatch) converter.read(TradeBatch.class, dbo);
|
TradeBatch b2 = (TradeBatch) converter.read(TradeBatch.class, dbo);
|
||||||
Assert.assertEquals(b.getBatchId(), b2.getBatchId());
|
assertEquals(b.getBatchId(), b2.getBatchId());
|
||||||
Assert.assertNotNull(b2.getTradeList());
|
assertNotNull(b2.getTradeList());
|
||||||
Assert.assertEquals(b.getTradeList().size(), b2.getTradeList().size());
|
assertEquals(b.getTradeList().size(), b2.getTradeList().size());
|
||||||
Assert.assertEquals(b.getTradeList().get(1).getTicker(), b2.getTradeList().get(1).getTicker());
|
assertEquals(b.getTradeList().get(1).getTicker(), b2.getTradeList().get(1).getTicker());
|
||||||
Assert.assertEquals(b.getTrades().length, b2.getTrades().length);
|
assertEquals(b.getTrades().length, b2.getTrades().length);
|
||||||
Assert.assertEquals(b.getTrades()[1].getTicker(), b2.getTrades()[1].getTicker());
|
assertEquals(b.getTrades()[1].getTicker(), b2.getTrades()[1].getTicker());
|
||||||
}
|
}
|
||||||
|
|
||||||
private TradeBatch createTradeBatch() {
|
private TradeBatch createTradeBatch() {
|
||||||
@@ -173,76 +167,26 @@ public class SimpleMongoConverterTests {
|
|||||||
test.setName("Sven");
|
test.setName("Sven");
|
||||||
test.setStringEnum(StringEnum.ONE);
|
test.setStringEnum(StringEnum.ONE);
|
||||||
test.setNumberEnum(NumberEnum.FIVE);
|
test.setNumberEnum(NumberEnum.FIVE);
|
||||||
SimpleMongoConverter converter = createConverter();
|
|
||||||
DBObject dbo = new BasicDBObject();
|
DBObject dbo = new BasicDBObject();
|
||||||
converter.write(test, dbo);
|
converter.write(test, dbo);
|
||||||
|
|
||||||
SomeEnumTest results = (SomeEnumTest) converter.read(SomeEnumTest.class, dbo);
|
SomeEnumTest results = (SomeEnumTest) converter.read(SomeEnumTest.class, dbo);
|
||||||
Assert.assertNotNull(results);
|
assertNotNull(results);
|
||||||
Assert.assertEquals(test.getId(), results.getId());
|
assertEquals(test.getId(), results.getId());
|
||||||
Assert.assertEquals(test.getName(), results.getName());
|
assertEquals(test.getName(), results.getName());
|
||||||
Assert.assertEquals(test.getStringEnum(), results.getStringEnum());
|
assertEquals(test.getStringEnum(), results.getStringEnum());
|
||||||
Assert.assertEquals(test.getNumberEnum(), results.getNumberEnum());
|
assertEquals(test.getNumberEnum(), results.getNumberEnum());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testReflection() {
|
public void testReflection() {
|
||||||
Portfolio p = createPortfolioWithManagers();
|
|
||||||
Method method = ReflectionUtils.findMethod(Portfolio.class, "setPortfolioManagers", Map.class);
|
Method method = ReflectionUtils.findMethod(Portfolio.class, "setPortfolioManagers", Map.class);
|
||||||
Assert.assertNotNull(method);
|
assertNotNull(method);
|
||||||
List<Class> paramClass = getGenericParameterClass(method);
|
List<Class<?>> paramClass = converter.getGenericParameterClass(method);
|
||||||
System.out.println(paramClass);
|
|
||||||
/*
|
assertThat(paramClass.isEmpty(), is(false));
|
||||||
Type t = method.getGenericReturnType();
|
assertThat(paramClass.size(), is(2));
|
||||||
if (t instanceof ParameterizedType) {
|
assertEquals(String.class, paramClass.get(0));
|
||||||
ParameterizedType pt = (ParameterizedType) t;
|
assertEquals(Person.class, paramClass.get(1));
|
||||||
Type paramType = pt.getActualTypeArguments()[1];
|
|
||||||
if (paramType instanceof ParameterizedType) {
|
|
||||||
ParameterizedType paramPtype = (ParameterizedType) pt;
|
|
||||||
System.out.println(paramPtype.getRawType());
|
|
||||||
}
|
|
||||||
}*/
|
|
||||||
// Assert.assertNotNull(null);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Class> getGenericParameterClass(Method setMethod) {
|
|
||||||
List<Class> actualGenericParameterTypes = new ArrayList<Class>();
|
|
||||||
Type[] genericParameterTypes = setMethod.getGenericParameterTypes();
|
|
||||||
|
|
||||||
for(Type genericParameterType : genericParameterTypes){
|
|
||||||
if(genericParameterType instanceof ParameterizedType){
|
|
||||||
ParameterizedType aType = (ParameterizedType) genericParameterType;
|
|
||||||
Type[] parameterArgTypes = aType.getActualTypeArguments();
|
|
||||||
for(Type parameterArgType : parameterArgTypes){
|
|
||||||
if (parameterArgType instanceof GenericArrayType)
|
|
||||||
{
|
|
||||||
Class arrayType = (Class) ((GenericArrayType) parameterArgType).getGenericComponentType();
|
|
||||||
actualGenericParameterTypes.add(Array.newInstance(arrayType, 0).getClass());
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if (parameterArgType instanceof ParameterizedType) {
|
|
||||||
ParameterizedType paramTypeArgs = (ParameterizedType) parameterArgType;
|
|
||||||
actualGenericParameterTypes.add((Class)paramTypeArgs.getRawType());
|
|
||||||
} else {
|
|
||||||
if (parameterArgType instanceof TypeVariable) {
|
|
||||||
throw new RuntimeException("Can not map " + ((TypeVariable) parameterArgType).getName());
|
|
||||||
} else {
|
|
||||||
if (parameterArgType instanceof Class) {
|
|
||||||
actualGenericParameterTypes.add((Class) parameterArgType);
|
|
||||||
} else {
|
|
||||||
throw new RuntimeException("Can not map " + parameterArgType);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return actualGenericParameterTypes;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,14 +2,10 @@ package org.springframework.data.document.mongodb.analytics;
|
|||||||
|
|
||||||
import java.util.Calendar;
|
import java.util.Calendar;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Iterator;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Ignore;
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.springframework.data.document.analytics.ControllerCounter;
|
import org.springframework.data.document.analytics.ControllerCounter;
|
||||||
import org.springframework.data.document.analytics.MvcEvent;
|
import org.springframework.data.document.analytics.MvcEvent;
|
||||||
@@ -19,7 +15,6 @@ import org.springframework.data.document.mongodb.MongoTemplate;
|
|||||||
|
|
||||||
import com.mongodb.BasicDBList;
|
import com.mongodb.BasicDBList;
|
||||||
import com.mongodb.BasicDBObject;
|
import com.mongodb.BasicDBObject;
|
||||||
import com.mongodb.DB;
|
|
||||||
import com.mongodb.DBCollection;
|
import com.mongodb.DBCollection;
|
||||||
import com.mongodb.DBObject;
|
import com.mongodb.DBObject;
|
||||||
import com.mongodb.Mongo;
|
import com.mongodb.Mongo;
|
||||||
@@ -61,17 +56,17 @@ public class MvcAnalyticsTests {
|
|||||||
MvcEvent.class);
|
MvcEvent.class);
|
||||||
Assert.assertEquals(22, mvcEvents.size());
|
Assert.assertEquals(22, mvcEvents.size());
|
||||||
|
|
||||||
List<MvcEvent> mvcEvents2 = mongoTemplate.getCollection("mvc", MvcEvent.class,
|
mongoTemplate.getCollection("mvc", MvcEvent.class,
|
||||||
new MongoReader<MvcEvent>() {
|
new MongoReader<MvcEvent>() {
|
||||||
public MvcEvent read(Class<? extends MvcEvent> clazz, DBObject dbo) {
|
public MvcEvent read(Class<? extends MvcEvent> clazz, DBObject dbo) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void loadCounterData() {
|
public void loadCounterData() {
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
storeCounterData("SignUpController", "createForm");
|
storeCounterData("SignUpController", "createForm");
|
||||||
storeCounterData("SignUpController", "create");
|
storeCounterData("SignUpController", "create");
|
||||||
@@ -156,12 +151,11 @@ public class MvcAnalyticsTests {
|
|||||||
"function(doc, out){ out.count++; }");
|
"function(doc, out){ out.count++; }");
|
||||||
if (result instanceof BasicDBList) {
|
if (result instanceof BasicDBList) {
|
||||||
BasicDBList dbList = (BasicDBList) result;
|
BasicDBList dbList = (BasicDBList) result;
|
||||||
for (Iterator iterator = dbList.iterator(); iterator.hasNext();) {
|
for (Object element : dbList) {
|
||||||
DBObject dbo = (DBObject) iterator.next();
|
DBObject dbo = (DBObject) element;
|
||||||
System.out.println(dbo);
|
System.out.println(dbo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Map resultMap = result.toMap();
|
|
||||||
System.out.println(result);
|
System.out.println(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -220,16 +214,6 @@ public class MvcAnalyticsTests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private ControllerCounter generateCounter() {
|
|
||||||
ControllerCounter cc = new ControllerCounter();
|
|
||||||
cc.setName("controller2");
|
|
||||||
cc.setCount(0);
|
|
||||||
Map<String, Double> methods = new HashMap<String, Double>();
|
|
||||||
methods.put("find", 1D);
|
|
||||||
cc.setMethods(methods);
|
|
||||||
return cc;
|
|
||||||
}
|
|
||||||
|
|
||||||
private MvcEvent generateEvent(Integer p1) {
|
private MvcEvent generateEvent(Integer p1) {
|
||||||
MvcEvent event = new MvcEvent();
|
MvcEvent event = new MvcEvent();
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user