DATAMONGO-1858 - Fix line endings to LF.

This commit is contained in:
Mark Paluch
2018-01-24 12:57:54 +01:00
parent 2af322a823
commit 72f461ae30
38 changed files with 3489 additions and 3489 deletions

View File

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

View File

@@ -1,297 +1,297 @@
/* /*
* Copyright 2011-2016 the original author or authors. * Copyright 2011-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.config; package org.springframework.data.mongodb.config;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;
import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.data.annotation.Persistent; import org.springframework.data.annotation.Persistent;
import org.springframework.data.authentication.UserCredentials; import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mapping.context.MappingContextIsNewStrategyFactory; import org.springframework.data.mapping.context.MappingContextIsNewStrategyFactory;
import org.springframework.data.mapping.model.CamelCaseAbbreviatingFieldNamingStrategy; import org.springframework.data.mapping.model.CamelCaseAbbreviatingFieldNamingStrategy;
import org.springframework.data.mapping.model.FieldNamingStrategy; import org.springframework.data.mapping.model.FieldNamingStrategy;
import org.springframework.data.mapping.model.PropertyNameFieldNamingStrategy; import org.springframework.data.mapping.model.PropertyNameFieldNamingStrategy;
import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.CustomConversions; import org.springframework.data.mongodb.core.convert.CustomConversions;
import org.springframework.data.mongodb.core.convert.DbRefResolver; import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver; import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext; import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.support.CachingIsNewStrategyFactory; import org.springframework.data.support.CachingIsNewStrategyFactory;
import org.springframework.data.support.IsNewStrategyFactory; import org.springframework.data.support.IsNewStrategyFactory;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import com.mongodb.Mongo; import com.mongodb.Mongo;
import com.mongodb.MongoClient; import com.mongodb.MongoClient;
/** /**
* Base class for Spring Data MongoDB configuration using JavaConfig. * Base class for Spring Data MongoDB configuration using JavaConfig.
* *
* @author Mark Pollack * @author Mark Pollack
* @author Oliver Gierke * @author Oliver Gierke
* @author Thomas Darimont * @author Thomas Darimont
* @author Ryan Tenney * @author Ryan Tenney
* @author Christoph Strobl * @author Christoph Strobl
*/ */
@Configuration @Configuration
public abstract class AbstractMongoConfiguration { public abstract class AbstractMongoConfiguration {
/** /**
* Return the name of the database to connect to. * Return the name of the database to connect to.
* *
* @return must not be {@literal null}. * @return must not be {@literal null}.
*/ */
protected abstract String getDatabaseName(); protected abstract String getDatabaseName();
/** /**
* Return the name of the authentication database to use. Defaults to {@literal null} and will turn into the value * Return the name of the authentication database to use. Defaults to {@literal null} and will turn into the value
* returned by {@link #getDatabaseName()} later on effectively. * returned by {@link #getDatabaseName()} later on effectively.
* *
* @return * @return
* @deprecated since 1.7. {@link MongoClient} should hold authentication data within * @deprecated since 1.7. {@link MongoClient} should hold authentication data within
* {@link MongoClient#getCredentialsList()} * {@link MongoClient#getCredentialsList()}
*/ */
@Deprecated @Deprecated
protected String getAuthenticationDatabaseName() { protected String getAuthenticationDatabaseName() {
return null; return null;
} }
/** /**
* Return the {@link Mongo} instance to connect to. Annotate with {@link Bean} in case you want to expose a * Return the {@link Mongo} instance to connect to. Annotate with {@link Bean} in case you want to expose a
* {@link Mongo} instance to the {@link org.springframework.context.ApplicationContext}. * {@link Mongo} instance to the {@link org.springframework.context.ApplicationContext}.
* *
* @return * @return
* @throws Exception * @throws Exception
*/ */
public abstract Mongo mongo() throws Exception; public abstract Mongo mongo() throws Exception;
/** /**
* Creates a {@link MongoTemplate}. * Creates a {@link MongoTemplate}.
* *
* @return * @return
* @throws Exception * @throws Exception
*/ */
@Bean @Bean
public MongoTemplate mongoTemplate() throws Exception { public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactory(), mappingMongoConverter()); return new MongoTemplate(mongoDbFactory(), mappingMongoConverter());
} }
/** /**
* Creates a {@link SimpleMongoDbFactory} to be used by the {@link MongoTemplate}. Will use the {@link Mongo} instance * Creates a {@link SimpleMongoDbFactory} to be used by the {@link MongoTemplate}. Will use the {@link Mongo} instance
* configured in {@link #mongo()}. * configured in {@link #mongo()}.
* *
* @see #mongo() * @see #mongo()
* @see #mongoTemplate() * @see #mongoTemplate()
* @return * @return
* @throws Exception * @throws Exception
*/ */
@Bean @Bean
public MongoDbFactory mongoDbFactory() throws Exception { public MongoDbFactory mongoDbFactory() throws Exception {
return new SimpleMongoDbFactory(mongo(), getDatabaseName(), getUserCredentials(), getAuthenticationDatabaseName()); return new SimpleMongoDbFactory(mongo(), getDatabaseName(), getUserCredentials(), getAuthenticationDatabaseName());
} }
/** /**
* Return the base package to scan for mapped {@link Document}s. Will return the package name of the configuration * Return the base package to scan for mapped {@link Document}s. Will return the package name of the configuration
* class' (the concrete class, not this one here) by default. So if you have a {@code com.acme.AppConfig} extending * class' (the concrete class, not this one here) by default. So if you have a {@code com.acme.AppConfig} extending
* {@link AbstractMongoConfiguration} the base package will be considered {@code com.acme} unless the method is * {@link AbstractMongoConfiguration} the base package will be considered {@code com.acme} unless the method is
* overridden to implement alternate behavior. * overridden to implement alternate behavior.
* *
* @return the base package to scan for mapped {@link Document} classes or {@literal null} to not enable scanning for * @return the base package to scan for mapped {@link Document} classes or {@literal null} to not enable scanning for
* entities. * entities.
* @deprecated use {@link #getMappingBasePackages()} instead. * @deprecated use {@link #getMappingBasePackages()} instead.
*/ */
@Deprecated @Deprecated
protected String getMappingBasePackage() { protected String getMappingBasePackage() {
Package mappingBasePackage = getClass().getPackage(); Package mappingBasePackage = getClass().getPackage();
return mappingBasePackage == null ? null : mappingBasePackage.getName(); return mappingBasePackage == null ? null : mappingBasePackage.getName();
} }
/** /**
* Returns the base packages to scan for MongoDB mapped entities at startup. Will return the package name of the * Returns the base packages to scan for MongoDB mapped entities at startup. Will return the package name of the
* configuration class' (the concrete class, not this one here) by default. So if you have a * configuration class' (the concrete class, not this one here) by default. So if you have a
* {@code com.acme.AppConfig} extending {@link AbstractMongoConfiguration} the base package will be considered * {@code com.acme.AppConfig} extending {@link AbstractMongoConfiguration} the base package will be considered
* {@code com.acme} unless the method is overridden to implement alternate behavior. * {@code com.acme} unless the method is overridden to implement alternate behavior.
* *
* @return the base packages to scan for mapped {@link Document} classes or an empty collection to not enable scanning * @return the base packages to scan for mapped {@link Document} classes or an empty collection to not enable scanning
* for entities. * for entities.
* @since 1.10 * @since 1.10
*/ */
protected Collection<String> getMappingBasePackages() { protected Collection<String> getMappingBasePackages() {
return Collections.singleton(getMappingBasePackage()); return Collections.singleton(getMappingBasePackage());
} }
/** /**
* Return {@link UserCredentials} to be used when connecting to the MongoDB instance or {@literal null} if none shall * Return {@link UserCredentials} to be used when connecting to the MongoDB instance or {@literal null} if none shall
* be used. * be used.
* *
* @return * @return
* @deprecated since 1.7. {@link MongoClient} should hold authentication data within * @deprecated since 1.7. {@link MongoClient} should hold authentication data within
* {@link MongoClient#getCredentialsList()} * {@link MongoClient#getCredentialsList()}
*/ */
@Deprecated @Deprecated
protected UserCredentials getUserCredentials() { protected UserCredentials getUserCredentials() {
return null; return null;
} }
/** /**
* Creates a {@link MongoMappingContext} equipped with entity classes scanned from the mapping base package. * Creates a {@link MongoMappingContext} equipped with entity classes scanned from the mapping base package.
* *
* @see #getMappingBasePackage() * @see #getMappingBasePackage()
* @return * @return
* @throws ClassNotFoundException * @throws ClassNotFoundException
*/ */
@Bean @Bean
public MongoMappingContext mongoMappingContext() throws ClassNotFoundException { public MongoMappingContext mongoMappingContext() throws ClassNotFoundException {
MongoMappingContext mappingContext = new MongoMappingContext(); MongoMappingContext mappingContext = new MongoMappingContext();
mappingContext.setInitialEntitySet(getInitialEntitySet()); mappingContext.setInitialEntitySet(getInitialEntitySet());
mappingContext.setSimpleTypeHolder(customConversions().getSimpleTypeHolder()); mappingContext.setSimpleTypeHolder(customConversions().getSimpleTypeHolder());
mappingContext.setFieldNamingStrategy(fieldNamingStrategy()); mappingContext.setFieldNamingStrategy(fieldNamingStrategy());
return mappingContext; return mappingContext;
} }
/** /**
* Returns a {@link MappingContextIsNewStrategyFactory} wrapped into a {@link CachingIsNewStrategyFactory}. * Returns a {@link MappingContextIsNewStrategyFactory} wrapped into a {@link CachingIsNewStrategyFactory}.
* *
* @return * @return
* @throws ClassNotFoundException * @throws ClassNotFoundException
*/ */
@Bean @Bean
public IsNewStrategyFactory isNewStrategyFactory() throws ClassNotFoundException { public IsNewStrategyFactory isNewStrategyFactory() throws ClassNotFoundException {
return new CachingIsNewStrategyFactory(new MappingContextIsNewStrategyFactory(mongoMappingContext())); return new CachingIsNewStrategyFactory(new MappingContextIsNewStrategyFactory(mongoMappingContext()));
} }
/** /**
* Register custom {@link Converter}s in a {@link CustomConversions} object if required. These * Register custom {@link Converter}s in a {@link CustomConversions} object if required. These
* {@link CustomConversions} will be registered with the {@link #mappingMongoConverter()} and * {@link CustomConversions} will be registered with the {@link #mappingMongoConverter()} and
* {@link #mongoMappingContext()}. Returns an empty {@link CustomConversions} instance by default. * {@link #mongoMappingContext()}. Returns an empty {@link CustomConversions} instance by default.
* *
* @return must not be {@literal null}. * @return must not be {@literal null}.
*/ */
@Bean @Bean
public CustomConversions customConversions() { public CustomConversions customConversions() {
return new CustomConversions(Collections.emptyList()); return new CustomConversions(Collections.emptyList());
} }
/** /**
* Creates a {@link MappingMongoConverter} using the configured {@link #mongoDbFactory()} and * Creates a {@link MappingMongoConverter} using the configured {@link #mongoDbFactory()} and
* {@link #mongoMappingContext()}. Will get {@link #customConversions()} applied. * {@link #mongoMappingContext()}. Will get {@link #customConversions()} applied.
* *
* @see #customConversions() * @see #customConversions()
* @see #mongoMappingContext() * @see #mongoMappingContext()
* @see #mongoDbFactory() * @see #mongoDbFactory()
* @return * @return
* @throws Exception * @throws Exception
*/ */
@Bean @Bean
public MappingMongoConverter mappingMongoConverter() throws Exception { public MappingMongoConverter mappingMongoConverter() throws Exception {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory()); DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory());
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext()); MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext());
converter.setCustomConversions(customConversions()); converter.setCustomConversions(customConversions());
return converter; return converter;
} }
/** /**
* Scans the mapping base package for classes annotated with {@link Document}. By default, it scans for entities in * Scans the mapping base package for classes annotated with {@link Document}. By default, it scans for entities in
* all packages returned by {@link #getMappingBasePackages()}. * all packages returned by {@link #getMappingBasePackages()}.
* *
* @see #getMappingBasePackages() * @see #getMappingBasePackages()
* @return * @return
* @throws ClassNotFoundException * @throws ClassNotFoundException
*/ */
protected Set<Class<?>> getInitialEntitySet() throws ClassNotFoundException { protected Set<Class<?>> getInitialEntitySet() throws ClassNotFoundException {
Set<Class<?>> initialEntitySet = new HashSet<Class<?>>(); Set<Class<?>> initialEntitySet = new HashSet<Class<?>>();
for (String basePackage : getMappingBasePackages()) { for (String basePackage : getMappingBasePackages()) {
initialEntitySet.addAll(scanForEntities(basePackage)); initialEntitySet.addAll(scanForEntities(basePackage));
} }
return initialEntitySet; return initialEntitySet;
} }
/** /**
* Scans the given base package for entities, i.e. MongoDB specific types annotated with {@link Document} and * Scans the given base package for entities, i.e. MongoDB specific types annotated with {@link Document} and
* {@link Persistent}. * {@link Persistent}.
* *
* @param basePackage must not be {@literal null}. * @param basePackage must not be {@literal null}.
* @return * @return
* @throws ClassNotFoundException * @throws ClassNotFoundException
* @since 1.10 * @since 1.10
*/ */
protected Set<Class<?>> scanForEntities(String basePackage) throws ClassNotFoundException { protected Set<Class<?>> scanForEntities(String basePackage) throws ClassNotFoundException {
if (!StringUtils.hasText(basePackage)) { if (!StringUtils.hasText(basePackage)) {
return Collections.emptySet(); return Collections.emptySet();
} }
Set<Class<?>> initialEntitySet = new HashSet<Class<?>>(); Set<Class<?>> initialEntitySet = new HashSet<Class<?>>();
if (StringUtils.hasText(basePackage)) { if (StringUtils.hasText(basePackage)) {
ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider( ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider(
false); false);
componentProvider.addIncludeFilter(new AnnotationTypeFilter(Document.class)); componentProvider.addIncludeFilter(new AnnotationTypeFilter(Document.class));
componentProvider.addIncludeFilter(new AnnotationTypeFilter(Persistent.class)); componentProvider.addIncludeFilter(new AnnotationTypeFilter(Persistent.class));
for (BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) { for (BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) {
initialEntitySet initialEntitySet
.add(ClassUtils.forName(candidate.getBeanClassName(), AbstractMongoConfiguration.class.getClassLoader())); .add(ClassUtils.forName(candidate.getBeanClassName(), AbstractMongoConfiguration.class.getClassLoader()));
} }
} }
return initialEntitySet; return initialEntitySet;
} }
/** /**
* Configures whether to abbreviate field names for domain objects by configuring a * Configures whether to abbreviate field names for domain objects by configuring a
* {@link CamelCaseAbbreviatingFieldNamingStrategy} on the {@link MongoMappingContext} instance created. For advanced * {@link CamelCaseAbbreviatingFieldNamingStrategy} on the {@link MongoMappingContext} instance created. For advanced
* customization needs, consider overriding {@link #mappingMongoConverter()}. * customization needs, consider overriding {@link #mappingMongoConverter()}.
* *
* @return * @return
*/ */
protected boolean abbreviateFieldNames() { protected boolean abbreviateFieldNames() {
return false; return false;
} }
/** /**
* Configures a {@link FieldNamingStrategy} on the {@link MongoMappingContext} instance created. * Configures a {@link FieldNamingStrategy} on the {@link MongoMappingContext} instance created.
* *
* @return * @return
* @since 1.5 * @since 1.5
*/ */
protected FieldNamingStrategy fieldNamingStrategy() { protected FieldNamingStrategy fieldNamingStrategy() {
return abbreviateFieldNames() ? new CamelCaseAbbreviatingFieldNamingStrategy() return abbreviateFieldNames() ? new CamelCaseAbbreviatingFieldNamingStrategy()
: PropertyNameFieldNamingStrategy.INSTANCE; : PropertyNameFieldNamingStrategy.INSTANCE;
} }
} }

