Switched to use new project layout; updated build; moved things around

This commit is contained in:
Thomas Risberg
2010-10-06 15:02:01 -04:00
parent 7e8b597108
commit c981b6a5e2
89 changed files with 3810 additions and 93 deletions

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java"/>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"/>
<classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
<classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>spring-datastore-mongodb</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.maven.ide.eclipse.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.maven.ide.eclipse.maven2Nature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,6 @@
#Wed Oct 06 14:49:48 EDT 2010
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.5

View File

@@ -0,0 +1,9 @@
#Wed Oct 06 14:49:46 EDT 2010
activeProfiles=
eclipse.preferences.version=1
fullBuildGoals=process-test-resources
includeModules=false
resolveWorkspaceProjects=true
resourceFilterGoals=process-resources resources\:testResources
skipCompilerPlugin=true
version=1

View File

@@ -0,0 +1,103 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-datastore-document-parent</artifactId>
<version>1.0.0.BUILD-SNAPSHOT</version>
<relativePath>../spring-datastore-document-parent/pom.xml</relativePath>
</parent>
<artifactId>spring-datastore-mongodb</artifactId>
<packaging>jar</packaging>
<name>Spring Datastore MongoDB Support</name>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<!-- Spring Data -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-datastore-document-core</artifactId>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<!-- MongoDB -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>com.springsource.bundlor</groupId>
<artifactId>com.springsource.bundlor.maven</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,11 @@
package org.springframework.datastore.document.mongodb;
import org.springframework.dao.DataAccessResourceFailureException;
public class CannotGetMongoDbConnectionException extends DataAccessResourceFailureException {
public CannotGetMongoDbConnectionException(String msg, Throwable cause) {
super(msg, cause);
}
}

View File

@@ -0,0 +1,145 @@
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.datastore.document.mongodb;
import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.NotWritablePropertyException;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.datastore.document.DocumentMapper;
import org.springframework.util.Assert;
import com.mongodb.DBObject;
/**
* Class used to map properties of a Document to the corresponding properties of a business object.
*
* @author Thomas Risberg
* @since 1.0
*/
public class MongoBeanPropertyDocumentMapper<T> implements DocumentMapper<DBObject, T> {
/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());
/** The class we are mapping to */
private Class<T> mappedClass;
/** Map of the fields we provide mapping for */
private Map<String, PropertyDescriptor> mappedFields;
/** Set of bean properties we provide mapping for */
private Set<String> mappedProperties;
public MongoBeanPropertyDocumentMapper(Class<T> mappedClass) {
initialize(mappedClass);
}
public T mapDocument(DBObject document) {
Assert.state(this.mappedClass != null, "Mapped class was not specified");
T mappedObject = BeanUtils.instantiate(this.mappedClass);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
initBeanWrapper(bw);
Set<String> keys = document.keySet();
for (String key : keys) {
String keyToUse = ("_id".equals(key) ? "id" : key);
PropertyDescriptor pd = this.mappedFields.get(keyToUse);
if (pd != null) {
try {
Object value = document.get(key);
try {
if (value instanceof ObjectId) {
bw.setPropertyValue(pd.getName(), ((ObjectId)value).toString());
}
else {
bw.setPropertyValue(pd.getName(), value);
}
}
catch (TypeMismatchException e) {
logger.warn("Intercepted TypeMismatchException for " + key + "' with value " + value +
" when setting property '" + pd.getName() + "' of type " + pd.getPropertyType() +
" on object: " + mappedObject);
}
}
catch (NotWritablePropertyException ex) {
throw new DataRetrievalFailureException(
"Unable to map key " + key + " to property " + pd.getName(), ex);
}
}
}
return mappedObject;
}
/**
* Get the class that we are mapping to.
*/
public final Class<T> getMappedClass() {
return this.mappedClass;
}
/**
* Initialize the mapping metadata for the given class.
* @param mappedClass the mapped class.
*/
protected void initialize(Class<T> mappedClass) {
this.mappedClass = mappedClass;
this.mappedFields = new HashMap<String, PropertyDescriptor>();
this.mappedProperties = new HashSet<String>();
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
for (PropertyDescriptor pd : pds) {
if (pd.getWriteMethod() != null) {
this.mappedFields.put(pd.getName(), pd);
this.mappedProperties.add(pd.getName());
}
}
}
/**
* Initialize the given BeanWrapper to be used for row mapping.
* To be called for each row.
* <p>The default implementation is empty. Can be overridden in subclasses.
* @param bw the BeanWrapper to initialize
*/
protected void initBeanWrapper(BeanWrapper bw) {
}
/**
* Static factory method to create a new MongoBeanPropertyDocumentMapper
* (with the mapped class specified only once).
* @param mappedClass the class that document should be mapped to
*/
public static <T> MongoBeanPropertyDocumentMapper<T> newInstance(Class<T> mappedClass) {
MongoBeanPropertyDocumentMapper<T> newInstance = new MongoBeanPropertyDocumentMapper<T>(mappedClass);
return newInstance;
}
}

