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

@@ -1,33 +0,0 @@
/*
* 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;
public abstract class AbstractDocumentStoreTemplate<C> {
public abstract C getConnection();
public <T> T execute(DocumentStoreConnectionCallback<C, T> action) {
try {
return action.doInConnection(getConnection());
}
catch (Exception e) {
throw new UncategorizedDocumentStoreException("Failure executing using datastore connection", e);
}
}
}

View File

@@ -1,29 +0,0 @@
/*
* 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;
/**
* Class used to map a Document to a business object.
*
* @author Thomas Risberg
* @since 1.0
*/
public interface DocumentMapper<D, T> {
T mapDocument(D document);
}

View File

@@ -1,29 +0,0 @@
/*
* 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;
/**
* Class used to map a business object to an object providing the source data for a Document.
*
* @author Thomas Risberg
* @since 1.0
*/
public interface DocumentSource<D> {
D getDocument();
}

View File

@@ -1,22 +0,0 @@
/*
* 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;
public interface DocumentStoreConnectionCallback<C, T> {
T doInConnection(C con) throws Exception;
}

View File

@@ -1,31 +0,0 @@
/*
* 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;
import org.springframework.dao.InvalidDataAccessApiUsageException;
public class InvalidDocumentStoreApiUageException extends InvalidDataAccessApiUsageException {
public InvalidDocumentStoreApiUageException(String msg) {
super(msg);
}
public InvalidDocumentStoreApiUageException(String msg, Throwable cause) {
super(msg, cause);
}
}

View File

@@ -1,27 +0,0 @@
/*
* 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;
import org.springframework.dao.UncategorizedDataAccessException;
public class UncategorizedDocumentStoreException extends UncategorizedDataAccessException {
public UncategorizedDocumentStoreException(String msg, Throwable cause) {
super(msg, cause);
}
}

View File

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

View File

@@ -1,96 +0,0 @@
/*
* 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.couchdb;
import org.jcouchdb.db.Database;
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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Convenient factory for configuring MongoDB.
*
* @author Thomas Risberg
* @since 1.0
*/
public class CouchDbFactoryBean implements FactoryBean<Database>, InitializingBean,
PersistenceExceptionTranslator {
/**
* Logger, available to subclasses.
*/
protected final Log logger = LogFactory.getLog(getClass());
private String host;
private Integer port;
private String databaseName;
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 Database getObject() throws Exception {
Assert.hasText(host, "Host must not be empty");
Assert.hasText(databaseName, "Database name must not be empty");
if (port == null) {
return new Database(host, databaseName);
}
else {
return new Database(host, port, databaseName);
}
}
public Class<? extends Database> getObjectType() {
return Database.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 (host == null) {
logger.warn("Property host not specified. Using default 'localhost'");
databaseName = "localhost";
}
if (databaseName == null) {
logger.warn("Property databaseName not specified. Using default name 'test'");
databaseName = "test";
}
}
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
logger.debug("Translating " + ex);
return CouchDbUtils.translateCouchExceptionIfPossible(ex);
}
}

View File