View File

@@ -1,69 +1,69 @@
/* /*
* Copyright 2011 the original author or authors. * Copyright 2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.config; package org.springframework.data.mongodb.config;
import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.BeanComponentDefinition; import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.parsing.CompositeComponentDefinition; import org.springframework.beans.factory.parsing.CompositeComponentDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.BeanDefinitionParser; import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext; import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.data.mongodb.core.MongoAdmin; import org.springframework.data.mongodb.core.MongoAdmin;
import org.springframework.data.mongodb.monitor.*; import org.springframework.data.mongodb.monitor.*;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.w3c.dom.Element; import org.w3c.dom.Element;
public class MongoJmxParser implements BeanDefinitionParser { public class MongoJmxParser implements BeanDefinitionParser {
public BeanDefinition parse(Element element, ParserContext parserContext) { public BeanDefinition parse(Element element, ParserContext parserContext) {
String name = element.getAttribute("mongo-ref"); String name = element.getAttribute("mongo-ref");
if (!StringUtils.hasText(name)) { if (!StringUtils.hasText(name)) {
name = "mongo"; name = "mongo";
} }
registerJmxComponents(name, element, parserContext); registerJmxComponents(name, element, parserContext);
return null; return null;
} }
protected void registerJmxComponents(String mongoRefName, Element element, ParserContext parserContext) { protected void registerJmxComponents(String mongoRefName, Element element, ParserContext parserContext) {
Object eleSource = parserContext.extractSource(element); Object eleSource = parserContext.extractSource(element);
CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), eleSource); CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), eleSource);
createBeanDefEntry(AssertMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); createBeanDefEntry(AssertMetrics.class, compositeDef, mongoRefName, eleSource, parserContext);
createBeanDefEntry(BackgroundFlushingMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); createBeanDefEntry(BackgroundFlushingMetrics.class, compositeDef, mongoRefName, eleSource, parserContext);
createBeanDefEntry(BtreeIndexCounters.class, compositeDef, mongoRefName, eleSource, parserContext); createBeanDefEntry(BtreeIndexCounters.class, compositeDef, mongoRefName, eleSource, parserContext);
createBeanDefEntry(ConnectionMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); createBeanDefEntry(ConnectionMetrics.class, compositeDef, mongoRefName, eleSource, parserContext);
createBeanDefEntry(GlobalLockMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); createBeanDefEntry(GlobalLockMetrics.class, compositeDef, mongoRefName, eleSource, parserContext);
createBeanDefEntry(MemoryMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); createBeanDefEntry(MemoryMetrics.class, compositeDef, mongoRefName, eleSource, parserContext);
createBeanDefEntry(OperationCounters.class, compositeDef, mongoRefName, eleSource, parserContext); createBeanDefEntry(OperationCounters.class, compositeDef, mongoRefName, eleSource, parserContext);
createBeanDefEntry(ServerInfo.class, compositeDef, mongoRefName, eleSource, parserContext); createBeanDefEntry(ServerInfo.class, compositeDef, mongoRefName, eleSource, parserContext);
createBeanDefEntry(MongoAdmin.class, compositeDef, mongoRefName, eleSource, parserContext); createBeanDefEntry(MongoAdmin.class, compositeDef, mongoRefName, eleSource, parserContext);
parserContext.registerComponent(compositeDef); parserContext.registerComponent(compositeDef);
} }
protected void createBeanDefEntry(Class<?> clazz, CompositeComponentDefinition compositeDef, String mongoRefName, protected void createBeanDefEntry(Class<?> clazz, CompositeComponentDefinition compositeDef, String mongoRefName,
Object eleSource, ParserContext parserContext) { Object eleSource, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz); BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
builder.getRawBeanDefinition().setSource(eleSource); builder.getRawBeanDefinition().setSource(eleSource);
builder.addConstructorArgReference(mongoRefName); builder.addConstructorArgReference(mongoRefName);
BeanDefinition assertDef = builder.getBeanDefinition(); BeanDefinition assertDef = builder.getBeanDefinition();
String assertName = parserContext.getReaderContext().registerWithGeneratedName(assertDef); String assertName = parserContext.getReaderContext().registerWithGeneratedName(assertDef);
compositeDef.addNestedComponent(new BeanComponentDefinition(assertDef, assertName)); compositeDef.addNestedComponent(new BeanComponentDefinition(assertDef, assertName));
} }
} }

View File

@@ -1,207 +1,207 @@
/* /*
* Copyright 2011-2017 the original author or authors. * Copyright 2011-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.config; package org.springframework.data.mongodb.config;
import static org.springframework.data.config.ParsingUtils.*; import static org.springframework.data.config.ParsingUtils.*;
import java.util.Map; import java.util.Map;
import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.CustomEditorConfigurer; import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedMap; import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.xml.BeanDefinitionParser; import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.data.mongodb.core.MongoClientOptionsFactoryBean; import org.springframework.data.mongodb.core.MongoClientOptionsFactoryBean;
import org.springframework.data.mongodb.core.MongoOptionsFactoryBean; import org.springframework.data.mongodb.core.MongoOptionsFactoryBean;
import org.springframework.util.xml.DomUtils; import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element; import org.w3c.dom.Element;
/** /**
* Utility methods for {@link BeanDefinitionParser} implementations for MongoDB. * Utility methods for {@link BeanDefinitionParser} implementations for MongoDB.
* *
* @author Mark Pollack * @author Mark Pollack
* @author Oliver Gierke * @author Oliver Gierke
* @author Thomas Darimont * @author Thomas Darimont
* @author Christoph Strobl * @author Christoph Strobl
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
abstract class MongoParsingUtils { abstract class MongoParsingUtils {
private MongoParsingUtils() {} private MongoParsingUtils() {}
/** /**
* Parses the mongo replica-set element. * Parses the mongo replica-set element.
* *
* @param parserContext the parser context * @param parserContext the parser context
* @param element the mongo element * @param element the mongo element
* @param mongoBuilder the bean definition builder to populate * @param mongoBuilder the bean definition builder to populate
* @return * @return
*/ */
static void parseReplicaSet(Element element, BeanDefinitionBuilder mongoBuilder) { static void parseReplicaSet(Element element, BeanDefinitionBuilder mongoBuilder) {
setPropertyValue(mongoBuilder, element, "replica-set", "replicaSetSeeds"); setPropertyValue(mongoBuilder, element, "replica-set", "replicaSetSeeds");
} }
/** /**
* Parses the {@code mongo:options} sub-element. Populates the given attribute factory with the proper attributes. * Parses the {@code mongo:options} sub-element. Populates the given attribute factory with the proper attributes.
* *
* @return true if parsing actually occured, {@literal false} otherwise * @return true if parsing actually occured, {@literal false} otherwise
*/ */
static boolean parseMongoOptions(Element element, BeanDefinitionBuilder mongoBuilder) { static boolean parseMongoOptions(Element element, BeanDefinitionBuilder mongoBuilder) {
Element optionsElement = DomUtils.getChildElementByTagName(element, "options"); Element optionsElement = DomUtils.getChildElementByTagName(element, "options");
if (optionsElement == null) { if (optionsElement == null) {
return false; return false;
} }
BeanDefinitionBuilder optionsDefBuilder = BeanDefinitionBuilder BeanDefinitionBuilder optionsDefBuilder = BeanDefinitionBuilder
.genericBeanDefinition(MongoOptionsFactoryBean.class); .genericBeanDefinition(MongoOptionsFactoryBean.class);
setPropertyValue(optionsDefBuilder, optionsElement, "connections-per-host", "connectionsPerHost"); setPropertyValue(optionsDefBuilder, optionsElement, "connections-per-host", "connectionsPerHost");
setPropertyValue(optionsDefBuilder, optionsElement, "threads-allowed-to-block-for-connection-multiplier", setPropertyValue(optionsDefBuilder, optionsElement, "threads-allowed-to-block-for-connection-multiplier",
"threadsAllowedToBlockForConnectionMultiplier"); "threadsAllowedToBlockForConnectionMultiplier");
setPropertyValue(optionsDefBuilder, optionsElement, "max-wait-time", "maxWaitTime"); setPropertyValue(optionsDefBuilder, optionsElement, "max-wait-time", "maxWaitTime");
setPropertyValue(optionsDefBuilder, optionsElement, "connect-timeout", "connectTimeout"); setPropertyValue(optionsDefBuilder, optionsElement, "connect-timeout", "connectTimeout");
setPropertyValue(optionsDefBuilder, optionsElement, "socket-timeout", "socketTimeout"); setPropertyValue(optionsDefBuilder, optionsElement, "socket-timeout", "socketTimeout");
setPropertyValue(optionsDefBuilder, optionsElement, "socket-keep-alive", "socketKeepAlive"); setPropertyValue(optionsDefBuilder, optionsElement, "socket-keep-alive", "socketKeepAlive");
setPropertyValue(optionsDefBuilder, optionsElement, "auto-connect-retry", "autoConnectRetry"); setPropertyValue(optionsDefBuilder, optionsElement, "auto-connect-retry", "autoConnectRetry");
setPropertyValue(optionsDefBuilder, optionsElement, "max-auto-connect-retry-time", "maxAutoConnectRetryTime"); setPropertyValue(optionsDefBuilder, optionsElement, "max-auto-connect-retry-time", "maxAutoConnectRetryTime");
setPropertyValue(optionsDefBuilder, optionsElement, "write-number", "writeNumber"); setPropertyValue(optionsDefBuilder, optionsElement, "write-number", "writeNumber");
setPropertyValue(optionsDefBuilder, optionsElement, "write-timeout", "writeTimeout"); setPropertyValue(optionsDefBuilder, optionsElement, "write-timeout", "writeTimeout");
setPropertyValue(optionsDefBuilder, optionsElement, "write-fsync", "writeFsync"); setPropertyValue(optionsDefBuilder, optionsElement, "write-fsync", "writeFsync");
setPropertyValue(optionsDefBuilder, optionsElement, "slave-ok", "slaveOk"); setPropertyValue(optionsDefBuilder, optionsElement, "slave-ok", "slaveOk");
setPropertyValue(optionsDefBuilder, optionsElement, "ssl", "ssl"); setPropertyValue(optionsDefBuilder, optionsElement, "ssl", "ssl");
setPropertyReference(optionsDefBuilder, optionsElement, "ssl-socket-factory-ref", "sslSocketFactory"); setPropertyReference(optionsDefBuilder, optionsElement, "ssl-socket-factory-ref", "sslSocketFactory");
mongoBuilder.addPropertyValue("mongoOptions", optionsDefBuilder.getBeanDefinition()); mongoBuilder.addPropertyValue("mongoOptions", optionsDefBuilder.getBeanDefinition());
return true; return true;
} }
/** /**
* Parses the {@code mongo:client-options} sub-element. Populates the given attribute factory with the proper * Parses the {@code mongo:client-options} sub-element. Populates the given attribute factory with the proper
* attributes. * attributes.
* *
* @param element must not be {@literal null}. * @param element must not be {@literal null}.
* @param mongoClientBuilder must not be {@literal null}. * @param mongoClientBuilder must not be {@literal null}.
* @return * @return
* @since 1.7 * @since 1.7
*/ */
public static boolean parseMongoClientOptions(Element element, BeanDefinitionBuilder mongoClientBuilder) { public static boolean parseMongoClientOptions(Element element, BeanDefinitionBuilder mongoClientBuilder) {
Element optionsElement = DomUtils.getChildElementByTagName(element, "client-options"); Element optionsElement = DomUtils.getChildElementByTagName(element, "client-options");
if (optionsElement == null) { if (optionsElement == null) {
return false; return false;
} }
BeanDefinitionBuilder clientOptionsDefBuilder = BeanDefinitionBuilder BeanDefinitionBuilder clientOptionsDefBuilder = BeanDefinitionBuilder
.genericBeanDefinition(MongoClientOptionsFactoryBean.class); .genericBeanDefinition(MongoClientOptionsFactoryBean.class);
setPropertyValue(clientOptionsDefBuilder, optionsElement, "description", "description"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "description", "description");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "min-connections-per-host", "minConnectionsPerHost"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "min-connections-per-host", "minConnectionsPerHost");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "connections-per-host", "connectionsPerHost"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "connections-per-host", "connectionsPerHost");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "threads-allowed-to-block-for-connection-multiplier", setPropertyValue(clientOptionsDefBuilder, optionsElement, "threads-allowed-to-block-for-connection-multiplier",
"threadsAllowedToBlockForConnectionMultiplier"); "threadsAllowedToBlockForConnectionMultiplier");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-wait-time", "maxWaitTime"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-wait-time", "maxWaitTime");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-connection-idle-time", "maxConnectionIdleTime"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-connection-idle-time", "maxConnectionIdleTime");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-connection-life-time", "maxConnectionLifeTime"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-connection-life-time", "maxConnectionLifeTime");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "connect-timeout", "connectTimeout"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "connect-timeout", "connectTimeout");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "socket-timeout", "socketTimeout"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "socket-timeout", "socketTimeout");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "socket-keep-alive", "socketKeepAlive"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "socket-keep-alive", "socketKeepAlive");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "read-preference", "readPreference"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "read-preference", "readPreference");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "write-concern", "writeConcern"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "write-concern", "writeConcern");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-frequency", "heartbeatFrequency"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-frequency", "heartbeatFrequency");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "min-heartbeat-frequency", "minHeartbeatFrequency"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "min-heartbeat-frequency", "minHeartbeatFrequency");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-connect-timeout", "heartbeatConnectTimeout"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-connect-timeout", "heartbeatConnectTimeout");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-socket-timeout", "heartbeatSocketTimeout"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-socket-timeout", "heartbeatSocketTimeout");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "ssl", "ssl"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "ssl", "ssl");
setPropertyReference(clientOptionsDefBuilder, optionsElement, "ssl-socket-factory-ref", "sslSocketFactory"); setPropertyReference(clientOptionsDefBuilder, optionsElement, "ssl-socket-factory-ref", "sslSocketFactory");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "server-selection-timeout", "serverSelectionTimeout"); setPropertyValue(clientOptionsDefBuilder, optionsElement, "server-selection-timeout", "serverSelectionTimeout");
mongoClientBuilder.addPropertyValue("mongoClientOptions", clientOptionsDefBuilder.getBeanDefinition()); mongoClientBuilder.addPropertyValue("mongoClientOptions", clientOptionsDefBuilder.getBeanDefinition());
return true; return true;
} }
/** /**
* Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a * Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a
* {@link WriteConcernPropertyEditor}. * {@link WriteConcernPropertyEditor}.
* *
* @return * @return
*/ */
static BeanDefinitionBuilder getWriteConcernPropertyEditorBuilder() { static BeanDefinitionBuilder getWriteConcernPropertyEditorBuilder() {
Map<String, Class<?>> customEditors = new ManagedMap<String, Class<?>>(); Map<String, Class<?>> customEditors = new ManagedMap<String, Class<?>>();
customEditors.put("com.mongodb.WriteConcern", WriteConcernPropertyEditor.class); customEditors.put("com.mongodb.WriteConcern", WriteConcernPropertyEditor.class);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class); BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class);
builder.addPropertyValue("customEditors", customEditors); builder.addPropertyValue("customEditors", customEditors);
return builder; return builder;
} }
/** /**
* One should only register one bean definition but want to have the convenience of using * One should only register one bean definition but want to have the convenience of using
* AbstractSingleBeanDefinitionParser but have the side effect of registering a 'default' property editor with the * AbstractSingleBeanDefinitionParser but have the side effect of registering a 'default' property editor with the
* container. * container.
*/ */
static BeanDefinitionBuilder getServerAddressPropertyEditorBuilder() { static BeanDefinitionBuilder getServerAddressPropertyEditorBuilder() {
Map<String, String> customEditors = new ManagedMap<String, String>(); Map<String, String> customEditors = new ManagedMap<String, String>();
customEditors.put("com.mongodb.ServerAddress[]", customEditors.put("com.mongodb.ServerAddress[]",
"org.springframework.data.mongodb.config.ServerAddressPropertyEditor"); "org.springframework.data.mongodb.config.ServerAddressPropertyEditor");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class); BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class);
builder.addPropertyValue("customEditors", customEditors); builder.addPropertyValue("customEditors", customEditors);
return builder; return builder;
} }
/** /**
* Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a * Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a
* {@link ReadPreferencePropertyEditor}. * {@link ReadPreferencePropertyEditor}.
* *
* @return * @return
* @since 1.7 * @since 1.7
*/ */
static BeanDefinitionBuilder getReadPreferencePropertyEditorBuilder() { static BeanDefinitionBuilder getReadPreferencePropertyEditorBuilder() {
Map<String, Class<?>> customEditors = new ManagedMap<String, Class<?>>(); Map<String, Class<?>> customEditors = new ManagedMap<String, Class<?>>();
customEditors.put("com.mongodb.ReadPreference", ReadPreferencePropertyEditor.class); customEditors.put("com.mongodb.ReadPreference", ReadPreferencePropertyEditor.class);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class); BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class);
builder.addPropertyValue("customEditors", customEditors); builder.addPropertyValue("customEditors", customEditors);
return builder; return builder;
} }
/** /**
* Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a * Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a
* {@link MongoCredentialPropertyEditor}. * {@link MongoCredentialPropertyEditor}.
* *
* @return * @return
* @since 1.7 * @since 1.7
*/ */
static BeanDefinitionBuilder getMongoCredentialPropertyEditor() { static BeanDefinitionBuilder getMongoCredentialPropertyEditor() {
Map<String, Class<?>> customEditors = new ManagedMap<String, Class<?>>(); Map<String, Class<?>> customEditors = new ManagedMap<String, Class<?>>();
customEditors.put("com.mongodb.MongoCredential[]", MongoCredentialPropertyEditor.class); customEditors.put("com.mongodb.MongoCredential[]", MongoCredentialPropertyEditor.class);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class); BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class);
builder.addPropertyValue("customEditors", customEditors); builder.addPropertyValue("customEditors", customEditors);
return builder; return builder;
} }
} }