View File

@@ -0,0 +1,120 @@
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.datastore.document.mongodb;
import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.NotReadablePropertyException;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.datastore.document.DocumentSource;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
/**
* Class used to map properties of a Document to the corresponding properties of a business object.
*
* @author Thomas Risberg
* @since 1.0
*/
public class MongoBeanPropertyDocumentSource implements DocumentSource<DBObject> {
/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());
/** The class we are mapping to */
private Object source;
/** The class we are mapping to */
private Class<?> mappedClass;
/** Map of the fields we provide mapping for */
private Map<String, PropertyDescriptor> mappedFields;
/** Set of bean properties we provide mapping for */
private Set<String> mappedProperties;
public MongoBeanPropertyDocumentSource(Object source) {
initialize(source);
}
@SuppressWarnings("rawtypes")
public DBObject getDocument() {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this.source);
DBObject dbo = new BasicDBObject();
for (String key : this.mappedFields.keySet()) {
String keyToUse = ("id".equals(key) ? "_id" : key);
PropertyDescriptor pd = this.mappedFields.get(key);
if (pd != null) {
try {
Object value = bw.getPropertyValue(key);
if (value instanceof Enum) {
dbo.put(keyToUse, ((Enum)value).name());
}
else {
dbo.put(keyToUse, value);
}
}
catch (NotReadablePropertyException ex) {
throw new DataRetrievalFailureException(
"Unable to map property " + pd.getName() + " to key " + key, ex);
}
}
}
return dbo;
}
/**
* Initialize the mapping metadata for the given class.
* @param mappedClass the mapped class.
*/
protected void initialize(Object source) {
this.source = source;
this.mappedClass = source.getClass();
this.mappedFields = new HashMap<String, PropertyDescriptor>();
this.mappedProperties = new HashSet<String>();
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
for (PropertyDescriptor pd : pds) {
if (pd.getWriteMethod() != null) {
this.mappedFields.put(pd.getName(), pd);
this.mappedProperties.add(pd.getName());
}
}
}
/**
* Initialize the given BeanWrapper to be used for row mapping.
* To be called for each row.
* <p>The default implementation is empty. Can be overridden in subclasses.
* @param bw the BeanWrapper to initialize
*/
protected void initBeanWrapper(BeanWrapper bw) {
}
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.datastore.document.mongodb;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.util.Assert;
import com.mongodb.DB;
import com.mongodb.Mongo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Convenient factory for configuring MongoDB.
*
* @author Thomas Risberg
* @since 1.0
*/
public class MongoDbFactoryBean implements FactoryBean<DB>, InitializingBean,
PersistenceExceptionTranslator {
/**
* Logger, available to subclasses.
*/
protected final Log logger = LogFactory.getLog(getClass());
private Mongo mongo;
private String host;
private Integer port;
private String databaseName;
public void setMongo(Mongo mongo) {
this.mongo = mongo;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public void setHost(String host) {
this.host = host;
}
public void setPort(int port) {
this.port = port;
}
public DB getObject() throws Exception {
Assert.notNull(mongo, "Mongo must not be null");
Assert.hasText(databaseName, "Database name must not be empty");
return mongo.getDB(databaseName);
}
public Class<? extends DB> getObjectType() {
return DB.class;
}
public boolean isSingleton() {
return false;
}
public void afterPropertiesSet() throws Exception {
// apply defaults - convenient when used to configure for tests
// in an application context
if (databaseName == null) {
logger.warn("Property databaseName not specified. Using default name 'test'");
databaseName = "test";
}
if (mongo == null) {
logger.warn("Property mongo not specified. Using default configuration");
if (host == null) {
mongo = new Mongo();
}
else {
if (port == null) {
mongo = new Mongo(host);
}
else {
mongo = new Mongo(host, port);
}
}
}
}
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
logger.debug("Translating " + ex);
return MongoDbUtils.translateMongoExceptionIfPossible(ex);
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.datastore.document.mongodb;
import org.springframework.dao.DataAccessException;
import org.springframework.datastore.document.UncategorizedDocumentStoreException;
import com.mongodb.MongoException;
/**
* Helper class featuring helper methods for internal MongoDb classes.
*
* <p>Mainly intended for internal use within the framework.
*
* @author Thomas Risberg
* @since 1.0
*/
public class MongoDbUtils {
/**
* Convert the given runtime exception to an appropriate exception from the
* <code>org.springframework.dao</code> hierarchy.
* Return null if no translation is appropriate: any other exception may
* have resulted from user code, and should not be translated.
* @param ex runtime exception that occurred
* @return the corresponding DataAccessException instance,
* or <code>null</code> if the exception should not be translated
*/
public static DataAccessException translateMongoExceptionIfPossible(RuntimeException ex) {
// Check for well-known MongoException subclasses.
// All other MongoExceptions
if (ex instanceof MongoException) {
return new UncategorizedDocumentStoreException(ex.getMessage(), ex);
}
// If we get here, we have an exception that resulted from user code,
// rather than the persistence provider, so we return null to indicate
// that translation should not occur.
return null;
}
}

View File

@@ -0,0 +1,9 @@
package org.springframework.datastore.document.mongodb;
import org.springframework.datastore.document.DocumentSource;
import com.mongodb.DBObject;
public interface MongoDocumentSource extends DocumentSource<DBObject> {
}

View File

@@ -0,0 +1,151 @@
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.datastore.document.mongodb;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.datastore.document.AbstractDocumentStoreTemplate;
import org.springframework.datastore.document.DocumentMapper;
import org.springframework.datastore.document.DocumentSource;
import org.springframework.datastore.document.mongodb.query.Query;
import com.mongodb.CommandResult;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
import com.mongodb.WriteResult;
import com.mongodb.util.JSON;
public class MongoTemplate extends AbstractDocumentStoreTemplate<DB> {
private DB db;
// public MongoTemplate() {
// super();
// }
public MongoTemplate(DB db) {
super();
this.db = db;
}
public void execute(String command) {
execute((DBObject)JSON.parse(command));
}
public void execute(DocumentSource<DBObject> command) {
execute(command.getDocument());
}
public void execute(DBObject command) {
CommandResult cr = getConnection().command(command);
String err = cr.getErrorMessage();
if (err != null) {
throw new InvalidDataAccessApiUsageException("Command execution of " +
command.toString() + " failed: " + err);
}
}
public void createCollection(String collectionName, DocumentSource<DBObject> documentSource) {
try {
getConnection().createCollection(collectionName, documentSource.getDocument());
} catch (MongoException e) {
throw new InvalidDataAccessApiUsageException("Error creating collection " + collectionName + ": " + e.getMessage(), e);
}
}
public void dropCollection(String collectionName) {
getConnection().getCollection(collectionName)
.drop();
}
public void saveObject(String collectionName, Object source) {
MongoBeanPropertyDocumentSource docSrc = new MongoBeanPropertyDocumentSource(source);
save(collectionName, docSrc);
}
public void save(String collectionName, DocumentSource<DBObject> documentSource) {
DBObject dbDoc = documentSource.getDocument();
WriteResult wr = null;
try {
wr = getConnection().getCollection(collectionName).save(dbDoc);
} catch (MongoException e) {
throw new DataRetrievalFailureException(wr.getLastError().getErrorMessage(), e);
}
}
public <T> List<T> queryForCollection(String collectionName, Class<T> targetClass) {
DocumentMapper<DBObject, T> mapper = MongoBeanPropertyDocumentMapper.newInstance(targetClass);
return queryForCollection(collectionName, mapper);
}
public <T> List<T> queryForCollection(String collectionName, DocumentMapper<DBObject, T> mapper) {
List<T> results = new ArrayList<T>();
DBCollection collection = getConnection().getCollection(collectionName);
for (DBObject dbo : collection.find()) {
results.add(mapper.mapDocument(dbo));
}
return results;
}
public <T> List<T> queryForList(String collectionName, Query query, Class<T> targetClass) {
DocumentMapper<DBObject, T> mapper = MongoBeanPropertyDocumentMapper.newInstance(targetClass);
return queryForList(collectionName, query, mapper);
}
public <T> List<T> queryForList(String collectionName, Query query, DocumentMapper<DBObject, T> mapper) {
return queryForList(collectionName, query.getQueryObject(), mapper);
}
public <T> List<T> queryForList(String collectionName, String query, Class<T> targetClass) {
DocumentMapper<DBObject, T> mapper = MongoBeanPropertyDocumentMapper.newInstance(targetClass);
return queryForList(collectionName, query, mapper);
}
public <T> List<T> queryForList(String collectionName, String query, DocumentMapper<DBObject, T> mapper) {
return queryForList(collectionName, (DBObject)JSON.parse(query), mapper);
}
public <T> List<T> queryForList(String collectionName, DBObject query, Class<T> targetClass) {
DocumentMapper<DBObject, T> mapper = MongoBeanPropertyDocumentMapper.newInstance(targetClass);
return queryForList(collectionName, query, mapper);
}
public <T> List<T> queryForList(String collectionName, DBObject query, DocumentMapper<DBObject, T> mapper) {
DBCollection collection = getConnection().getCollection(collectionName);
List<T> results = new ArrayList<T>();
for (DBObject dbo : collection.find(query)) {
results.add(mapper.mapDocument(dbo));
}
return results;
}
public RuntimeException translateIfNecessary(RuntimeException ex) {
return MongoDbUtils.translateMongoExceptionIfPossible(ex);
}
@Override
public DB getConnection() {
return db;
}
}

View File

@@ -0,0 +1,25 @@
package org.springframework.datastore.document.mongodb.query;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
public class BasicQuery implements Query {
private DBObject dbo = null;
public BasicQuery(String query) {
super();
this.dbo = (DBObject) JSON.parse(query);
}
public BasicQuery(DBObject dbo) {
super();
this.dbo = dbo;
}
public DBObject getQueryObject() {
return dbo;
}
}

View File

@@ -0,0 +1,146 @@
package org.springframework.datastore.document.mongodb.query;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import org.springframework.datastore.document.InvalidDocumentStoreApiUageException;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
public class Criteria implements CriteriaSpec {
private QueryBuilder qb = null;
private LinkedHashMap<String, Object> criteria = new LinkedHashMap<String, Object>();
private Object isValue = null;
public Criteria(QueryBuilder qb) {
super();
this.qb = qb;
}
public Criteria and(String key) {
return qb.find(key);
}
public Criteria is(Object o) {
if (isValue != null) {
throw new InvalidDocumentStoreApiUageException("Multiple 'is' values declared.");
}
this.isValue = o;
return this;
}
public Criteria lt(Object o) {
criteria.put("$lt", o);
return this;
}
public Criteria lte(Object o) {
criteria.put("$lte", o);
return this;
}
public Criteria gt(Object o) {
criteria.put("$gt", o);
return this;
}
public Criteria gte(Object o) {
criteria.put("$gte", o);
return this;
}
public Criteria in(Object... o) {
criteria.put("$in", o);
return this;
}
public Criteria nin(Object... o) {
criteria.put("$min", o);
return this;
}
public Criteria mod(Number value, Number remainder) {
List<Object> l = new ArrayList<Object>();
l.add(value);
l.add(remainder);
criteria.put("$mod", l);
return this;
}
public Criteria all(Object o) {
criteria.put("$is", o);
return this;
}
public Criteria size(Object o) {
criteria.put("$is", o);
return this;
}
public Criteria exists(boolean b) {
return this;
}
public Criteria type(int t) {
return this;
}
public Criteria not() {
criteria.put("$not", null);
return this;
}
public Criteria regExp(String re) {
return this;
}
public void or(List<Query> queries) {
criteria.put("$or", queries);
}
public Query build() {
return qb.build();
}
/* (non-Javadoc)
* @see org.springframework.datastore.document.mongodb.query.Criteria#getCriteriaObject(java.lang.String)
*/
public DBObject getCriteriaObject(String key) {
DBObject dbo = new BasicDBObject();
boolean not = false;
for (String k : criteria.keySet()) {
if (not) {
DBObject notDbo = new BasicDBObject();
notDbo.put(k, criteria.get(k));
dbo.put("$not", notDbo);
not = false;
}
else {
if ("$not".equals(k)) {
not = true;
}
else {
dbo.put(k, criteria.get(k));
}
}
}
DBObject queryCriteria = new BasicDBObject();
if (isValue != null) {
queryCriteria.put(key, isValue);
queryCriteria.putAll(dbo);
}
else {
queryCriteria.put(key, dbo);
}
return queryCriteria;
}
}

View File

@@ -0,0 +1,9 @@
package org.springframework.datastore.document.mongodb.query;
import com.mongodb.DBObject;
public interface CriteriaSpec {
DBObject getCriteriaObject(String key);
}

View File

@@ -0,0 +1,14 @@
package org.springframework.datastore.document.mongodb.query;
public class FieldSpecification {
public FieldSpecification include(String key) {
return this;
}
public FieldSpecification exclude(String key) {
return this;
}
}

View File

@@ -0,0 +1,31 @@
package org.springframework.datastore.document.mongodb.query;
import org.bson.types.BasicBSONList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
public class OrCriteria implements CriteriaSpec {
Query[] queries = null;
public OrCriteria(Query[] queries) {
super();
this.queries = queries;
}
/* (non-Javadoc)
* @see org.springframework.datastore.document.mongodb.query.Criteria#getCriteriaObject(java.lang.String)
*/
public DBObject getCriteriaObject(String key) {
DBObject dbo = new BasicDBObject();
BasicBSONList l = new BasicBSONList();
for (Query q : queries) {
l.add(q.getQueryObject());
}
dbo.put(key, l);
return dbo;
}
}

View File

@@ -0,0 +1,10 @@
package org.springframework.datastore.document.mongodb.query;
import com.mongodb.DBObject;
public interface Query {
DBObject getQueryObject();
}

View File

@@ -0,0 +1,53 @@
package org.springframework.datastore.document.mongodb.query;
import java.util.LinkedHashMap;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
public class QueryBuilder implements Query {
private LinkedHashMap<String, CriteriaSpec> criteria = new LinkedHashMap<String, CriteriaSpec>();
public Criteria find(String key) {
Criteria c = new Criteria(this);
this.criteria.put(key, c);
return c;
}
public QueryBuilder or(Query... queries) {
this.criteria.put("$or", new OrCriteria(queries));
return this;
}
public FieldSpecification fields() {
return new FieldSpecification();
}
public SliceSpecification slice() {
return new SliceSpecification();
}
public SortSpecification sort() {
return new SortSpecification();
}
public QueryBuilder limit(int limit) {
return this;
}
public Query build() {
return this;
}
public DBObject getQueryObject() {
DBObject dbo = new BasicDBObject();
for (String k : criteria.keySet()) {
CriteriaSpec c = criteria.get(k);
DBObject cl = c.getCriteriaObject(k);
dbo.putAll(cl);
}
return dbo;
}
}

View File

@@ -0,0 +1,10 @@
package org.springframework.datastore.document.mongodb.query;
public class SliceSpecification {
public SliceSpecification on(String key, int size) {
return this;
}
}

View File

@@ -0,0 +1,14 @@
package org.springframework.datastore.document.mongodb.query;
public class SortSpecification {
public enum SortOrder {
ASCENDING, DESCENDING
}
public SortSpecification on(String key, SortOrder order) {
return this;
}
}

View File

@@ -0,0 +1,22 @@
Bundle-SymbolicName: org.springframework.datastore.document
Bundle-Name: Spring Datastore Document
Bundle-Vendor: SpringSource
Bundle-ManifestVersion: 2
Import-Package:
sun.reflect;version="0";resolution:=optional
Import-Template:
org.springframework.beans.*;version="[3.0.0, 4.0.0)",
org.springframework.core.*;version="[3.0.0, 4.0.0)",
org.springframework.dao.*;version="[3.0.0, 4.0.0)",
org.springframework.util.*;version="[3.0.0, 4.0.0)",
org.springframework.data.core.*;version="[1.0.0, 2.0.0)",
org.springframework.datastore.core.*;version="[1.0.0, 2.0.0)",
org.springframework.datastore.persistence.*;version="[1.0.0, 2.0.0)",
org.springframework.datastore.document.*;version="[1.0.0, 2.0.0)",
com.mongodb.*;version="0",
org.bson.*;version="0",
org.aopalliance.*;version="[1.0.0, 2.0.0)";resolution:=optional,
org.apache.commons.logging.*;version="[1.1.1, 2.0.0)",
org.w3c.dom.*;version="0"