@@ -1,57 +0,0 @@
/*
* 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.couchdb;
import org.jcouchdb.exception.CouchDBException;
import org.springframework.dao.DataAccessException;
import org.springframework.datastore.document.UncategorizedDocumentStoreException;
/**
* 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 CouchDbUtils {
/**
* 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 translateCouchExceptionIfPossible(RuntimeException ex) {
// Check for well-known MongoException subclasses.
// All other MongoExceptions
if (ex instanceof CouchDBException) {
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

@@ -1,8 +0,0 @@
package org.springframework.datastore.document.couchdb;
import org.jcouchdb.document.BaseDocument;
import org.springframework.datastore.document.DocumentSource;
public interface CouchDocumentSource extends DocumentSource<BaseDocument> {
}

View File

@@ -1,54 +0,0 @@
/*
* 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.couchdb;
import org.jcouchdb.db.Database;
import org.jcouchdb.document.BaseDocument;
import org.springframework.datastore.document.AbstractDocumentStoreTemplate;
import org.springframework.datastore.document.DocumentSource;
public class CouchTemplate extends AbstractDocumentStoreTemplate<Database> {
private Database database;
public CouchTemplate() {
super();
}
public CouchTemplate(String host, String databaseName) {
super();
database = new Database(host, databaseName);
}
public CouchTemplate(Database database) {
super();
this.database = database;
}
public void save(DocumentSource<BaseDocument> documentSource) {
BaseDocument d = documentSource.getDocument();
getConnection().createDocument(d);
}
@Override
public Database getConnection() {
return database;
}
}

View File

@@ -1,11 +0,0 @@
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

@@ -1,145 +0,0 @@
/*
* 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

@@ -1,120 +0,0 @@
/*
* 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

@@ -1,108 +0,0 @@
/*
* 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

@@ -1,58 +0,0 @@
/*
* 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

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

View File

@@ -1,151 +0,0 @@
/*
* 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

@@ -1,25 +0,0 @@
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

@@ -1,146 +0,0 @@
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

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

View File

@@ -1,14 +0,0 @@
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

@@ -1,31 +0,0 @@
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

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

View File

@@ -1,53 +0,0 @@
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

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

@@ -0,0 +1,178 @@
/* stylesheet.css 2008/04/22 nicolekonicki */
/*
*
* Spring-specific Javadoc style sheet
*
*/
.code
{
border: 1px solid black;
background-color: #F4F4F4;
padding: 5px;
}
body
{
font: 12px Verdana, Arial, Helvetica, "Bitstream Vera Sans", sans-serif;
background-color: #fff;
color: #333;
}
/* Link colors */
a
{
color:#2c7b14;
text-decoration:none;
}
a:hover
{
text-decoration:underline;
}
/* Headings */
h1
{
font-size:28px;
color:#007c00;
}
/* Table colors */
table
{
border:none;
}
td
{
border:none;
border-bottom:1px dotted #ddd;
}
th
{
border:none;
}
.TableHeadingColor th
{
background-color: #efffcb;
background-image: url(doc-files/th-background.png);
background-repeat: repeat-x;
color:#fff;
font-size:14px;
height:26px;
}
.TableSubHeadingColor
{
background: #f7ffee;
}
.TableRowColor
{
background: #fff;
}
.TableRowColor a
{
border-bottom:none;
color:#2c7b14;
font-weight:normal;
}
tr.TableRowColor:hover
{
background:#eef2e1;
}
/* Font used in left-hand frame lists */
.FrameTitleFont
{
font-size: 120%;
font-weight:bold;
}
.FrameTitleFont a
{
color: #333;
}
.FrameHeadingFont
{
font-weight: bold;
font-size:95%;
}
.FrameItemFont
{
line-height:130%;
font-size: 95%;
}
.FrameItemFont a
{
color:#333;
}
.FrameItemFont a:hover
{
color:#249901;
border-bottom:none;
text-decoration:underline;
}
/* Navigation bar fonts and colors */
.NavBarCell1
{
background-color:#fff;
border:none;
}
.NavBarCell1Rev
{
background-color:#e3faa5;
border:1px solid #9ad00c;
padding:0;
margin:0;
}
.NavBarCell1 a
{
color:#333;
text-decoration:none;
}
.NavBarFont1Rev
{
}
.NavBarCell2
{
border:none;
}
.NavBarCell2 a
{
color:#249901;
font-size:90%;
}
.NavBarCell3
{
border:none;
}
/* Override sizes in font tags */
font
{
font: inherit !important;
}

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@@ -0,0 +1,5 @@
Spring Datastore Document 1.0.0 Milestone 1 (?, 2010)
=============================================
New Features
* Lot's of good stuff

View File

@@ -0,0 +1,21 @@
========================================================================
== NOTICE file corresponding to section 4 d of the Apache License, ==
== Version 2.0, in this case for the Spring Integration distribution. ==
========================================================================
This product includes software developed by
the Apache Software Foundation (http://www.apache.org).
The end-user documentation included with a redistribution, if any,
must include the following acknowledgement:
"This product includes software developed by the Spring Framework
Project (http://www.springframework.org)."
Alternatively, this acknowledgement may appear in the software itself,
if and wherever such third-party acknowledgements normally appear.
The names "Spring", "Spring Framework", and "Spring Data" must
not be used to endorse or promote products derived from this software
without prior written permission. For written permission, please contact
enquiries@springsource.com.

View File

@@ -0,0 +1,17 @@
SPRING DATASTORE DOCUMENT 1.0.0 M1 (? ? 2010)
-------------------------------------------------
Spring Datastore Document is released under the terms of the Apache Software License Version 2.0 (see license.txt).
DISTRIBUTION CONTENTS:
The JARs are available in the 'dist' directory, and the source JARs are in the 'src' directory.
The reference manual and javadoc are located in the 'docs' directory.
ADDITIONAL RESOURCES:
Spring Data Homepage: http://www.springsource.org/spring-data
Spring Data Forum: http://forum.springsource.org/forumdisplay.php?f=??