View File

@@ -1,26 +1,26 @@
/* /*
* Copyright 2010-2011 the original author or authors. * Copyright 2010-2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
import com.mongodb.DBCollection; import com.mongodb.DBCollection;
import com.mongodb.MongoException; import com.mongodb.MongoException;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
public interface CollectionCallback<T> { public interface CollectionCallback<T> {
T doInCollection(DBCollection collection) throws MongoException, DataAccessException; T doInCollection(DBCollection collection) throws MongoException, DataAccessException;
} }

View File

@@ -1,70 +1,70 @@
/* /*
* Copyright 2010-2011 the original author or authors. * Copyright 2010-2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
/** /**
* Provides a simple wrapper to encapsulate the variety of settings you can use when creating a collection. * Provides a simple wrapper to encapsulate the variety of settings you can use when creating a collection.
* *
* @author Thomas Risberg * @author Thomas Risberg
*/ */
public class CollectionOptions { public class CollectionOptions {
private Integer maxDocuments; private Integer maxDocuments;
private Integer size; private Integer size;
private Boolean capped; private Boolean capped;
/** /**
* Constructs a new <code>CollectionOptions</code> instance. * Constructs a new <code>CollectionOptions</code> instance.
* *
* @param size the collection size in bytes, this data space is preallocated * @param size the collection size in bytes, this data space is preallocated
* @param maxDocuments the maximum number of documents in the collection. * @param maxDocuments the maximum number of documents in the collection.
* @param capped true to created a "capped" collection (fixed size with auto-FIFO behavior based on insertion order), * @param capped true to created a "capped" collection (fixed size with auto-FIFO behavior based on insertion order),
* false otherwise. * false otherwise.
*/ */
public CollectionOptions(Integer size, Integer maxDocuments, Boolean capped) { public CollectionOptions(Integer size, Integer maxDocuments, Boolean capped) {
super(); super();
this.maxDocuments = maxDocuments; this.maxDocuments = maxDocuments;
this.size = size; this.size = size;
this.capped = capped; this.capped = capped;
} }
public Integer getMaxDocuments() { public Integer getMaxDocuments() {
return maxDocuments; return maxDocuments;
} }
public void setMaxDocuments(Integer maxDocuments) { public void setMaxDocuments(Integer maxDocuments) {
this.maxDocuments = maxDocuments; this.maxDocuments = maxDocuments;
} }
public Integer getSize() { public Integer getSize() {
return size; return size;
} }
public void setSize(Integer size) { public void setSize(Integer size) {
this.size = size; this.size = size;
} }
public Boolean getCapped() { public Boolean getCapped() {
return capped; return capped;
} }
public void setCapped(Boolean capped) { public void setCapped(Boolean capped) {
this.capped = capped; this.capped = capped;
} }
} }

