Renamed packages from datastore to data
This commit is contained in:
@@ -1,14 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" output="target/classes" path="src/main/java"/>
|
||||
<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">
|
||||
<attributes>
|
||||
<attribute name="org.eclipse.jst.component.nondependency" value=""/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
|
||||
<classpathentry kind="output" path="target/classes"/>
|
||||
</classpath>
|
||||
@@ -1,9 +0,0 @@
|
||||
#Thu Oct 14 10:28:36 EDT 2010
|
||||
eclipse.preferences.version=1
|
||||
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
|
||||
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
|
||||
org.eclipse.jdt.core.compiler.compliance=1.5
|
||||
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
|
||||
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
|
||||
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
|
||||
org.eclipse.jdt.core.compiler.source=1.5
|
||||
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project-modules id="moduleCoreId" project-version="1.5.0">
|
||||
<wb-module deploy-name="spring-data-mongodb">
|
||||
<wb-resource deploy-path="/" source-path="/src/main/java"/>
|
||||
</wb-module>
|
||||
</project-modules>
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<faceted-project>
|
||||
<installed facet="java" version="1.5"/>
|
||||
<installed facet="jst.utility" version="1.0"/>
|
||||
</faceted-project>
|
||||
@@ -1,9 +0,0 @@
|
||||
#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
|
||||
@@ -1,103 +0,0 @@
|
||||
<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>
|
||||
@@ -1,3 +0,0 @@
|
||||
Manifest-Version: 1.0
|
||||
Class-Path:
|
||||
|
||||
@@ -1,26 +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.data.document.mongodb;
|
||||
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
|
||||
public class CannotGetMongoDbConnectionException extends DataAccessResourceFailureException {
|
||||
|
||||
public CannotGetMongoDbConnectionException(String msg, Throwable cause) {
|
||||
super(msg, cause);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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.data.document.mongodb;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
|
||||
import com.mongodb.DBCollection;
|
||||
import com.mongodb.MongoException;
|
||||
|
||||
public interface CollectionCallback<T> {
|
||||
|
||||
T doInCollection(DBCollection collection) throws MongoException, DataAccessException;
|
||||
|
||||
}
|
||||
@@ -1,60 +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.data.document.mongodb;
|
||||
|
||||
public class CollectionOptions {
|
||||
|
||||
private Integer maxDocuments;
|
||||
|
||||
private Integer size;
|
||||
|
||||
private Boolean capped;
|
||||
|
||||
|
||||
|
||||
public CollectionOptions(Integer size, Integer maxDocuments, Boolean capped) {
|
||||
super();
|
||||
this.maxDocuments = maxDocuments;
|
||||
this.size = size;
|
||||
this.capped = capped;
|
||||
}
|
||||
|
||||
public Integer getMaxDocuments() {
|
||||
return maxDocuments;
|
||||
}
|
||||
|
||||
public void setMaxDocuments(Integer maxDocuments) {
|
||||
this.maxDocuments = maxDocuments;
|
||||
}
|
||||
|
||||
public Integer getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
public void setSize(Integer size) {
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
public Boolean getCapped() {
|
||||
return capped;
|
||||
}
|
||||
|
||||
public void setCapped(Boolean capped) {
|
||||
this.capped = capped;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,28 +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.data.document.mongodb;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
|
||||
import com.mongodb.DB;
|
||||
import com.mongodb.DBCollection;
|
||||
import com.mongodb.MongoException;
|
||||
|
||||
public interface DBCallback<T> {
|
||||
|
||||
T doInDB(DB db) throws MongoException, DataAccessException;
|
||||
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package org.springframework.data.document.mongodb;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.springframework.transaction.support.ResourceHolderSupport;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import com.mongodb.DB;
|
||||
|
||||
public class DBHolder extends ResourceHolderSupport {
|
||||
private static final Object DEFAULT_KEY = new Object();
|
||||
|
||||
private final Map<Object, DB> dbMap = new ConcurrentHashMap<Object, DB>();
|
||||
|
||||
|
||||
public DBHolder(DB db) {
|
||||
addDB(db);
|
||||
}
|
||||
|
||||
public DBHolder(Object key, DB db) {
|
||||
addDB(key, db);
|
||||
}
|
||||
|
||||
|
||||
public DB getDB() {
|
||||
return getDB(DEFAULT_KEY);
|
||||
}
|
||||
|
||||
public DB getDB(Object key) {
|
||||
return this.dbMap.get(key);
|
||||
}
|
||||
|
||||
|
||||
public DB getAnyDB() {
|
||||
if (!this.dbMap.isEmpty()) {
|
||||
return this.dbMap.values().iterator().next();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void addDB(DB session) {
|
||||
addDB(DEFAULT_KEY, session);
|
||||
}
|
||||
|
||||
public void addDB(Object key, DB session) {
|
||||
Assert.notNull(key, "Key must not be null");
|
||||
Assert.notNull(session, "DB must not be null");
|
||||
this.dbMap.put(key, session);
|
||||
}
|
||||
|
||||
public DB removeDB(Object key) {
|
||||
return this.dbMap.remove(key);
|
||||
}
|
||||
|
||||
public boolean containsDB(DB session) {
|
||||
return this.dbMap.containsValue(session);
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return this.dbMap.isEmpty();
|
||||
}
|
||||
|
||||
public boolean doesNotHoldNonDefaultDB() {
|
||||
synchronized (this.dbMap) {
|
||||
return this.dbMap.isEmpty() ||
|
||||
(this.dbMap.size() == 1 && this.dbMap.containsKey(DEFAULT_KEY));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package org.springframework.data.document.mongodb;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DBObject;
|
||||
|
||||
public class FluentDbObject {
|
||||
|
||||
public static DBObject DbObject(Tuple... entries) {
|
||||
BasicDBObject map = new BasicDBObject();
|
||||
|
||||
for (Tuple entry : entries) {
|
||||
map.put(entry.t1, entry.t2);
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
public static Tuple pair(String o1, Object o2) {
|
||||
return new Tuple(o1, o2);
|
||||
}
|
||||
|
||||
public static class Tuple {
|
||||
private String t1;
|
||||
private Object t2;
|
||||
|
||||
public Tuple(String t1, Object t2) {
|
||||
this.t1 = t1;
|
||||
this.t2 = t2;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,21 +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.data.document.mongodb;
|
||||
|
||||
|
||||
public interface MongoConverter extends MongoWriter<Object>, MongoReader<Object> {
|
||||
|
||||
}
|
||||
@@ -1,168 +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.data.document.mongodb;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.datastore.document.UncategorizedDocumentStoreException;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import com.mongodb.DB;
|
||||
import com.mongodb.Mongo;
|
||||
import com.mongodb.MongoException;
|
||||
import com.mongodb.MongoException.DuplicateKey;
|
||||
import com.mongodb.MongoException.Network;
|
||||
|
||||
/**
|
||||
* Helper class featuring helper methods for internal MongoDb classes.
|
||||
*
|
||||
* <p>Mainly intended for internal use within the framework.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
* @author Graeme Rocher
|
||||
*
|
||||
* @since 1.0
|
||||
*/
|
||||
public class MongoDbUtils {
|
||||
|
||||
static final Log logger = LogFactory.getLog(MongoDbUtils.class);
|
||||
|
||||
/**
|
||||
* 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 DuplicateKey) {
|
||||
return new DataIntegrityViolationException(ex.getMessage(),ex);
|
||||
}
|
||||
if(ex instanceof Network) {
|
||||
return new DataAccessResourceFailureException(ex.getMessage(), ex);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
public static DB getDB(Mongo mongo, String databaseName) {
|
||||
return doGetDB(mongo, databaseName, true);
|
||||
}
|
||||
|
||||
public static DB doGetDB(Mongo mongo, String databaseName, boolean allowCreate) {
|
||||
Assert.notNull(mongo, "No Mongo instance specified");
|
||||
|
||||
DBHolder dbHolder = (DBHolder) TransactionSynchronizationManager.getResource(mongo);
|
||||
if (dbHolder != null && !dbHolder.isEmpty()) {
|
||||
// pre-bound Mongo DB
|
||||
DB db = null;
|
||||
if (TransactionSynchronizationManager.isSynchronizationActive() &&
|
||||
dbHolder.doesNotHoldNonDefaultDB()) {
|
||||
// Spring transaction management is active ->
|
||||
db = dbHolder.getDB();
|
||||
if (db != null && !dbHolder.isSynchronizedWithTransaction()) {
|
||||
logger.debug("Registering Spring transaction synchronization for existing Mongo DB");
|
||||
TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(dbHolder, mongo));
|
||||
dbHolder.setSynchronizedWithTransaction(true);
|
||||
}
|
||||
}
|
||||
if (db != null) {
|
||||
return db;
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("Opening Mongo DB");
|
||||
DB db = mongo.getDB(databaseName);
|
||||
// Use same Session for further Mongo actions within the transaction.
|
||||
// Thread object will get removed by synchronization at transaction completion.
|
||||
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
// We're within a Spring-managed transaction, possibly from JtaTransactionManager.
|
||||
logger.debug("Registering Spring transaction synchronization for new Hibernate Session");
|
||||
DBHolder holderToUse = dbHolder;
|
||||
if (holderToUse == null) {
|
||||
holderToUse = new DBHolder(db);
|
||||
}
|
||||
else {
|
||||
holderToUse.addDB(db);
|
||||
}
|
||||
TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(holderToUse, mongo));
|
||||
holderToUse.setSynchronizedWithTransaction(true);
|
||||
if (holderToUse != dbHolder) {
|
||||
TransactionSynchronizationManager.bindResource(mongo, holderToUse);
|
||||
}
|
||||
}
|
||||
|
||||
// Check whether we are allowed to return the DB.
|
||||
if (!allowCreate && !isDBTransactional(db, mongo)) {
|
||||
throw new IllegalStateException("No Mongo DB bound to thread, " +
|
||||
"and configuration does not allow creation of non-transactional one here");
|
||||
}
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Return whether the given DB instance is transactional, that is,
|
||||
* bound to the current thread by Spring's transaction facilities.
|
||||
* @param db the DB to check
|
||||
* @param mongo the Mongo instance that the DB was created with
|
||||
* (may be <code>null</code>)
|
||||
* @return whether the DB is transactional
|
||||
*/
|
||||
public static boolean isDBTransactional(DB db, Mongo mongo) {
|
||||
if (mongo == null) {
|
||||
return false;
|
||||
}
|
||||
DBHolder dbHolder =
|
||||
(DBHolder) TransactionSynchronizationManager.getResource(mongo);
|
||||
return (dbHolder != null && dbHolder.containsDB(db));
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform actual closing of the Mongo DB object,
|
||||
* catching and logging any cleanup exceptions thrown.
|
||||
* @param db the DB to close (may be <code>null</code>)
|
||||
*/
|
||||
public static void closeDB(DB db) {
|
||||
if (db != null) {
|
||||
logger.debug("Closing Mongo DB object");
|
||||
try {
|
||||
db.requestDone();
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
logger.debug("Unexpected exception on closing Mongo DB object", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,24 +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.data.document.mongodb;
|
||||
|
||||
import org.springframework.datastore.document.DocumentSource;
|
||||
|
||||
import com.mongodb.DBObject;
|
||||
|
||||
public interface MongoDocumentSource extends DocumentSource<DBObject> {
|
||||
|
||||
}
|
||||
@@ -1,20 +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.data.document.mongodb;
|
||||
|
||||
public interface MongoDocumentWriter {
|
||||
|
||||
}
|
||||
@@ -1,23 +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.data.document.mongodb;
|
||||
|
||||
import com.mongodb.DBObject;
|
||||
|
||||
public interface MongoReader<T> {
|
||||
|
||||
T read(Class<? extends T> clazz, DBObject dbo);
|
||||
}
|
||||
@@ -1,20 +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.data.document.mongodb;
|
||||
|
||||
public interface MongoReaderWriter<T> extends MongoWriter<T>, MongoReader<T> {
|
||||
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package org.springframework.data.document.mongodb;
|
||||
|
||||
import org.springframework.transaction.support.ResourceHolder;
|
||||
import org.springframework.transaction.support.ResourceHolderSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
|
||||
public class MongoSynchronization extends ResourceHolderSynchronization
|
||||
implements TransactionSynchronization {
|
||||
|
||||
public MongoSynchronization(ResourceHolder resourceHolder,
|
||||
Object resourceKey) {
|
||||
super(resourceHolder, resourceKey);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,313 +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.data.document.mongodb;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.dao.DataRetrievalFailureException;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.data.document.mongodb.query.Query;
|
||||
import org.springframework.datastore.document.AbstractDocumentStoreTemplate;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.CommandResult;
|
||||
import com.mongodb.DB;
|
||||
import com.mongodb.DBCollection;
|
||||
import com.mongodb.DBObject;
|
||||
import com.mongodb.Mongo;
|
||||
import com.mongodb.MongoException;
|
||||
import com.mongodb.WriteResult;
|
||||
import com.mongodb.util.JSON;
|
||||
|
||||
public class MongoTemplate extends AbstractDocumentStoreTemplate<DB> implements InitializingBean {
|
||||
|
||||
private DB db;
|
||||
|
||||
private String defaultCollectionName;
|
||||
|
||||
private MongoConverter mongoConverter;
|
||||
|
||||
//TODO expose configuration...
|
||||
private CollectionOptions defaultCollectionOptions;
|
||||
|
||||
private Mongo mongo;
|
||||
|
||||
private String databaseName;
|
||||
|
||||
|
||||
public MongoTemplate(Mongo mongo, String databaseName) {
|
||||
this(mongo, databaseName, null, null);
|
||||
}
|
||||
|
||||
public MongoTemplate(Mongo mongo, String databaseName, String defaultCollectionName) {
|
||||
this(mongo, databaseName, defaultCollectionName, null);
|
||||
}
|
||||
|
||||
public MongoTemplate(Mongo mongo, String databaseName, MongoConverter mongoConverter) {
|
||||
this(mongo, databaseName, null, mongoConverter);
|
||||
}
|
||||
|
||||
public MongoTemplate(Mongo mongo, String databaseName, String defaultCollectionName, MongoConverter mongoConverter) {
|
||||
this.mongoConverter = mongoConverter;
|
||||
this.defaultCollectionName = defaultCollectionName;
|
||||
this.mongo = mongo;
|
||||
this.databaseName = databaseName;
|
||||
}
|
||||
|
||||
public void setDefaultCollectionName(String defaultCollectionName) {
|
||||
this.defaultCollectionName = defaultCollectionName;
|
||||
}
|
||||
|
||||
public void setDatabaseName(String databaseName) {
|
||||
this.databaseName = databaseName;
|
||||
}
|
||||
|
||||
public String getDefaultCollectionName() {
|
||||
return defaultCollectionName;
|
||||
}
|
||||
|
||||
|
||||
public void executeCommand(String jsonCommand) {
|
||||
executeCommand((DBObject)JSON.parse(jsonCommand));
|
||||
}
|
||||
|
||||
public void executeCommand(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 <T> T executeInSession(DBCallback<T> action) {
|
||||
DB db = getConnection();
|
||||
db.requestStart();
|
||||
try {
|
||||
return action.doInDB(db);
|
||||
} catch (MongoException e) {
|
||||
//TODO refine exception thrown to capture last error.
|
||||
CommandResult result = db.getLastError();
|
||||
throw new InvalidDataAccessApiUsageException("Error accessing DB " + db + ":" + e.getMessage(), e);
|
||||
} finally {
|
||||
db.requestDone();
|
||||
}
|
||||
}
|
||||
|
||||
public DBCollection createCollection(String collectionName) {
|
||||
try {
|
||||
return getConnection().createCollection(collectionName, null);
|
||||
} catch (MongoException e) {
|
||||
throw new InvalidDataAccessApiUsageException("Error creating collection " + collectionName + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public void createCollection(String collectionName, CollectionOptions collectionOptions) {
|
||||
try {
|
||||
getConnection().createCollection(collectionName, convertToDbObject(collectionOptions));
|
||||
} catch (MongoException e) {
|
||||
throw new InvalidDataAccessApiUsageException("Error creating collection " + collectionName + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public DBCollection getCollection(String collectionName) {
|
||||
try {
|
||||
return getConnection().getCollection(collectionName);
|
||||
} catch (MongoException e) {
|
||||
throw new InvalidDataAccessApiUsageException("Error creating collection " + collectionName + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public boolean collectionExists(String collectionName) {
|
||||
try {
|
||||
return getConnection().collectionExists(collectionName);
|
||||
} catch (MongoException e) {
|
||||
throw new InvalidDataAccessApiUsageException("Error creating collection " + collectionName + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public void dropCollection(String collectionName) {
|
||||
getConnection().getCollection(collectionName)
|
||||
.drop();
|
||||
}
|
||||
|
||||
|
||||
private String getRequiredDefaultCollectionName() {
|
||||
String name = getDefaultCollectionName();
|
||||
if (name == null) {
|
||||
throw new IllegalStateException(
|
||||
"No 'defaultCollection' or 'defaultCollectionName' specified. Check configuration of MongoTemplate.");
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
|
||||
public void save(Object objectToSave) {
|
||||
save(getRequiredDefaultCollectionName(), objectToSave);
|
||||
}
|
||||
|
||||
public void save(String collectionName, Object objectToSave) {
|
||||
BasicDBObject dbDoc = new BasicDBObject();
|
||||
this.mongoConverter.write(objectToSave, dbDoc);
|
||||
saveDBObject(collectionName, dbDoc);
|
||||
}
|
||||
|
||||
public <T> void save(String collectionName, T objectToSave, MongoWriter<T> writer) {
|
||||
BasicDBObject dbDoc = new BasicDBObject();
|
||||
this.mongoConverter.write(objectToSave, dbDoc);
|
||||
saveDBObject(collectionName, dbDoc);
|
||||
}
|
||||
|
||||
|
||||
protected void saveDBObject(String collectionName, BasicDBObject dbDoc) {
|
||||
if (dbDoc.keySet().size() > 0 ) {
|
||||
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(Class<T> targetClass) {
|
||||
|
||||
List<T> results = new ArrayList<T>();
|
||||
DBCollection collection = getConnection().getCollection(getDefaultCollectionName());
|
||||
for (DBObject dbo : collection.find()) {
|
||||
Object obj = mongoConverter.read(targetClass, dbo);
|
||||
//effectively acts as a query on the collection restricting it to elements of a specific type
|
||||
if (targetClass.isInstance(obj)) {
|
||||
results.add(targetClass.cast(obj));
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public <T> List<T> queryForCollection(String collectionName, Class<T> targetClass) {
|
||||
|
||||
List<T> results = new ArrayList<T>();
|
||||
DBCollection collection = getConnection().getCollection(collectionName);
|
||||
for (DBObject dbo : collection.find()) {
|
||||
Object obj = mongoConverter.read(targetClass, dbo);
|
||||
//effectively acts as a query on the collection restricting it to elements of a specific type
|
||||
if (targetClass.isInstance(obj)) {
|
||||
results.add(targetClass.cast(obj));
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public <T> List<T> queryForCollection(String collectionName, Class<T> targetClass, MongoReader<T> reader) {
|
||||
List<T> results = new ArrayList<T>();
|
||||
DBCollection collection = getConnection().getCollection(collectionName);
|
||||
for (DBObject dbo : collection.find()) {
|
||||
results.add(reader.read(targetClass, dbo));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
|
||||
public <T> List<T> queryForList(String collectionName, Query query, Class<T> targetClass) {
|
||||
return queryForList(collectionName, query.getQueryObject(), targetClass);
|
||||
}
|
||||
|
||||
public <T> List<T> queryForList(String collectionName, Query query, Class<T> targetClass, MongoReader<T> reader) {
|
||||
return queryForList(collectionName, query.getQueryObject(), targetClass, reader);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public <T> List<T> queryForList(String collectionName, String query, Class<T> targetClass) {
|
||||
return queryForList(collectionName, (DBObject)JSON.parse(query), targetClass);
|
||||
}
|
||||
|
||||
public <T> List<T> queryForList(String collectionName, String query, Class<T> targetClass, MongoReader<T> reader) {
|
||||
return queryForList(collectionName, (DBObject)JSON.parse(query), targetClass, reader);
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
|
||||
public <T> List<T> queryForList(String collectionName, DBObject query, Class<T> targetClass) {
|
||||
DBCollection collection = getConnection().getCollection(collectionName);
|
||||
List<T> results = new ArrayList<T>();
|
||||
for (DBObject dbo : collection.find(query)) {
|
||||
Object obj = mongoConverter.read(targetClass,dbo);
|
||||
//effectively acts as a query on the collection restricting it to elements of a specific type
|
||||
if (targetClass.isInstance(obj)) {
|
||||
results.add(targetClass.cast(obj));
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public <T> List<T> queryForList(String collectionName, DBObject query, Class<T> targetClass, MongoReader<T> reader) {
|
||||
DBCollection collection = getConnection().getCollection(collectionName);
|
||||
List<T> results = new ArrayList<T>();
|
||||
for (DBObject dbo : collection.find(query)) {
|
||||
results.add(reader.read(targetClass, dbo));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public RuntimeException convertMongoAccessException(RuntimeException ex) {
|
||||
return MongoDbUtils.translateMongoExceptionIfPossible(ex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DB getConnection() {
|
||||
return MongoDbUtils.getDB(mongo, databaseName);
|
||||
}
|
||||
|
||||
|
||||
protected DBObject convertToDbObject(CollectionOptions collectionOptions) {
|
||||
DBObject dbo = new BasicDBObject();
|
||||
if (collectionOptions != null) {
|
||||
if (collectionOptions.getCapped() != null) {
|
||||
dbo.put("capped", collectionOptions.getCapped().booleanValue());
|
||||
}
|
||||
if (collectionOptions.getSize() != null) {
|
||||
dbo.put("size", collectionOptions.getSize().intValue());
|
||||
}
|
||||
if (collectionOptions.getMaxDocuments() != null ) {
|
||||
dbo.put("max", collectionOptions.getMaxDocuments().intValue());
|
||||
}
|
||||
}
|
||||
return dbo;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
if (this.getDefaultCollectionName() != null) {
|
||||
DB db = getConnection();
|
||||
if (! db.collectionExists(getDefaultCollectionName())) {
|
||||
db.createCollection(getDefaultCollectionName(), null);
|
||||
}
|
||||
}
|
||||
if (this.mongoConverter == null) {
|
||||
mongoConverter = new SimpleMongoConverter();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,23 +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.data.document.mongodb;
|
||||
|
||||
import com.mongodb.DBObject;
|
||||
|
||||
public interface MongoWriter<T> {
|
||||
|
||||
void write(T t, DBObject dbo);
|
||||
}
|
||||
@@ -1,376 +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.data.document.mongodb;
|
||||
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.GenericArrayType;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.lang.reflect.TypeVariable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.bson.types.CodeWScope;
|
||||
import org.bson.types.ObjectId;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.BeanWrapper;
|
||||
import org.springframework.beans.PropertyAccessorFactory;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.core.convert.support.GenericConversionService;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DBObject;
|
||||
import com.mongodb.DBRef;
|
||||
|
||||
public class SimpleMongoConverter implements MongoConverter {
|
||||
|
||||
|
||||
/** Logger available to subclasses */
|
||||
protected final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
public static final Set<String> SIMPLE_TYPES;
|
||||
|
||||
static {
|
||||
Set<String> basics = new HashSet<String>();
|
||||
basics.add(boolean.class.getName());
|
||||
basics.add(long.class.getName());
|
||||
basics.add(short.class.getName());
|
||||
basics.add(int.class.getName());
|
||||
basics.add(byte.class.getName());
|
||||
basics.add(float.class.getName());
|
||||
basics.add(double.class.getName());
|
||||
basics.add(char.class.getName());
|
||||
basics.add(Boolean.class.getName());
|
||||
basics.add(Long.class.getName());
|
||||
basics.add(Short.class.getName());
|
||||
basics.add(Integer.class.getName());
|
||||
basics.add(Byte.class.getName());
|
||||
basics.add(Float.class.getName());
|
||||
basics.add(Double.class.getName());
|
||||
basics.add(Character.class.getName());
|
||||
basics.add(String.class.getName());
|
||||
basics.add(java.util.Date.class.getName());
|
||||
// basics.add(Time.class.getName());
|
||||
// basics.add(Timestamp.class.getName());
|
||||
// basics.add(java.sql.Date.class.getName());
|
||||
// basics.add(BigDecimal.class.getName());
|
||||
// basics.add(BigInteger.class.getName());
|
||||
basics.add(Locale.class.getName());
|
||||
// basics.add(Calendar.class.getName());
|
||||
// basics.add(GregorianCalendar.class.getName());
|
||||
// basics.add(java.util.Currency.class.getName());
|
||||
// basics.add(TimeZone.class.getName());
|
||||
// basics.add(Object.class.getName());
|
||||
basics.add(Class.class.getName());
|
||||
// basics.add(byte[].class.getName());
|
||||
// basics.add(Byte[].class.getName());
|
||||
// basics.add(char[].class.getName());
|
||||
// basics.add(Character[].class.getName());
|
||||
// basics.add(Blob.class.getName());
|
||||
// basics.add(Clob.class.getName());
|
||||
// basics.add(Serializable.class.getName());
|
||||
// basics.add(URI.class.getName());
|
||||
// basics.add(URL.class.getName());
|
||||
basics.add(DBRef.class.getName());
|
||||
basics.add(Pattern.class.getName());
|
||||
basics.add(CodeWScope.class.getName());
|
||||
basics.add(ObjectId.class.getName());
|
||||
// TODO check on enums.. basics.add(Enum.class.getName());
|
||||
SIMPLE_TYPES = Collections.unmodifiableSet(basics);
|
||||
}
|
||||
|
||||
protected GenericConversionService conversionService = new GenericConversionService();
|
||||
|
||||
public SimpleMongoConverter() {
|
||||
initializeConverters();
|
||||
}
|
||||
|
||||
public SimpleMongoConverter(GenericConversionService conversionService) {
|
||||
super();
|
||||
this.conversionService = conversionService;
|
||||
}
|
||||
|
||||
protected void initializeConverters() {
|
||||
conversionService.addConverter(new Converter<ObjectId, String>() {
|
||||
public String convert(ObjectId id) {
|
||||
return id.toString();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/*
|
||||
public ConversionContext getConversionContext() {
|
||||
return conversionContext;
|
||||
}
|
||||
|
||||
public void setConversionContext(ConversionContext conversionContext) {
|
||||
this.conversionContext = conversionContext;
|
||||
}
|
||||
|
||||
public void writeNew(Object obj, DBObject dbo) {
|
||||
conversionContext.convertToDBObject(dbo, null, obj);
|
||||
}*/
|
||||
|
||||
public void write(Object obj, DBObject dbo) {
|
||||
|
||||
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(obj);
|
||||
// This will leverage the conversion service.
|
||||
initBeanWrapper(bw);
|
||||
|
||||
PropertyDescriptor[] propertyDescriptors = BeanUtils
|
||||
.getPropertyDescriptors(obj.getClass());
|
||||
for (PropertyDescriptor pd : propertyDescriptors) {
|
||||
// if (isSimpleType(pd.getPropertyType())) {
|
||||
Object value = bw.getPropertyValue(pd.getName());
|
||||
String keyToUse = ("id".equals(pd.getName()) ? "_id" : pd.getName());
|
||||
|
||||
if (isValidProperty(pd)) {
|
||||
// TODO validate Enums...
|
||||
writeValue(dbo, keyToUse, value);
|
||||
// dbo.put(keyToUse, value);
|
||||
} else {
|
||||
//TODO exclude Class properties from consideration
|
||||
logger.warn("Unable to map property " + pd.getName()
|
||||
+ ". Skipping.");
|
||||
}
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void writeValue(DBObject dbo, String keyToUse, Object value) {
|
||||
|
||||
// is not asimple type.
|
||||
if (value != null) {
|
||||
if (!isSimpleType(value.getClass())) {
|
||||
writeCompoundValue(dbo, keyToUse, value);
|
||||
} else {
|
||||
dbo.put(keyToUse, value);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void writeCompoundValue(DBObject dbo, String keyToUse, Object value) {
|
||||
if (value instanceof Map) {
|
||||
writeMap(dbo, keyToUse, (Map<String, Object>)value);
|
||||
return;
|
||||
}
|
||||
if (value instanceof Collection) {
|
||||
// Should write a collection!
|
||||
return;
|
||||
}
|
||||
DBObject nestedDbo = new BasicDBObject();
|
||||
write(value, nestedDbo);
|
||||
dbo.put(keyToUse, nestedDbo);
|
||||
|
||||
}
|
||||
|
||||
protected void writeMap(DBObject dbo, String keyToUse, Map<String, Object> map) {
|
||||
//TODO support non-string based keys as long as there is a Spring Converter obj->string and (optionally) string->obj
|
||||
DBObject dboToPopulate = null;
|
||||
if (keyToUse != null) {
|
||||
dboToPopulate = new BasicDBObject();
|
||||
} else {
|
||||
dboToPopulate = dbo;
|
||||
}
|
||||
if (map != null) {
|
||||
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||||
Object entryValue = entry.getValue();
|
||||
if (!isSimpleType(entryValue.getClass())) {
|
||||
writeCompoundValue(dboToPopulate, entry.getKey(), entryValue);
|
||||
} else {
|
||||
dboToPopulate.put(entry.getKey(), entryValue);
|
||||
}
|
||||
}
|
||||
dbo.put(keyToUse, dboToPopulate);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
public Object readNew(Class<? extends Object> clazz, DBObject dbo) {
|
||||
return conversionContext.convertToObject(clazz, dbo);
|
||||
}*/
|
||||
|
||||
public Object read(Class<? extends Object> clazz, DBObject dbo) {
|
||||
|
||||
|
||||
|
||||
Assert.state(clazz != null, "Mapped class was not specified");
|
||||
Object mappedObject = BeanUtils.instantiate(clazz);
|
||||
BeanWrapper bw = PropertyAccessorFactory
|
||||
.forBeanPropertyAccess(mappedObject);
|
||||
initBeanWrapper(bw);
|
||||
|
||||
// Iterate over properties of the object.b
|
||||
// TODO iterate over the properties of DBObject and support nested property names with SpEL
|
||||
// e.g. { "parameters.p1" : "1" , "count" : 5.0}
|
||||
PropertyDescriptor[] propertyDescriptors = BeanUtils
|
||||
.getPropertyDescriptors(clazz);
|
||||
for (PropertyDescriptor pd : propertyDescriptors) {
|
||||
|
||||
if (dbo.containsField(pd.getName())) {
|
||||
Object value = dbo.get(pd.getName());
|
||||
if (value instanceof ObjectId) {
|
||||
setObjectIdOnObject(bw, pd, (ObjectId) value);
|
||||
} else {
|
||||
if (isValidProperty(pd)) {
|
||||
// This will leverage the conversion service.
|
||||
// bw.setPropertyValue(pd.getName(),
|
||||
// dbo.get(pd.getName()));
|
||||
readValue(bw, pd, dbo);
|
||||
} else {
|
||||
logger.warn("Unable to map DBObject field "
|
||||
+ pd.getName() + " to property " + pd.getName()
|
||||
+ ". Skipping.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return mappedObject;
|
||||
}
|
||||
|
||||
protected void readValue(BeanWrapper bw, PropertyDescriptor pd, DBObject dbo) {
|
||||
|
||||
Object value = dbo.get(pd.getName());
|
||||
// is not a simple type.
|
||||
if (!isSimpleType(value.getClass())) {
|
||||
bw.setPropertyValue(pd.getName(),readCompoundValue(pd, (DBObject) dbo.get(pd.getName())));
|
||||
} else {
|
||||
bw.setPropertyValue(pd.getName(), value);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private Object readCompoundValue(PropertyDescriptor pd, DBObject dbo) {
|
||||
Class propertyClazz = pd.getPropertyType();
|
||||
if (Map.class.isAssignableFrom(propertyClazz)) {
|
||||
//TODO assure is assignable to BasicDBObject
|
||||
return readMap(pd, (BasicDBObject)dbo, getGenericParameterClass(pd.getWriteMethod()).get(1) );
|
||||
}
|
||||
if (Collection.class.isAssignableFrom(propertyClazz)) {
|
||||
// Should read a collection!
|
||||
return null;
|
||||
}
|
||||
return read(propertyClazz, dbo);
|
||||
}
|
||||
|
||||
protected Map createMap() {
|
||||
return new HashMap();
|
||||
}
|
||||
|
||||
protected Map readMap(PropertyDescriptor pd, BasicDBObject dbo, Class valueClazz) {
|
||||
Class propertyClazz = pd.getPropertyType();
|
||||
Map map = createMap();
|
||||
for (Map.Entry entry : dbo.entrySet()) {
|
||||
Object entryValue = entry.getValue();
|
||||
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(entryValue);
|
||||
initBeanWrapper(bw);
|
||||
|
||||
if (!isSimpleType(entryValue.getClass())) {
|
||||
map.put((String)entry.getKey(), read(valueClazz, (DBObject) entryValue));
|
||||
//Can do some reflection tricks here -
|
||||
//throw new RuntimeException("User types not supported yet as values for Maps");
|
||||
} else {
|
||||
map.put((String)entry.getKey(), entryValue );
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
|
||||
|
||||
protected void setObjectIdOnObject(BeanWrapper bw, PropertyDescriptor pd,
|
||||
ObjectId value) {
|
||||
// TODO strategy for setting the id field. suggest looking for public
|
||||
// property 'Id' or private field id or _id;
|
||||
|
||||
}
|
||||
|
||||
protected boolean isValidProperty(PropertyDescriptor descriptor) {
|
||||
return (descriptor.getReadMethod() != null && descriptor
|
||||
.getWriteMethod() != null);
|
||||
}
|
||||
|
||||
protected boolean isSimpleType(Class propertyType) {
|
||||
if (propertyType == null)
|
||||
return false;
|
||||
if (propertyType.isArray()) {
|
||||
return isSimpleType(propertyType.getComponentType());
|
||||
}
|
||||
return SIMPLE_TYPES.contains(propertyType.getName());
|
||||
}
|
||||
|
||||
protected void initBeanWrapper(BeanWrapper bw) {
|
||||
bw.setConversionService(conversionService);
|
||||
}
|
||||
|
||||
|
||||
public List<Class> getGenericParameterClass(Method setMethod) {
|
||||
List<Class> actualGenericParameterTypes = new ArrayList<Class>();
|
||||
Type[] genericParameterTypes = setMethod.getGenericParameterTypes();
|
||||
|
||||
for(Type genericParameterType : genericParameterTypes){
|
||||
if(genericParameterType instanceof ParameterizedType){
|
||||
ParameterizedType aType = (ParameterizedType) genericParameterType;
|
||||
Type[] parameterArgTypes = aType.getActualTypeArguments();
|
||||
for(Type parameterArgType : parameterArgTypes){
|
||||
if (parameterArgType instanceof GenericArrayType)
|
||||
{
|
||||
Class arrayType = (Class) ((GenericArrayType) parameterArgType).getGenericComponentType();
|
||||
actualGenericParameterTypes.add(Array.newInstance(arrayType, 0).getClass());
|
||||
}
|
||||
else {
|
||||
if (parameterArgType instanceof ParameterizedType) {
|
||||
ParameterizedType paramTypeArgs = (ParameterizedType) parameterArgType;
|
||||
actualGenericParameterTypes.add((Class)paramTypeArgs.getRawType());
|
||||
} else {
|
||||
if (parameterArgType instanceof TypeVariable) {
|
||||
throw new RuntimeException("Can not map " + ((TypeVariable) parameterArgType).getName());
|
||||
} else {
|
||||
if (parameterArgType instanceof Class) {
|
||||
actualGenericParameterTypes.add((Class) parameterArgType);
|
||||
} else {
|
||||
throw new RuntimeException("Can not map " + parameterArgType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
return actualGenericParameterTypes;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,111 +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.data.document.mongodb.bean.factory;
|
||||
|
||||
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.data.document.mongodb.MongoDbUtils;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import com.mongodb.Mongo;
|
||||
import com.mongodb.MongoOptions;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
/**
|
||||
* Convenient factory for configuring MongoDB.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
* @author Graeme Rocher
|
||||
*
|
||||
* @since 1.0
|
||||
*/
|
||||
public class MongoFactoryBean implements FactoryBean<Mongo>, InitializingBean,
|
||||
PersistenceExceptionTranslator {
|
||||
|
||||
|
||||
/**
|
||||
* Logger, available to subclasses.
|
||||
*/
|
||||
protected final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private Mongo mongo;
|
||||
private MongoOptions mongoOptions;
|
||||
private String host;
|
||||
private Integer port;
|
||||
|
||||
public void setMongo(Mongo mongo) {
|
||||
this.mongo = mongo;
|
||||
}
|
||||
|
||||
public void setMongoOptions(MongoOptions mongoOptions) {
|
||||
this.mongoOptions = mongoOptions;
|
||||
}
|
||||
|
||||
public void setHost(String host) {
|
||||
this.host = host;
|
||||
}
|
||||
|
||||
public void setPort(int port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public Mongo getObject() throws Exception {
|
||||
Assert.notNull(mongo, "Mongo must not be null");
|
||||
return mongo;
|
||||
}
|
||||
|
||||
public Class<? extends Mongo> getObjectType() {
|
||||
return Mongo.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 (mongo == null) {
|
||||
|
||||
if (host == null) {
|
||||
logger.warn("Property host not specified. Using default configuration");
|
||||
mongo = new Mongo();
|
||||
}
|
||||
else {
|
||||
if(mongoOptions != null) {
|
||||
mongo = new Mongo(host != null ? host : "localhost", mongoOptions);
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,137 +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.data.document.mongodb.bean.factory;
|
||||
|
||||
import org.springframework.beans.factory.FactoryBean;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
|
||||
|
||||
import com.mongodb.MongoOptions;
|
||||
|
||||
/**
|
||||
* A factory bean for consruction a MongoOptions instance
|
||||
*
|
||||
* @author Graeme Rocher
|
||||
*
|
||||
*/
|
||||
public class MongoOptionsFactoryBean implements FactoryBean<MongoOptions>, InitializingBean{
|
||||
|
||||
private static final MongoOptions MONGO_OPTIONS = new MongoOptions();
|
||||
/**
|
||||
number of connections allowed per host
|
||||
will block if run out
|
||||
*/
|
||||
private int connectionsPerHost = MONGO_OPTIONS.connectionsPerHost;
|
||||
|
||||
/**
|
||||
multiplier for connectionsPerHost for # of threads that can block
|
||||
if connectionsPerHost is 10, and threadsAllowedToBlockForConnectionMultiplier is 5,
|
||||
then 50 threads can block
|
||||
more than that and an exception will be throw
|
||||
*/
|
||||
private int threadsAllowedToBlockForConnectionMultiplier = MONGO_OPTIONS.threadsAllowedToBlockForConnectionMultiplier;
|
||||
|
||||
/**
|
||||
* max wait time of a blocking thread for a connection
|
||||
*/
|
||||
private int maxWaitTime = MONGO_OPTIONS.maxWaitTime;
|
||||
|
||||
/**
|
||||
connect timeout in milliseconds. 0 is default and infinite
|
||||
*/
|
||||
private int connectTimeout = MONGO_OPTIONS.connectTimeout;
|
||||
|
||||
/**
|
||||
socket timeout. 0 is default and infinite
|
||||
*/
|
||||
private int socketTimeout = MONGO_OPTIONS.socketTimeout;
|
||||
|
||||
/**
|
||||
this controls whether or not on a connect, the system retries automatically
|
||||
*/
|
||||
private boolean autoConnectRetry = MONGO_OPTIONS.autoConnectRetry;
|
||||
|
||||
|
||||
/**
|
||||
number of connections allowed per host
|
||||
will block if run out
|
||||
*/
|
||||
public void setConnectionsPerHost(int connectionsPerHost) {
|
||||
this.connectionsPerHost = connectionsPerHost;
|
||||
}
|
||||
|
||||
/**
|
||||
multiplier for connectionsPerHost for # of threads that can block
|
||||
if connectionsPerHost is 10, and threadsAllowedToBlockForConnectionMultiplier is 5,
|
||||
then 50 threads can block
|
||||
more than that and an exception will be throw
|
||||
*/
|
||||
public void setThreadsAllowedToBlockForConnectionMultiplier(
|
||||
int threadsAllowedToBlockForConnectionMultiplier) {
|
||||
this.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
|
||||
}
|
||||
|
||||
/**
|
||||
* max wait time of a blocking thread for a connection
|
||||
*/
|
||||
public void setMaxWaitTime(int maxWaitTime) {
|
||||
this.maxWaitTime = maxWaitTime;
|
||||
}
|
||||
|
||||
/**
|
||||
connect timeout in milliseconds. 0 is default and infinite
|
||||
*/
|
||||
public void setConnectTimeout(int connectTimeout) {
|
||||
this.connectTimeout = connectTimeout;
|
||||
}
|
||||
|
||||
/**
|
||||
socket timeout. 0 is default and infinite
|
||||
*/
|
||||
public void setSocketTimeout(int socketTimeout) {
|
||||
this.socketTimeout = socketTimeout;
|
||||
}
|
||||
|
||||
/**
|
||||
this controls whether or not on a connect, the system retries automatically
|
||||
*/
|
||||
public void setAutoConnectRetry(boolean autoConnectRetry) {
|
||||
this.autoConnectRetry = autoConnectRetry;
|
||||
}
|
||||
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
MONGO_OPTIONS.connectionsPerHost = connectionsPerHost;
|
||||
MONGO_OPTIONS.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
|
||||
MONGO_OPTIONS.maxWaitTime = maxWaitTime;
|
||||
MONGO_OPTIONS.connectTimeout = connectTimeout;
|
||||
MONGO_OPTIONS.socketTimeout = socketTimeout;
|
||||
MONGO_OPTIONS.autoConnectRetry = autoConnectRetry;
|
||||
|
||||
}
|
||||
|
||||
public MongoOptions getObject() throws Exception {
|
||||
return MONGO_OPTIONS;
|
||||
}
|
||||
|
||||
public Class<?> getObjectType() {
|
||||
return MongoOptions.class;
|
||||
}
|
||||
|
||||
public boolean isSingleton() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,40 +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.data.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,161 +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.data.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,24 +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.data.document.mongodb.query;
|
||||
|
||||
import com.mongodb.DBObject;
|
||||
|
||||
public interface CriteriaSpec {
|
||||
|
||||
DBObject getCriteriaObject(String key);
|
||||
|
||||
}
|
||||
@@ -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.data.document.mongodb.query;
|
||||
|
||||
|
||||
public class FieldSpecification {
|
||||
|
||||
public FieldSpecification include(String key) {
|
||||
return this;
|
||||
}
|
||||
|
||||
public FieldSpecification exclude(String key) {
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,46 +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.data.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,25 +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.data.document.mongodb.query;
|
||||
|
||||
import com.mongodb.DBObject;
|
||||
|
||||
|
||||
public interface Query {
|
||||
|
||||
DBObject getQueryObject();
|
||||
|
||||
}
|
||||
@@ -1,68 +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.data.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,25 +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.data.document.mongodb.query;
|
||||
|
||||
|
||||
public class SliceSpecification {
|
||||
|
||||
public SliceSpecification on(String key, int size) {
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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.data.document.mongodb.query;
|
||||
|
||||
|
||||
public class SortSpecification {
|
||||
|
||||
public enum SortOrder {
|
||||
ASCENDING, DESCENDING
|
||||
}
|
||||
|
||||
public SortSpecification on(String key, SortOrder order) {
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,42 +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.data.document.mongodb;
|
||||
|
||||
public class Person {
|
||||
|
||||
private String firstName;
|
||||
|
||||
private Person friend;
|
||||
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public Person getFriend() {
|
||||
return friend;
|
||||
}
|
||||
|
||||
public void setFriend(Person friend) {
|
||||
this.friend = friend;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,66 +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.data.document.mongodb;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class Portfolio {
|
||||
|
||||
private String portfolioName;
|
||||
private User user;
|
||||
private List trades;
|
||||
private Map<String, Integer> positions;
|
||||
private Map<String, Person> portfolioManagers;
|
||||
|
||||
public Map<String, Person> getPortfolioManagers() {
|
||||
return portfolioManagers;
|
||||
}
|
||||
public void setPortfolioManagers(Map<String, Person> portfolioManagers) {
|
||||
this.portfolioManagers = portfolioManagers;
|
||||
}
|
||||
public Map<String, Integer> getPositions() {
|
||||
return positions;
|
||||
}
|
||||
public void setPositions(Map<String, Integer> positions) {
|
||||
this.positions = positions;
|
||||
}
|
||||
public Portfolio() {
|
||||
trades = new ArrayList();
|
||||
}
|
||||
public String getPortfolioName() {
|
||||
return portfolioName;
|
||||
}
|
||||
public void setPortfolioName(String portfolioName) {
|
||||
this.portfolioName = portfolioName;
|
||||
}
|
||||
public List getTrades() {
|
||||
return trades;
|
||||
}
|
||||
public void setTrades(List trades) {
|
||||
this.trades = trades;
|
||||
}
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -1,192 +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.data.document.mongodb;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.GenericArrayType;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.lang.reflect.TypeVariable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.document.mongodb.SimpleMongoConverter;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DBObject;
|
||||
|
||||
public class SimpleMongoConverterTests {
|
||||
|
||||
@Test
|
||||
public void notNestedObject() {
|
||||
User user = new User();
|
||||
user.setAccountName("My Account");
|
||||
user.setUserName("Mark");
|
||||
SimpleMongoConverter converter = createConverter();
|
||||
DBObject dbo = new BasicDBObject();
|
||||
converter.write(user, dbo);
|
||||
Assert.assertEquals("My Account", dbo.get("accountName"));
|
||||
Assert.assertEquals("Mark", dbo.get("userName"));
|
||||
|
||||
User u = (User) converter.read(User.class, dbo);
|
||||
|
||||
Assert.assertEquals("My Account", u.getAccountName());
|
||||
Assert.assertEquals("Mark", u.getUserName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nestedObject() {
|
||||
Portfolio p = createPortfolioWithNoTrades();
|
||||
SimpleMongoConverter converter = createConverter();
|
||||
DBObject dbo = new BasicDBObject();
|
||||
converter.write(p, dbo);
|
||||
Assert.assertEquals("High Risk Trading Account",
|
||||
dbo.get("portfolioName"));
|
||||
Assert.assertTrue(dbo.containsField("user"));
|
||||
|
||||
Portfolio cp = (Portfolio) converter.read(Portfolio.class, dbo);
|
||||
Assert.assertEquals("High Risk Trading Account", cp.getPortfolioName());
|
||||
Assert.assertEquals("Joe Trader", cp.getUser().getUserName());
|
||||
Assert.assertEquals("ACCT-123", cp.getUser().getAccountName());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void objectWithMap() {
|
||||
Portfolio p = createPortfolioWithPositions();
|
||||
SimpleMongoConverter converter = createConverter();
|
||||
DBObject dbo = new BasicDBObject();
|
||||
converter.write(p, dbo);
|
||||
|
||||
Portfolio cp = (Portfolio) converter.read(Portfolio.class, dbo);
|
||||
Assert.assertEquals("High Risk Trading Account", cp.getPortfolioName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void objectWithMapContainingNonPrimitiveTypeAsValue() {
|
||||
Portfolio p = createPortfolioWithManagers();
|
||||
SimpleMongoConverter converter = createConverter();
|
||||
DBObject dbo = new BasicDBObject();
|
||||
converter.write(p, dbo);
|
||||
|
||||
Portfolio cp = (Portfolio) converter.read(Portfolio.class, dbo);
|
||||
Assert.assertEquals("High Risk Trading Account", cp.getPortfolioName());
|
||||
}
|
||||
|
||||
private SimpleMongoConverter createConverter() {
|
||||
SimpleMongoConverter converter = new SimpleMongoConverter();
|
||||
return converter;
|
||||
}
|
||||
|
||||
protected Portfolio createPortfolioWithPositions() {
|
||||
|
||||
Portfolio portfolio = new Portfolio();
|
||||
portfolio.setPortfolioName("High Risk Trading Account");
|
||||
Map<String, Integer> positions = new HashMap<String, Integer>();
|
||||
positions.put("CSCO", 1);
|
||||
portfolio.setPositions(positions);
|
||||
return portfolio;
|
||||
}
|
||||
|
||||
protected Portfolio createPortfolioWithManagers() {
|
||||
|
||||
Portfolio portfolio = new Portfolio();
|
||||
portfolio.setPortfolioName("High Risk Trading Account");
|
||||
Map<String, Person> managers = new HashMap<String, Person>();
|
||||
Person p1 = new Person();
|
||||
p1.setFirstName("Mark");
|
||||
managers.put("CSCO", p1);
|
||||
portfolio.setPortfolioManagers(managers);
|
||||
return portfolio;
|
||||
}
|
||||
|
||||
protected Portfolio createPortfolioWithNoTrades() {
|
||||
Portfolio portfolio = new Portfolio();
|
||||
User user = new User();
|
||||
user.setUserName("Joe Trader");
|
||||
user.setAccountName("ACCT-123");
|
||||
portfolio.setUser(user);
|
||||
portfolio.setPortfolioName("High Risk Trading Account");
|
||||
return portfolio;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReflection() {
|
||||
Portfolio p = createPortfolioWithManagers();
|
||||
Method method = ReflectionUtils.findMethod(Portfolio.class, "setPortfolioManagers", Map.class);
|
||||
Assert.assertNotNull(method);
|
||||
List<Class> paramClass = getGenericParameterClass(method);
|
||||
System.out.println(paramClass);
|
||||
/*
|
||||
Type t = method.getGenericReturnType();
|
||||
if (t instanceof ParameterizedType) {
|
||||
ParameterizedType pt = (ParameterizedType) t;
|
||||
Type paramType = pt.getActualTypeArguments()[1];
|
||||
if (paramType instanceof ParameterizedType) {
|
||||
ParameterizedType paramPtype = (ParameterizedType) pt;
|
||||
System.out.println(paramPtype.getRawType());
|
||||
}
|
||||
}*/
|
||||
// Assert.assertNotNull(null);
|
||||
|
||||
}
|
||||
|
||||
public List<Class> getGenericParameterClass(Method setMethod) {
|
||||
List<Class> actualGenericParameterTypes = new ArrayList<Class>();
|
||||
Type[] genericParameterTypes = setMethod.getGenericParameterTypes();
|
||||
|
||||
for(Type genericParameterType : genericParameterTypes){
|
||||
if(genericParameterType instanceof ParameterizedType){
|
||||
ParameterizedType aType = (ParameterizedType) genericParameterType;
|
||||
Type[] parameterArgTypes = aType.getActualTypeArguments();
|
||||
for(Type parameterArgType : parameterArgTypes){
|
||||
if (parameterArgType instanceof GenericArrayType)
|
||||
{
|
||||
Class arrayType = (Class) ((GenericArrayType) parameterArgType).getGenericComponentType();
|
||||
actualGenericParameterTypes.add(Array.newInstance(arrayType, 0).getClass());
|
||||
}
|
||||
else {
|
||||
if (parameterArgType instanceof ParameterizedType) {
|
||||
ParameterizedType paramTypeArgs = (ParameterizedType) parameterArgType;
|
||||
actualGenericParameterTypes.add((Class)paramTypeArgs.getRawType());
|
||||
} else {
|
||||
if (parameterArgType instanceof TypeVariable) {
|
||||
throw new RuntimeException("Can not map " + ((TypeVariable) parameterArgType).getName());
|
||||
} else {
|
||||
if (parameterArgType instanceof Class) {
|
||||
actualGenericParameterTypes.add((Class) parameterArgType);
|
||||
} else {
|
||||
throw new RuntimeException("Can not map " + parameterArgType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
return actualGenericParameterTypes;
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,62 +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.data.document.mongodb;
|
||||
|
||||
public class Trade {
|
||||
|
||||
private String ticker;
|
||||
|
||||
private long quantity;
|
||||
|
||||
private double price;
|
||||
|
||||
private String orderType;
|
||||
|
||||
public String getOrderType() {
|
||||
return orderType;
|
||||
}
|
||||
|
||||
public void setOrderType(String orderType) {
|
||||
this.orderType = orderType;
|
||||
}
|
||||
|
||||
public double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public long getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(long quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public String getTicker() {
|
||||
return ticker;
|
||||
}
|
||||
|
||||
public void setTicker(String ticker) {
|
||||
this.ticker = ticker;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -1,74 +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.data.document.mongodb;
|
||||
|
||||
public class User {
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result
|
||||
+ ((accountName == null) ? 0 : accountName.hashCode());
|
||||
result = prime * result
|
||||
+ ((userName == null) ? 0 : userName.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
User other = (User) obj;
|
||||
if (accountName == null) {
|
||||
if (other.accountName != null)
|
||||
return false;
|
||||
} else if (!accountName.equals(other.accountName))
|
||||
return false;
|
||||
if (userName == null) {
|
||||
if (other.userName != null)
|
||||
return false;
|
||||
} else if (!userName.equals(other.userName))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private String accountName;
|
||||
|
||||
private String userName;
|
||||
|
||||
public String getAccountName() {
|
||||
return accountName;
|
||||
}
|
||||
|
||||
public void setAccountName(String accountName) {
|
||||
this.accountName = accountName;
|
||||
}
|
||||
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
public void setUserName(String userName) {
|
||||
this.userName = userName;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
package org.springframework.data.document.mongodb.analytics;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.document.mongodb.MongoReader;
|
||||
import org.springframework.data.document.mongodb.MongoTemplate;
|
||||
import org.springframework.datastore.document.analytics.ControllerCounter;
|
||||
import org.springframework.datastore.document.analytics.MvcEvent;
|
||||
import org.springframework.datastore.document.analytics.Parameters;
|
||||
|
||||
import com.mongodb.BasicDBList;
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DB;
|
||||
import com.mongodb.DBCollection;
|
||||
import com.mongodb.DBObject;
|
||||
import com.mongodb.Mongo;
|
||||
import com.mongodb.QueryBuilder;
|
||||
import com.mongodb.WriteResult;
|
||||
|
||||
|
||||
public class MvcAnalyticsTests {
|
||||
|
||||
private MongoTemplate mongoTemplate;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
Mongo m = new Mongo();
|
||||
mongoTemplate = new MongoTemplate(m, "mvc", "mvc");
|
||||
mongoTemplate.afterPropertiesSet();
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void clean() {
|
||||
mongoTemplate.dropCollection("mvc");
|
||||
mongoTemplate.createCollection("mvc");
|
||||
mongoTemplate.dropCollection("counters");
|
||||
mongoTemplate.createCollection("counters");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadMvcEventData() {
|
||||
|
||||
// datasize, favoriteRestId
|
||||
createAndStoreMvcEvent(5, 1);
|
||||
createAndStoreMvcEvent(6, 2);
|
||||
createAndStoreMvcEvent(3, 3);
|
||||
createAndStoreMvcEvent(8, 4);
|
||||
|
||||
List<MvcEvent> mvcEvents = mongoTemplate.queryForCollection("mvc",
|
||||
MvcEvent.class);
|
||||
Assert.assertEquals(22, mvcEvents.size());
|
||||
|
||||
List<MvcEvent> mvcEvents2 = mongoTemplate.queryForCollection("mvc", MvcEvent.class,
|
||||
new MongoReader<MvcEvent>() {
|
||||
public MvcEvent read(Class<? extends MvcEvent> clazz, DBObject dbo) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadCounterData() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
storeCounterData("SignUpController", "createForm");
|
||||
storeCounterData("SignUpController", "create");
|
||||
storeCounterData("SignUpController", "show");
|
||||
storeCounterData("RestaurantController", "addFavoriteRestaurant");
|
||||
}
|
||||
for (int i = 0; i< 5;i++) {
|
||||
storeCounterData("RestaurantController", "list");
|
||||
storeCounterData("SignUpController", "show");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void queryCounterData() {
|
||||
DBObject query = QueryBuilder.start("name").is("SignUpController").get();
|
||||
for (DBObject dbo : mongoTemplate.getCollection("counters").find(query)) {
|
||||
System.out.println(dbo);
|
||||
}
|
||||
List<ControllerCounter> counters = mongoTemplate.queryForList("counters", "{ 'name' : 'SignUpController'} ", ControllerCounter.class);
|
||||
for (ControllerCounter controllerCounter : counters) {
|
||||
System.out.println(controllerCounter);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
*
|
||||
* var start = new Date(2010,9,1); var end = new Date(2010,11,1);
|
||||
* db.mvc.group( { cond: {"action": "addFavoriteRestaurant", "date": {$gte:
|
||||
* start, $lt: end}} , key: {"parameters.p1": true} , initial: {count: 0} ,
|
||||
* reduce: function(doc, out){ out.count++; } } );
|
||||
*/
|
||||
|
||||
@Test
|
||||
public void listAllMvcEvents() {
|
||||
List<MvcEvent> mvcEvents = mongoTemplate.queryForCollection("mvc",
|
||||
MvcEvent.class);
|
||||
for (MvcEvent mvcEvent : mvcEvents) {
|
||||
System.out.println(mvcEvent.getDate());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void groupQuery() {
|
||||
// This circumvents exception translation
|
||||
DBCollection collection = mongoTemplate.getConnection().getCollection(
|
||||
"mvc");
|
||||
|
||||
// QueryBuilder qb = new QueryBuilder();
|
||||
// qb.start("date").greaterThan(object)
|
||||
Calendar startDate = Calendar.getInstance();
|
||||
startDate.clear();
|
||||
startDate.set(Calendar.YEAR, 2010);
|
||||
startDate.set(Calendar.MONTH, 5);
|
||||
Calendar endDate = Calendar.getInstance();
|
||||
endDate.clear();
|
||||
endDate.set(Calendar.YEAR, 2010);
|
||||
endDate.set(Calendar.MONTH, 12);
|
||||
|
||||
/*
|
||||
* QueryBuilder qb = new QueryBuilder(); Query q =
|
||||
* qb.find("date").gte(startDate
|
||||
* .getTime()).lt(endDate.getTime()).and("action"
|
||||
* ).is("addFavoriteRestaurant").build(); DBObject cond2 =
|
||||
* q.getQueryObject();
|
||||
*/
|
||||
DBObject cond = QueryBuilder.start("date")
|
||||
.greaterThanEquals(startDate.getTime())
|
||||
.lessThan(endDate.getTime()).and("action")
|
||||
.is("addFavoriteRestaurant").get();
|
||||
DBObject key = new BasicDBObject("parameters.p1", true);
|
||||
/*
|
||||
* DBObject dateQ = new BasicDBObject(); dateQ.put("$gte",
|
||||
* startDate.getTime()); dateQ.put("$lt", endDate.getTime()); DBObject
|
||||
* cond = new BasicDBObject(); cond.put("action",
|
||||
* "addFavoriteRestaurant"); cond.put("date", dateQ);
|
||||
*/
|
||||
|
||||
DBObject intitial = new BasicDBObject("count", 0);
|
||||
DBObject result = collection.group(key, cond, intitial,
|
||||
"function(doc, out){ out.count++; }");
|
||||
if (result instanceof BasicDBList) {
|
||||
BasicDBList dbList = (BasicDBList) result;
|
||||
for (Iterator iterator = dbList.iterator(); iterator.hasNext();) {
|
||||
DBObject dbo = (DBObject) iterator.next();
|
||||
System.out.println(dbo);
|
||||
}
|
||||
}
|
||||
Map resultMap = result.toMap();
|
||||
System.out.println(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void storeControllerCounterInfo() {
|
||||
|
||||
BasicDBObject query = new BasicDBObject("name", "controller1");
|
||||
|
||||
BasicDBObject changes = new BasicDBObject();
|
||||
changes.put("$set", new BasicDBObject("name", "controller1"));
|
||||
changes.put("$inc", new BasicDBObject("count", 1));
|
||||
|
||||
//mongoTemplate.upsertAndModify(dbo("key","value"), inc("count",1));
|
||||
//dbo(set("name","controller"), inc("count", 1));
|
||||
|
||||
///mongoTemplate.update(collection("counters")
|
||||
|
||||
WriteResult r = mongoTemplate.getCollection("counters").update(query, changes, true,false);
|
||||
//{ "err" : "Modifiers and non-modifiers cannot be mixed" , "code" : 10154 , "n" : 0 , "ok" : 1.0}
|
||||
//{ "err" : null , "updatedExisting" : false , "upserted" : { "$oid" : "4cba814a5a4900000000495d"} , "n" : 1 , "ok" : 1.0}
|
||||
//{ "err" : null , "updatedExisting" : true , "n" : 1 , "ok" : 1.0}
|
||||
System.out.println(r);
|
||||
|
||||
// changes = new BasicDBObject("methods", new BasicDBObject("find", 1));
|
||||
// mongoTemplate.getCollection("counters").update(query, changes, true,
|
||||
// false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updateMethodCounter() {
|
||||
DBObject query = new BasicDBObject("name", "controller1");
|
||||
DBObject changes = new BasicDBObject("$inc", new BasicDBObject("methods.find", 1));
|
||||
mongoTemplate.getConnection().getCollection("counters").update(query, changes, true, false);
|
||||
}
|
||||
|
||||
|
||||
public void storeCounterData(String controllerName, String methodName) {
|
||||
BasicDBObject query = new BasicDBObject("name", controllerName);
|
||||
|
||||
BasicDBObject changes = new BasicDBObject();
|
||||
changes.put("$set", new BasicDBObject("name", controllerName));
|
||||
changes.put("$inc", new BasicDBObject("count", 1));
|
||||
|
||||
WriteResult r = mongoTemplate.getCollection("counters").update(query, changes, true,false);
|
||||
System.out.println(r);
|
||||
|
||||
changes = new BasicDBObject("$inc", new BasicDBObject("methods." + methodName, 1));
|
||||
r = mongoTemplate.getConnection().getCollection("counters").update(query, changes, true, false);
|
||||
System.out.println(r);
|
||||
}
|
||||
|
||||
private void createAndStoreMvcEvent(int dataSize, int p1) {
|
||||
for (int i = 0; i < dataSize; i++) {
|
||||
MvcEvent event = generateEvent(p1);
|
||||
mongoTemplate.save(event);
|
||||
}
|
||||
}
|
||||
|
||||
private ControllerCounter generateCounter() {
|
||||
ControllerCounter cc = new ControllerCounter();
|
||||
cc.setName("controller2");
|
||||
cc.setCount(0);
|
||||
Map<String, Double> methods = new HashMap<String, Double>();
|
||||
methods.put("find", 1D);
|
||||
cc.setMethods(methods);
|
||||
return cc;
|
||||
}
|
||||
|
||||
private MvcEvent generateEvent(Integer p1) {
|
||||
MvcEvent event = new MvcEvent();
|
||||
|
||||
event.setController("RestaurantController");
|
||||
event.setAction("addFavoriteRestaurant");
|
||||
event.setDate(new Date());
|
||||
event.setRemoteUser("mpollack");
|
||||
event.setRequestAddress("127.0.0.1");
|
||||
event.setRequestUri("/myrestaurants-analytics/restaurants");
|
||||
Parameters params = new Parameters();
|
||||
params.setP1(p1.toString());
|
||||
params.setP2("2");
|
||||
event.setParameters(params);
|
||||
|
||||
return event;
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
log4j.rootCategory=INFO, stdout
|
||||
|
||||
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
|
||||
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
|
||||
|
||||
log4j.category.org.apache.activemq=ERROR
|
||||
log4j.category.org.springframework.batch=DEBUG
|
||||
log4j.category.org.springframework.transaction=INFO
|
||||
|
||||
log4j.category.org.hibernate.SQL=DEBUG
|
||||
# for debugging datasource initialization
|
||||
# log4j.category.test.jdbc=DEBUG
|
||||
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<import resource="classpath:/META-INF/spring/app-context.xml"/>
|
||||
|
||||
</beans>
|
||||
@@ -1,23 +0,0 @@
|
||||
Bundle-SymbolicName: org.springframework.datastore.mongodb
|
||||
Bundle-Name: Spring Datastore Mongo DB Support
|
||||
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.transaction.*;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"
|
||||
|
||||
|
||||
Reference in New Issue
Block a user