View File

@@ -1,25 +1,25 @@
/* /*
* Copyright 2010-2011 the original author or authors. * Copyright 2010-2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
import com.mongodb.DB; import com.mongodb.DB;
import com.mongodb.MongoException; import com.mongodb.MongoException;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
public interface DbCallback<T> { public interface DbCallback<T> {
T doInDB(DB db) throws MongoException, DataAccessException; T doInDB(DB db) throws MongoException, DataAccessException;
} }

View File

@@ -1,101 +1,101 @@
/* /*
* Copyright 2011-2017 the original author or authors. * Copyright 2011-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
import org.springframework.data.authentication.UserCredentials; import org.springframework.data.authentication.UserCredentials;
import org.springframework.jmx.export.annotation.ManagedOperation; import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import com.mongodb.DB; import com.mongodb.DB;
import com.mongodb.Mongo; import com.mongodb.Mongo;
/** /**
* Mongo server administration exposed via JMX annotations * Mongo server administration exposed via JMX annotations
* *
* @author Mark Pollack * @author Mark Pollack
* @author Thomas Darimont * @author Thomas Darimont
* @author Mark Paluch * @author Mark Paluch
*/ */
@ManagedResource(description = "Mongo Admin Operations") @ManagedResource(description = "Mongo Admin Operations")
public class MongoAdmin implements MongoAdminOperations { public class MongoAdmin implements MongoAdminOperations {
private final Mongo mongo; private final Mongo mongo;
private String username; private String username;
private String password; private String password;
private String authenticationDatabaseName; private String authenticationDatabaseName;
public MongoAdmin(Mongo mongo) { public MongoAdmin(Mongo mongo) {
Assert.notNull(mongo, "Mongo must not be null!"); Assert.notNull(mongo, "Mongo must not be null!");
this.mongo = mongo; this.mongo = mongo;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.data.mongodb.core.core.MongoAdminOperations#dropDatabase(java.lang.String) * @see org.springframework.data.mongodb.core.core.MongoAdminOperations#dropDatabase(java.lang.String)
*/ */
@ManagedOperation @ManagedOperation
public void dropDatabase(String databaseName) { public void dropDatabase(String databaseName) {
getDB(databaseName).dropDatabase(); getDB(databaseName).dropDatabase();
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.data.mongodb.core.core.MongoAdminOperations#createDatabase(java.lang.String) * @see org.springframework.data.mongodb.core.core.MongoAdminOperations#createDatabase(java.lang.String)
*/ */
@ManagedOperation @ManagedOperation
public void createDatabase(String databaseName) { public void createDatabase(String databaseName) {
getDB(databaseName); getDB(databaseName);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.data.mongodb.core.core.MongoAdminOperations#getDatabaseStats(java.lang.String) * @see org.springframework.data.mongodb.core.core.MongoAdminOperations#getDatabaseStats(java.lang.String)
*/ */
@ManagedOperation @ManagedOperation
public String getDatabaseStats(String databaseName) { public String getDatabaseStats(String databaseName) {
return getDB(databaseName).getStats().toString(); return getDB(databaseName).getStats().toString();
} }
/** /**
* Sets the username to use to connect to the Mongo database * Sets the username to use to connect to the Mongo database
* *
* @param username The username to use * @param username The username to use
*/ */
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
/** /**
* Sets the password to use to authenticate with the Mongo database. * Sets the password to use to authenticate with the Mongo database.
* *
* @param password The password to use * @param password The password to use
*/ */
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
/** /**
* Sets the authenticationDatabaseName to use to authenticate with the Mongo database. * Sets the authenticationDatabaseName to use to authenticate with the Mongo database.
* *
* @param authenticationDatabaseName The authenticationDatabaseName to use. * @param authenticationDatabaseName The authenticationDatabaseName to use.
*/ */
public void setAuthenticationDatabaseName(String authenticationDatabaseName) { public void setAuthenticationDatabaseName(String authenticationDatabaseName) {
this.authenticationDatabaseName = authenticationDatabaseName; this.authenticationDatabaseName = authenticationDatabaseName;
} }
DB getDB(String databaseName) { DB getDB(String databaseName) {
return MongoDbUtils.getDB(mongo, databaseName, new UserCredentials(username, password), authenticationDatabaseName); return MongoDbUtils.getDB(mongo, databaseName, new UserCredentials(username, password), authenticationDatabaseName);
} }
} }

View File

@@ -1,34 +1,34 @@
/* /*
* Copyright 2011-2014 the original author or authors. * Copyright 2011-2014 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
import org.springframework.jmx.export.annotation.ManagedOperation; import org.springframework.jmx.export.annotation.ManagedOperation;
/** /**
* @author Mark Pollack * @author Mark Pollack
* @author Oliver Gierke * @author Oliver Gierke
*/ */
public interface MongoAdminOperations { public interface MongoAdminOperations {
@ManagedOperation @ManagedOperation
void dropDatabase(String databaseName); void dropDatabase(String databaseName);
@ManagedOperation @ManagedOperation
void createDatabase(String databaseName); void createDatabase(String databaseName);
@ManagedOperation @ManagedOperation
String getDatabaseStats(String databaseName); String getDatabaseStats(String databaseName);
} }

View File

@@ -1,235 +1,235 @@
/* /*
* Copyright 2011-2015 the original author or authors. * Copyright 2011-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core; package org.springframework.data.mongodb.core;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.DisposableBean;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.data.authentication.UserCredentials; import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import com.mongodb.DB; import com.mongodb.DB;
import com.mongodb.Mongo; import com.mongodb.Mongo;
import com.mongodb.MongoClient; import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI; import com.mongodb.MongoClientURI;
import com.mongodb.MongoException; import com.mongodb.MongoException;
import com.mongodb.MongoURI; import com.mongodb.MongoURI;
import com.mongodb.WriteConcern; import com.mongodb.WriteConcern;
/** /**
* Factory to create {@link DB} instances from a {@link Mongo} instance. * Factory to create {@link DB} instances from a {@link Mongo} instance.
* *
* @author Mark Pollack * @author Mark Pollack
* @author Oliver Gierke * @author Oliver Gierke
* @author Thomas Darimont * @author Thomas Darimont
* @author Christoph Strobl * @author Christoph Strobl
*/ */
public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory { public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory {
private final Mongo mongo; private final Mongo mongo;
private final String databaseName; private final String databaseName;
private final boolean mongoInstanceCreated; private final boolean mongoInstanceCreated;
private final UserCredentials credentials; private final UserCredentials credentials;
private final PersistenceExceptionTranslator exceptionTranslator; private final PersistenceExceptionTranslator exceptionTranslator;
private final String authenticationDatabaseName; private final String authenticationDatabaseName;
private WriteConcern writeConcern; private WriteConcern writeConcern;
/** /**
* Create an instance of {@link SimpleMongoDbFactory} given the {@link Mongo} instance and database name. * Create an instance of {@link SimpleMongoDbFactory} given the {@link Mongo} instance and database name.
* *
* @param mongo Mongo instance, must not be {@literal null}. * @param mongo Mongo instance, must not be {@literal null}.
* @param databaseName database name, not be {@literal null} or empty. * @param databaseName database name, not be {@literal null} or empty.
* @deprecated since 1.7. Please use {@link #SimpleMongoDbFactory(MongoClient, String)}. * @deprecated since 1.7. Please use {@link #SimpleMongoDbFactory(MongoClient, String)}.
*/ */
@Deprecated @Deprecated
public SimpleMongoDbFactory(Mongo mongo, String databaseName) { public SimpleMongoDbFactory(Mongo mongo, String databaseName) {
this(mongo, databaseName, null); this(mongo, databaseName, null);
} }
/** /**
* Create an instance of SimpleMongoDbFactory given the Mongo instance, database name, and username/password * Create an instance of SimpleMongoDbFactory given the Mongo instance, database name, and username/password
* *
* @param mongo Mongo instance, must not be {@literal null}. * @param mongo Mongo instance, must not be {@literal null}.
* @param databaseName Database name, must not be {@literal null} or empty. * @param databaseName Database name, must not be {@literal null} or empty.
* @param credentials username and password. * @param credentials username and password.
* @deprecated since 1.7. The credentials used should be provided by {@link MongoClient#getCredentialsList()}. * @deprecated since 1.7. The credentials used should be provided by {@link MongoClient#getCredentialsList()}.
*/ */
@Deprecated @Deprecated
public SimpleMongoDbFactory(Mongo mongo, String databaseName, UserCredentials credentials) { public SimpleMongoDbFactory(Mongo mongo, String databaseName, UserCredentials credentials) {
this(mongo, databaseName, credentials, false, null); this(mongo, databaseName, credentials, false, null);
} }
/** /**
* Create an instance of SimpleMongoDbFactory given the Mongo instance, database name, and username/password * Create an instance of SimpleMongoDbFactory given the Mongo instance, database name, and username/password
* *
* @param mongo Mongo instance, must not be {@literal null}. * @param mongo Mongo instance, must not be {@literal null}.
* @param databaseName Database name, must not be {@literal null} or empty. * @param databaseName Database name, must not be {@literal null} or empty.
* @param credentials username and password. * @param credentials username and password.
* @param authenticationDatabaseName the database name to use for authentication * @param authenticationDatabaseName the database name to use for authentication
* @deprecated since 1.7. The credentials used should be provided by {@link MongoClient#getCredentialsList()}. * @deprecated since 1.7. The credentials used should be provided by {@link MongoClient#getCredentialsList()}.
*/ */
@Deprecated @Deprecated
public SimpleMongoDbFactory(Mongo mongo, String databaseName, UserCredentials credentials, public SimpleMongoDbFactory(Mongo mongo, String databaseName, UserCredentials credentials,
String authenticationDatabaseName) { String authenticationDatabaseName) {
this(mongo, databaseName, credentials, false, authenticationDatabaseName); this(mongo, databaseName, credentials, false, authenticationDatabaseName);
} }
/** /**
* Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoURI}. * Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoURI}.
* *
* @param uri must not be {@literal null}. * @param uri must not be {@literal null}.
* @throws MongoException * @throws MongoException
* @throws UnknownHostException * @throws UnknownHostException
* @see MongoURI * @see MongoURI
* @deprecated since 1.7. Please use {@link #SimpleMongoDbFactory(MongoClientURI)} instead. * @deprecated since 1.7. Please use {@link #SimpleMongoDbFactory(MongoClientURI)} instead.
*/ */
@Deprecated @Deprecated
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())), true, this(new Mongo(uri), uri.getDatabase(), new UserCredentials(uri.getUsername(), parseChars(uri.getPassword())), true,
uri.getDatabase()); uri.getDatabase());
} }
/** /**
* Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoClientURI}. * Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoClientURI}.
* *
* @param uri must not be {@literal null}. * @param uri must not be {@literal null}.
* @throws UnknownHostException * @throws UnknownHostException
* @since 1.7 * @since 1.7
*/ */
public SimpleMongoDbFactory(MongoClientURI uri) throws UnknownHostException { public SimpleMongoDbFactory(MongoClientURI uri) throws UnknownHostException {
this(new MongoClient(uri), uri.getDatabase(), true); this(new MongoClient(uri), uri.getDatabase(), true);
} }
/** /**
* Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoClient}. * Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoClient}.
* *
* @param mongoClient must not be {@literal null}. * @param mongoClient must not be {@literal null}.
* @param databaseName must not be {@literal null}. * @param databaseName must not be {@literal null}.
* @since 1.7 * @since 1.7
*/ */
public SimpleMongoDbFactory(MongoClient mongoClient, String databaseName) { public SimpleMongoDbFactory(MongoClient mongoClient, String databaseName) {
this(mongoClient, databaseName, false); this(mongoClient, databaseName, false);
} }
private SimpleMongoDbFactory(Mongo mongo, String databaseName, UserCredentials credentials, private SimpleMongoDbFactory(Mongo mongo, String databaseName, UserCredentials credentials,
boolean mongoInstanceCreated, String authenticationDatabaseName) { boolean mongoInstanceCreated, String authenticationDatabaseName) {
if (mongo instanceof MongoClient && (credentials != null && !UserCredentials.NO_CREDENTIALS.equals(credentials))) { if (mongo instanceof MongoClient && (credentials != null && !UserCredentials.NO_CREDENTIALS.equals(credentials))) {
throw new InvalidDataAccessApiUsageException( throw new InvalidDataAccessApiUsageException(
"Usage of 'UserCredentials' with 'MongoClient' is no longer supported. Please use 'MongoCredential' for 'MongoClient' or just 'Mongo'."); "Usage of 'UserCredentials' with 'MongoClient' is no longer supported. Please use 'MongoCredential' for 'MongoClient' or just 'Mongo'.");
} }
Assert.notNull(mongo, "Mongo must not be null"); Assert.notNull(mongo, "Mongo must not be null");
Assert.hasText(databaseName, "Database name must not be empty"); Assert.hasText(databaseName, "Database name must not be empty");
Assert.isTrue(databaseName.matches("[\\w-]+"), Assert.isTrue(databaseName.matches("[\\w-]+"),
"Database name must only contain letters, numbers, underscores and dashes!"); "Database name must only contain letters, numbers, underscores and dashes!");
this.mongo = mongo; this.mongo = mongo;
this.databaseName = databaseName; this.databaseName = databaseName;
this.mongoInstanceCreated = mongoInstanceCreated; this.mongoInstanceCreated = mongoInstanceCreated;
this.credentials = credentials == null ? UserCredentials.NO_CREDENTIALS : credentials; this.credentials = credentials == null ? UserCredentials.NO_CREDENTIALS : credentials;
this.exceptionTranslator = new MongoExceptionTranslator(); this.exceptionTranslator = new MongoExceptionTranslator();
this.authenticationDatabaseName = StringUtils.hasText(authenticationDatabaseName) ? authenticationDatabaseName this.authenticationDatabaseName = StringUtils.hasText(authenticationDatabaseName) ? authenticationDatabaseName
: databaseName; : databaseName;
Assert.isTrue(this.authenticationDatabaseName.matches("[\\w-]+"), Assert.isTrue(this.authenticationDatabaseName.matches("[\\w-]+"),
"Authentication database name must only contain letters, numbers, underscores and dashes!"); "Authentication database name must only contain letters, numbers, underscores and dashes!");
} }
/** /**
* @param client * @param client
* @param databaseName * @param databaseName
* @param mongoInstanceCreated * @param mongoInstanceCreated
* @since 1.7 * @since 1.7
*/ */
private SimpleMongoDbFactory(MongoClient client, String databaseName, boolean mongoInstanceCreated) { private SimpleMongoDbFactory(MongoClient client, String databaseName, boolean mongoInstanceCreated) {
Assert.notNull(client, "MongoClient must not be null!"); Assert.notNull(client, "MongoClient must not be null!");
Assert.hasText(databaseName, "Database name must not be empty!"); Assert.hasText(databaseName, "Database name must not be empty!");
this.mongo = client; this.mongo = client;
this.databaseName = databaseName; this.databaseName = databaseName;
this.mongoInstanceCreated = mongoInstanceCreated; this.mongoInstanceCreated = mongoInstanceCreated;
this.exceptionTranslator = new MongoExceptionTranslator(); this.exceptionTranslator = new MongoExceptionTranslator();
this.credentials = UserCredentials.NO_CREDENTIALS; this.credentials = UserCredentials.NO_CREDENTIALS;
this.authenticationDatabaseName = databaseName; this.authenticationDatabaseName = databaseName;
} }
/** /**
* Configures the {@link WriteConcern} to be used on the {@link DB} instance being created. * Configures the {@link WriteConcern} to be used on the {@link DB} instance being created.
* *
* @param writeConcern the writeConcern to set * @param writeConcern the writeConcern to set
*/ */
public void setWriteConcern(WriteConcern writeConcern) { public void setWriteConcern(WriteConcern writeConcern) {
this.writeConcern = writeConcern; this.writeConcern = writeConcern;
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see org.springframework.data.mongodb.MongoDbFactory#getDb() * @see org.springframework.data.mongodb.MongoDbFactory#getDb()
*/ */
public DB getDb() throws DataAccessException { public DB getDb() throws DataAccessException {
return getDb(databaseName); return getDb(databaseName);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see org.springframework.data.mongodb.MongoDbFactory#getDb(java.lang.String) * @see org.springframework.data.mongodb.MongoDbFactory#getDb(java.lang.String)
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public DB getDb(String dbName) throws DataAccessException { public DB getDb(String dbName) throws DataAccessException {
Assert.hasText(dbName, "Database name must not be empty."); Assert.hasText(dbName, "Database name must not be empty.");
DB db = MongoDbUtils.getDB(mongo, dbName, credentials, authenticationDatabaseName); DB db = MongoDbUtils.getDB(mongo, dbName, credentials, authenticationDatabaseName);
if (writeConcern != null) { if (writeConcern != null) {
db.setWriteConcern(writeConcern); db.setWriteConcern(writeConcern);
} }
return db; return db;
} }
/** /**
* Clean up the Mongo instance if it was created by the factory itself. * Clean up the Mongo instance if it was created by the factory itself.
* *
* @see DisposableBean#destroy() * @see DisposableBean#destroy()
*/ */
public void destroy() throws Exception { public void destroy() throws Exception {
if (mongoInstanceCreated) { if (mongoInstanceCreated) {
mongo.close(); mongo.close();
} }
} }
private static String parseChars(char[] chars) { private static String parseChars(char[] chars) {
return chars == null ? null : String.valueOf(chars); return chars == null ? null : String.valueOf(chars);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see org.springframework.data.mongodb.MongoDbFactory#getExceptionTranslator() * @see org.springframework.data.mongodb.MongoDbFactory#getExceptionTranslator()
*/ */
@Override @Override
public PersistenceExceptionTranslator getExceptionTranslator() { public PersistenceExceptionTranslator getExceptionTranslator() {
return this.exceptionTranslator; return this.exceptionTranslator;
} }
} }

View File

@@ -1,43 +1,43 @@
/* /*
* Copyright 2010-2013 the original author or authors. * Copyright 2010-2013 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core.convert; package org.springframework.data.mongodb.core.convert;
import org.springframework.data.convert.EntityConverter; import org.springframework.data.convert.EntityConverter;
import org.springframework.data.convert.EntityReader; import org.springframework.data.convert.EntityReader;
import org.springframework.data.convert.TypeMapper; import org.springframework.data.convert.TypeMapper;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity; import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import com.mongodb.DBObject; import com.mongodb.DBObject;
/** /**
* Central Mongo specific converter interface which combines {@link MongoWriter} and {@link MongoReader}. * Central Mongo specific converter interface which combines {@link MongoWriter} and {@link MongoReader}.
* *
* @author Oliver Gierke * @author Oliver Gierke
* @author Thomas Darimont * @author Thomas Darimont
*/ */
public interface MongoConverter extends public interface MongoConverter extends
EntityConverter<MongoPersistentEntity<?>, MongoPersistentProperty, Object, DBObject>, MongoWriter<Object>, EntityConverter<MongoPersistentEntity<?>, MongoPersistentProperty, Object, DBObject>, MongoWriter<Object>,
EntityReader<Object, DBObject> { EntityReader<Object, DBObject> {
/** /**
* Returns thw {@link TypeMapper} being used to write type information into {@link DBObject}s created with that * Returns thw {@link TypeMapper} being used to write type information into {@link DBObject}s created with that
* converter. * converter.
* *
* @return will never be {@literal null}. * @return will never be {@literal null}.
*/ */
MongoTypeMapper getTypeMapper(); MongoTypeMapper getTypeMapper();
} }

View File

@@ -1,63 +1,63 @@
/* /*
* Copyright 2010-2013 the original author or authors. * Copyright 2010-2013 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.core.convert; package org.springframework.data.mongodb.core.convert;
import org.springframework.data.convert.EntityWriter; import org.springframework.data.convert.EntityWriter;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.util.TypeInformation; import org.springframework.data.util.TypeInformation;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.DBRef; import com.mongodb.DBRef;
/** /**
* A MongoWriter is responsible for converting an object of type T to the native MongoDB representation DBObject. * A MongoWriter is responsible for converting an object of type T to the native MongoDB representation DBObject.
* *
* @param <T> the type of the object to convert to a DBObject * @param <T> the type of the object to convert to a DBObject
* @author Mark Pollack * @author Mark Pollack
* @author Thomas Risberg * @author Thomas Risberg
* @author Oliver Gierke * @author Oliver Gierke
*/ */
public interface MongoWriter<T> extends EntityWriter<T, DBObject> { public interface MongoWriter<T> extends EntityWriter<T, DBObject> {
/** /**
* Converts the given object into one Mongo will be able to store natively. If the given object can already be stored * Converts the given object into one Mongo will be able to store natively. If the given object can already be stored
* as is, no conversion will happen. * as is, no conversion will happen.
* *
* @param obj can be {@literal null}. * @param obj can be {@literal null}.
* @return * @return
*/ */
Object convertToMongoType(Object obj); Object convertToMongoType(Object obj);
/** /**
* Converts the given object into one Mongo will be able to store natively but retains the type information in case * Converts the given object into one Mongo will be able to store natively but retains the type information in case
* the given {@link TypeInformation} differs from the given object type. * the given {@link TypeInformation} differs from the given object type.
* *
* @param obj can be {@literal null}. * @param obj can be {@literal null}.
* @param typeInformation can be {@literal null}. * @param typeInformation can be {@literal null}.
* @return * @return
*/ */
Object convertToMongoType(Object obj, TypeInformation<?> typeInformation); Object convertToMongoType(Object obj, TypeInformation<?> typeInformation);
/** /**
* Creates a {@link DBRef} to refer to the given object. * Creates a {@link DBRef} to refer to the given object.
* *
* @param object the object to create a {@link DBRef} to link to. The object's type has to carry an id attribute. * @param object the object to create a {@link DBRef} to link to. The object's type has to carry an id attribute.
* @param referingProperty the client-side property referring to the object which might carry additional metadata for * @param referingProperty the client-side property referring to the object which might carry additional metadata for
* the {@link DBRef} object to create. Can be {@literal null}. * the {@link DBRef} object to create. Can be {@literal null}.
* @return will never be {@literal null}. * @return will never be {@literal null}.
*/ */
DBRef toDBRef(Object object, MongoPersistentProperty referingProperty); DBRef toDBRef(Object object, MongoPersistentProperty referingProperty);
} }

View File

@@ -1,72 +1,72 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.monitor; package org.springframework.data.mongodb.monitor;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.data.authentication.UserCredentials; import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.core.MongoDbUtils; import org.springframework.data.mongodb.core.MongoDbUtils;
import com.mongodb.CommandResult; import com.mongodb.CommandResult;
import com.mongodb.DB; import com.mongodb.DB;
import com.mongodb.Mongo; import com.mongodb.Mongo;
import com.mongodb.MongoException; import com.mongodb.MongoException;
/** /**
* Base class to encapsulate common configuration settings when connecting to a database * Base class to encapsulate common configuration settings when connecting to a database
* *
* @author Mark Pollack * @author Mark Pollack
* @author Oliver Gierke * @author Oliver Gierke
*/ */
public abstract class AbstractMonitor { public abstract class AbstractMonitor {
private final Logger logger = LoggerFactory.getLogger(getClass()); private final Logger logger = LoggerFactory.getLogger(getClass());
protected Mongo mongo; protected Mongo mongo;
private String username; private String username;
private String password; private String password;
/** /**
* Sets the username to use to connect to the Mongo database * Sets the username to use to connect to the Mongo database
* *
* @param username The username to use * @param username The username to use
*/ */
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
/** /**
* Sets the password to use to authenticate with the Mongo database. * Sets the password to use to authenticate with the Mongo database.
* *
* @param password The password to use * @param password The password to use
*/ */
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
public CommandResult getServerStatus() { public CommandResult getServerStatus() {
CommandResult result = getDb("admin").command("serverStatus"); CommandResult result = getDb("admin").command("serverStatus");
if (!result.ok()) { if (!result.ok()) {
logger.error("Could not query for server status. Command Result = " + result); logger.error("Could not query for server status. Command Result = " + result);
throw new MongoException("could not query for server status. Command Result = " + result); throw new MongoException("could not query for server status. Command Result = " + result);
} }
return result; return result;
} }
public DB getDb(String databaseName) { public DB getDb(String databaseName) {
return MongoDbUtils.getDB(mongo, databaseName, new UserCredentials(username, password)); return MongoDbUtils.getDB(mongo, databaseName, new UserCredentials(username, password));
} }
} }

View File

@@ -1,67 +1,67 @@
/* /*
* Copyright 2002-2011 the original author or authors. * Copyright 2002-2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.monitor; package org.springframework.data.mongodb.monitor;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.Mongo; import com.mongodb.Mongo;
import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedMetric;
import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.jmx.support.MetricType; import org.springframework.jmx.support.MetricType;
/** /**
* JMX Metrics for assertions * JMX Metrics for assertions
* *
* @author Mark Pollack * @author Mark Pollack
*/ */
@ManagedResource(description = "Assertion Metrics") @ManagedResource(description = "Assertion Metrics")
public class AssertMetrics extends AbstractMonitor { public class AssertMetrics extends AbstractMonitor {
public AssertMetrics(Mongo mongo) { public AssertMetrics(Mongo mongo) {
this.mongo = mongo; this.mongo = mongo;
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Regular") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Regular")
public int getRegular() { public int getRegular() {
return getBtree("regular"); return getBtree("regular");
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Warning") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Warning")
public int getWarning() { public int getWarning() {
return getBtree("warning"); return getBtree("warning");
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Msg") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Msg")
public int getMsg() { public int getMsg() {
return getBtree("msg"); return getBtree("msg");
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "User") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "User")
public int getUser() { public int getUser() {
return getBtree("user"); return getBtree("user");
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Rollovers") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Rollovers")
public int getRollovers() { public int getRollovers() {
return getBtree("rollovers"); return getBtree("rollovers");
} }
private int getBtree(String key) { private int getBtree(String key) {
DBObject asserts = (DBObject) getServerStatus().get("asserts"); DBObject asserts = (DBObject) getServerStatus().get("asserts");
// Class c = btree.get(key).getClass(); // Class c = btree.get(key).getClass();
return (Integer) asserts.get(key); return (Integer) asserts.get(key);
} }
} }

View File

@@ -1,75 +1,75 @@
/* /*
* Copyright 2002-2011 the original author or authors. * Copyright 2002-2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.monitor; package org.springframework.data.mongodb.monitor;
import java.util.Date; import java.util.Date;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.Mongo; import com.mongodb.Mongo;
import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedMetric;
import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.jmx.support.MetricType; import org.springframework.jmx.support.MetricType;
/** /**
* JMX Metrics for Background Flushing * JMX Metrics for Background Flushing
* *
* @author Mark Pollack * @author Mark Pollack
*/ */
@ManagedResource(description = "Background Flushing Metrics") @ManagedResource(description = "Background Flushing Metrics")
public class BackgroundFlushingMetrics extends AbstractMonitor { public class BackgroundFlushingMetrics extends AbstractMonitor {
public BackgroundFlushingMetrics(Mongo mongo) { public BackgroundFlushingMetrics(Mongo mongo) {
this.mongo = mongo; this.mongo = mongo;
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Flushes") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Flushes")
public int getFlushes() { public int getFlushes() {
return getFlushingData("flushes", java.lang.Integer.class); return getFlushingData("flushes", java.lang.Integer.class);
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Total ms", unit = "ms") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Total ms", unit = "ms")
public int getTotalMs() { public int getTotalMs() {
return getFlushingData("total_ms", java.lang.Integer.class); return getFlushingData("total_ms", java.lang.Integer.class);
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Average ms", unit = "ms") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Average ms", unit = "ms")
public double getAverageMs() { public double getAverageMs() {
return getFlushingData("average_ms", java.lang.Double.class); return getFlushingData("average_ms", java.lang.Double.class);
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Last Ms", unit = "ms") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Last Ms", unit = "ms")
public int getLastMs() { public int getLastMs() {
return getFlushingData("last_ms", java.lang.Integer.class); return getFlushingData("last_ms", java.lang.Integer.class);
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Last finished") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Last finished")
public Date getLastFinished() { public Date getLastFinished() {
return getLast(); return getLast();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private <T> T getFlushingData(String key, Class<T> targetClass) { private <T> T getFlushingData(String key, Class<T> targetClass) {
DBObject mem = (DBObject) getServerStatus().get("backgroundFlushing"); DBObject mem = (DBObject) getServerStatus().get("backgroundFlushing");
return (T) mem.get(key); return (T) mem.get(key);
} }
private Date getLast() { private Date getLast() {
DBObject bgFlush = (DBObject) getServerStatus().get("backgroundFlushing"); DBObject bgFlush = (DBObject) getServerStatus().get("backgroundFlushing");
Date lastFinished = (Date) bgFlush.get("last_finished"); Date lastFinished = (Date) bgFlush.get("last_finished");
return lastFinished; return lastFinished;
} }
} }

View File

@@ -1,74 +1,74 @@
/* /*
* Copyright 2002-2011 the original author or authors. * Copyright 2002-2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.monitor; package org.springframework.data.mongodb.monitor;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.Mongo; import com.mongodb.Mongo;
import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedMetric;
import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.jmx.support.MetricType; import org.springframework.jmx.support.MetricType;
/** /**
* JMX Metrics for B-tree index counters * JMX Metrics for B-tree index counters
* *
* @author Mark Pollack * @author Mark Pollack
*/ */
@ManagedResource(description = "Btree Metrics") @ManagedResource(description = "Btree Metrics")
public class BtreeIndexCounters extends AbstractMonitor { public class BtreeIndexCounters extends AbstractMonitor {
public BtreeIndexCounters(Mongo mongo) { public BtreeIndexCounters(Mongo mongo) {
this.mongo = mongo; this.mongo = mongo;
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Accesses") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Accesses")
public int getAccesses() { public int getAccesses() {
return getBtree("accesses"); return getBtree("accesses");
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Hits") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Hits")
public int getHits() { public int getHits() {
return getBtree("hits"); return getBtree("hits");
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Misses") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Misses")
public int getMisses() { public int getMisses() {
return getBtree("misses"); return getBtree("misses");
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Resets") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Resets")
public int getResets() { public int getResets() {
return getBtree("resets"); return getBtree("resets");
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Miss Ratio") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Miss Ratio")
public int getMissRatio() { public int getMissRatio() {
return getBtree("missRatio"); return getBtree("missRatio");
} }
private int getBtree(String key) { private int getBtree(String key) {
DBObject indexCounters = (DBObject) getServerStatus().get("indexCounters"); DBObject indexCounters = (DBObject) getServerStatus().get("indexCounters");
if (indexCounters.get("note") != null) { if (indexCounters.get("note") != null) {
String message = (String) indexCounters.get("note"); String message = (String) indexCounters.get("note");
if (message.contains("not supported")) { if (message.contains("not supported")) {
return -1; return -1;
} }
} }
DBObject btree = (DBObject) indexCounters.get("btree"); DBObject btree = (DBObject) indexCounters.get("btree");
// Class c = btree.get(key).getClass(); // Class c = btree.get(key).getClass();
return (Integer) btree.get(key); return (Integer) btree.get(key);
} }
} }

View File

@@ -1,53 +1,53 @@
/* /*
* Copyright 2002-2011 the original author or authors. * Copyright 2002-2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.monitor; package org.springframework.data.mongodb.monitor;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.Mongo; import com.mongodb.Mongo;
import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedMetric;
import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.jmx.support.MetricType; import org.springframework.jmx.support.MetricType;
/** /**
* JMX Metrics for Connections * JMX Metrics for Connections
* *
* @author Mark Pollack * @author Mark Pollack
*/ */
@ManagedResource(description = "Connection metrics") @ManagedResource(description = "Connection metrics")
public class ConnectionMetrics extends AbstractMonitor { public class ConnectionMetrics extends AbstractMonitor {
public ConnectionMetrics(Mongo mongo) { public ConnectionMetrics(Mongo mongo) {
this.mongo = mongo; this.mongo = mongo;
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Current Connections") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Current Connections")
public int getCurrent() { public int getCurrent() {
return getConnectionData("current", java.lang.Integer.class); return getConnectionData("current", java.lang.Integer.class);
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Available Connections") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Available Connections")
public int getAvailable() { public int getAvailable() {
return getConnectionData("available", java.lang.Integer.class); return getConnectionData("available", java.lang.Integer.class);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private <T> T getConnectionData(String key, Class<T> targetClass) { private <T> T getConnectionData(String key, Class<T> targetClass) {
DBObject mem = (DBObject) getServerStatus().get("connections"); DBObject mem = (DBObject) getServerStatus().get("connections");
// Class c = mem.get(key).getClass(); // Class c = mem.get(key).getClass();
return (T) mem.get(key); return (T) mem.get(key);
} }
} }

View File

@@ -1,77 +1,77 @@
/* /*
* Copyright 2002-2011 the original author or authors. * Copyright 2002-2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.monitor; package org.springframework.data.mongodb.monitor;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.Mongo; import com.mongodb.Mongo;
import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedMetric;
import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.jmx.support.MetricType; import org.springframework.jmx.support.MetricType;
/** /**
* JMX Metrics for Global Locks * JMX Metrics for Global Locks
* *
* @author Mark Pollack * @author Mark Pollack
*/ */
@ManagedResource(description = "Global Lock Metrics") @ManagedResource(description = "Global Lock Metrics")
public class GlobalLockMetrics extends AbstractMonitor { public class GlobalLockMetrics extends AbstractMonitor {
public GlobalLockMetrics(Mongo mongo) { public GlobalLockMetrics(Mongo mongo) {
this.mongo = mongo; this.mongo = mongo;
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Total time") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Total time")
public double getTotalTime() { public double getTotalTime() {
return getGlobalLockData("totalTime", java.lang.Double.class); return getGlobalLockData("totalTime", java.lang.Double.class);
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Lock time", unit = "s") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Lock time", unit = "s")
public double getLockTime() { public double getLockTime() {
return getGlobalLockData("lockTime", java.lang.Double.class); return getGlobalLockData("lockTime", java.lang.Double.class);
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Lock time") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Lock time")
public double getLockTimeRatio() { public double getLockTimeRatio() {
return getGlobalLockData("ratio", java.lang.Double.class); return getGlobalLockData("ratio", java.lang.Double.class);
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Current Queue") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Current Queue")
public int getCurrentQueueTotal() { public int getCurrentQueueTotal() {
return getCurrentQueue("total"); return getCurrentQueue("total");
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Reader Queue") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Reader Queue")
public int getCurrentQueueReaders() { public int getCurrentQueueReaders() {
return getCurrentQueue("readers"); return getCurrentQueue("readers");
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Writer Queue") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Writer Queue")
public int getCurrentQueueWriters() { public int getCurrentQueueWriters() {
return getCurrentQueue("writers"); return getCurrentQueue("writers");
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private <T> T getGlobalLockData(String key, Class<T> targetClass) { private <T> T getGlobalLockData(String key, Class<T> targetClass) {
DBObject globalLock = (DBObject) getServerStatus().get("globalLock"); DBObject globalLock = (DBObject) getServerStatus().get("globalLock");
return (T) globalLock.get(key); return (T) globalLock.get(key);
} }
private int getCurrentQueue(String key) { private int getCurrentQueue(String key) {
DBObject globalLock = (DBObject) getServerStatus().get("globalLock"); DBObject globalLock = (DBObject) getServerStatus().get("globalLock");
DBObject currentQueue = (DBObject) globalLock.get("currentQueue"); DBObject currentQueue = (DBObject) globalLock.get("currentQueue");
return (Integer) currentQueue.get(key); return (Integer) currentQueue.get(key);
} }
} }

View File

@@ -1,68 +1,68 @@
/* /*
* Copyright 2002-2011 the original author or authors. * Copyright 2002-2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.monitor; package org.springframework.data.mongodb.monitor;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.Mongo; import com.mongodb.Mongo;
import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedMetric;
import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.jmx.support.MetricType; import org.springframework.jmx.support.MetricType;
/** /**
* JMX Metrics for Memory * JMX Metrics for Memory
* *
* @author Mark Pollack * @author Mark Pollack
*/ */
@ManagedResource(description = "Memory Metrics") @ManagedResource(description = "Memory Metrics")
public class MemoryMetrics extends AbstractMonitor { public class MemoryMetrics extends AbstractMonitor {
public MemoryMetrics(Mongo mongo) { public MemoryMetrics(Mongo mongo) {
this.mongo = mongo; this.mongo = mongo;
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Memory address size") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Memory address size")
public int getBits() { public int getBits() {
return getMemData("bits", java.lang.Integer.class); return getMemData("bits", java.lang.Integer.class);
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Resident in Physical Memory", unit = "MB") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Resident in Physical Memory", unit = "MB")
public int getResidentSpace() { public int getResidentSpace() {
return getMemData("resident", java.lang.Integer.class); return getMemData("resident", java.lang.Integer.class);
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Virtual Address Space", unit = "MB") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Virtual Address Space", unit = "MB")
public int getVirtualAddressSpace() { public int getVirtualAddressSpace() {
return getMemData("virtual", java.lang.Integer.class); return getMemData("virtual", java.lang.Integer.class);
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Is memory info supported on this platform") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Is memory info supported on this platform")
public boolean getMemoryInfoSupported() { public boolean getMemoryInfoSupported() {
return getMemData("supported", java.lang.Boolean.class); return getMemData("supported", java.lang.Boolean.class);
} }
@ManagedMetric(metricType = MetricType.GAUGE, displayName = "Memory Mapped Space", unit = "MB") @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Memory Mapped Space", unit = "MB")
public int getMemoryMappedSpace() { public int getMemoryMappedSpace() {
return getMemData("mapped", java.lang.Integer.class); return getMemData("mapped", java.lang.Integer.class);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private <T> T getMemData(String key, Class<T> targetClass) { private <T> T getMemData(String key, Class<T> targetClass) {
DBObject mem = (DBObject) getServerStatus().get("mem"); DBObject mem = (DBObject) getServerStatus().get("mem");
// Class c = mem.get(key).getClass(); // Class c = mem.get(key).getClass();
return (T) mem.get(key); return (T) mem.get(key);
} }
} }

View File

@@ -1,70 +1,70 @@
/* /*
* Copyright 2002-2011 the original author or authors. * Copyright 2002-2011 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.monitor; package org.springframework.data.mongodb.monitor;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.Mongo; import com.mongodb.Mongo;
import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedMetric;
import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.jmx.support.MetricType; import org.springframework.jmx.support.MetricType;
/** /**
* JMX Metrics for Operation counters * JMX Metrics for Operation counters
* *
* @author Mark Pollack * @author Mark Pollack
*/ */
@ManagedResource(description = "Operation Counters") @ManagedResource(description = "Operation Counters")
public class OperationCounters extends AbstractMonitor { public class OperationCounters extends AbstractMonitor {
public OperationCounters(Mongo mongo) { public OperationCounters(Mongo mongo) {
this.mongo = mongo; this.mongo = mongo;
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Insert operation count") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Insert operation count")
public int getInsertCount() { public int getInsertCount() {
return getOpCounter("insert"); return getOpCounter("insert");
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Query operation count") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Query operation count")
public int getQueryCount() { public int getQueryCount() {
return getOpCounter("query"); return getOpCounter("query");
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Update operation count") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Update operation count")
public int getUpdateCount() { public int getUpdateCount() {
return getOpCounter("update"); return getOpCounter("update");
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Delete operation count") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Delete operation count")
public int getDeleteCount() { public int getDeleteCount() {
return getOpCounter("delete"); return getOpCounter("delete");
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "GetMore operation count") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "GetMore operation count")
public int getGetMoreCount() { public int getGetMoreCount() {
return getOpCounter("getmore"); return getOpCounter("getmore");
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Command operation count") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Command operation count")
public int getCommandCount() { public int getCommandCount() {
return getOpCounter("command"); return getOpCounter("command");
} }
private int getOpCounter(String key) { private int getOpCounter(String key) {
DBObject opCounters = (DBObject) getServerStatus().get("opcounters"); DBObject opCounters = (DBObject) getServerStatus().get("opcounters");
return (Integer) opCounters.get(key); return (Integer) opCounters.get(key);
} }
} }

View File

@@ -1,76 +1,76 @@
/* /*
* Copyright 2012-2015 the original author or authors. * Copyright 2012-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.mongodb.monitor; package org.springframework.data.mongodb.monitor;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedMetric;
import org.springframework.jmx.export.annotation.ManagedOperation; import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.jmx.support.MetricType; import org.springframework.jmx.support.MetricType;
import com.mongodb.Mongo; import com.mongodb.Mongo;
/** /**
* Expose basic server information via JMX * Expose basic server information via JMX
* *
* @author Mark Pollack * @author Mark Pollack
* @author Thomas Darimont * @author Thomas Darimont
* @author Christoph Strobl * @author Christoph Strobl
*/ */
@ManagedResource(description = "Server Information") @ManagedResource(description = "Server Information")
public class ServerInfo extends AbstractMonitor { public class ServerInfo extends AbstractMonitor {
public ServerInfo(Mongo mongo) { public ServerInfo(Mongo mongo) {
this.mongo = mongo; this.mongo = mongo;
} }
/** /**
* Returns the hostname of the used server reported by MongoDB. * Returns the hostname of the used server reported by MongoDB.
* *
* @return the reported hostname can also be an IP address. * @return the reported hostname can also be an IP address.
* @throws UnknownHostException * @throws UnknownHostException
*/ */
@ManagedOperation(description = "Server host name") @ManagedOperation(description = "Server host name")
public String getHostName() throws UnknownHostException { public String getHostName() throws UnknownHostException {
/* /*
* UnknownHostException is not necessary anymore, but clients could have * UnknownHostException is not necessary anymore, but clients could have
* called this method in a try..catch(UnknownHostException) already * called this method in a try..catch(UnknownHostException) already
*/ */
return mongo.getAddress().getHost(); return mongo.getAddress().getHost();
} }
@ManagedMetric(displayName = "Uptime Estimate") @ManagedMetric(displayName = "Uptime Estimate")
public double getUptimeEstimate() { public double getUptimeEstimate() {
return (Double) getServerStatus().get("uptimeEstimate"); return (Double) getServerStatus().get("uptimeEstimate");
} }
@ManagedOperation(description = "MongoDB Server Version") @ManagedOperation(description = "MongoDB Server Version")
public String getVersion() { public String getVersion() {
return (String) getServerStatus().get("version"); return (String) getServerStatus().get("version");
} }
@ManagedOperation(description = "Local Time") @ManagedOperation(description = "Local Time")
public String getLocalTime() { public String getLocalTime() {
return (String) getServerStatus().get("localTime"); return (String) getServerStatus().get("localTime");
} }
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Server uptime in seconds", unit = "seconds") @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Server uptime in seconds", unit = "seconds")
public double getUptime() { public double getUptime() {
return (Double) getServerStatus().get("uptime"); return (Double) getServerStatus().get("uptime");
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" <beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd"> xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans> </beans>