Repository: ttrelle/spring-data-examples
Branch: master
Commit: 80b3e307c4a6
Files: 83
Total size: 98.5 KB
Directory structure:
gitextract_eebtamkp/
├── .gitignore
├── .travis.yml
├── README.md
├── mongodriver/
│ ├── .gitignore
│ ├── pom.xml
│ └── src/
│ └── main/
│ └── java/
│ └── de/
│ └── codecentric/
│ ├── Connection.java
│ ├── driverclient/
│ │ ├── OrderExample.java
│ │ ├── ReplicaSetTimeout.java
│ │ └── SimpleMongoClient.java
│ ├── notifications/
│ │ ├── DocumentProducer.java
│ │ └── EventListener.java
│ └── transaction/
│ └── SimpleTransaction.java
├── pom.xml
├── spring-boot-mongo/
│ ├── .gitignore
│ ├── docker-compose.yml
│ ├── mvnw
│ ├── mvnw.cmd
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── docker/
│ │ │ └── Dockerfile
│ │ ├── java/
│ │ │ └── de/
│ │ │ └── codecentric/
│ │ │ └── mongoboot/
│ │ │ ├── Item.java
│ │ │ ├── Order.java
│ │ │ ├── OrderRepository.java
│ │ │ └── SpringBootMongoApplication.java
│ │ └── resources/
│ │ └── application.properties
│ └── test/
│ └── java/
│ └── de/
│ └── codecentric/
│ └── mongoboot/
│ └── SpringBootMongoApplicationTests.java
├── springdata-jpa/
│ ├── .gitignore
│ ├── README.md
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── jpa/
│ │ │ ├── domain/
│ │ │ │ └── User.java
│ │ │ └── repo/
│ │ │ ├── ClassicUserRepository.java
│ │ │ └── UserRepository.java
│ │ └── resources/
│ │ └── META-INF/
│ │ ├── orm.xml
│ │ └── persistence.xml
│ └── test/
│ ├── java/
│ │ └── jpa/
│ │ └── repo/
│ │ └── JpaRepoTest.java
│ └── resources/
│ └── jpa/
│ └── repo/
│ └── JpaRepoTest-context.xml
├── springdata-mongodb/
│ ├── .gitignore
│ ├── README.md
│ ├── pom.xml
│ ├── rs-dev0.yml
│ ├── single-node.yml
│ └── src/
│ ├── main/
│ │ ├── bat/
│ │ │ ├── masterslave.bat
│ │ │ └── shard.bat
│ │ ├── doc/
│ │ │ └── points.pptx
│ │ └── java/
│ │ └── mongodb/
│ │ ├── Adresse.java
│ │ ├── PointOfInterest.java
│ │ ├── geo/
│ │ │ ├── Location.java
│ │ │ └── LocationRepository.java
│ │ ├── order/
│ │ │ ├── Item.java
│ │ │ ├── Order.java
│ │ │ ├── OrderBeforeSaveListener.java
│ │ │ └── OrderRepository.java
│ │ └── user/
│ │ ├── User.java
│ │ └── UserRepository.java
│ ├── misc/
│ │ ├── java/
│ │ │ └── mongodb/
│ │ │ ├── CappedCollectionManipulationTest.java
│ │ │ └── MongoDBMassTest.java
│ │ └── resources/
│ │ ├── CappedCollectionManipulationTest-context.xml
│ │ └── MongoDBMassTest-context.xml
│ └── test/
│ ├── java/
│ │ └── mongodb/
│ │ ├── config/
│ │ │ ├── LocalhostMongoConfiguration.java
│ │ │ └── LocalhostMongoGridFSConfiguration.java
│ │ ├── geo/
│ │ │ └── LocationRepositoryTest.java
│ │ ├── order/
│ │ │ ├── OrderRepositoryTest.java
│ │ │ └── OrderSubListTest.java
│ │ └── user/
│ │ ├── IndexViolationTest.java
│ │ └── UserRepositoryTest.java
│ └── resources/
│ └── dummy.txt
├── springdata-neo4j/
│ ├── .gitignore
│ ├── README.md
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── doc/
│ │ │ └── example1.pptx
│ │ └── java/
│ │ └── neo4j/
│ │ ├── domain/
│ │ │ └── User.java
│ │ └── repo/
│ │ └── UserRepository.java
│ └── test/
│ └── java/
│ └── neo4j/
│ └── repo/
│ ├── Neo4jRepoTest.java
│ └── Neo4jTestConfig.java
└── springdata-redis/
├── .gitignore
├── README.md
├── pom.xml
└── src/
├── main/
│ └── java/
│ └── redis/
│ ├── StringStringRepository.java
│ ├── User.java
│ └── UserRepository.java
└── test/
├── java/
│ └── redis/
│ ├── StringStringRepositoryTest.java
│ └── UserRepositoryTest.java
└── resources/
└── redis/
├── StringStringRepositoryTest-context.xml
└── UserRepositoryTest-context.xml
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
/target
/.settings
.classpath
.project
================================================
FILE: .travis.yml
================================================
language: java
jdk:
- openjdk11
services:
- mongodb
- redis
addons:
apt:
sources:
- mongodb-3.4-precise
packages:
- mongodb-org-server
================================================
FILE: README.md
================================================
# Spring Data Blog Series
This projects holds the Java source examples for my blog post series on the Spring Data project:
* [GridFS Support in Spring Data MongoDB](http://blog.codecentric.de/en/2012/07/gridfs-support-in-spring-data-mongodb/)
* [Part 6: Spring Data Redis](http://blog.codecentric.de/en/2012/04/spring-data-redis/)
* [Part 5: Spring Data Neo4j](http://blog.codecentric.de/en/2012/02/spring-data-neo4j/)
* [Part 4: Geospatial Queries with Spring Data MongoDB](http://blog.codecentric.de/en/2012/02/spring-data-mongodb-geospatial-queries/)
* [Part 3: Spring Data MongoDB](http://blog.codecentric.de/en/2012/02/spring-data-mongodb/)
* [Part 2: Spring Data JPA](http://blog.codecentric.de/en/2012/01/spring-data-jpa/)
* [Part 1: Spring Data Commons](http://blog.codecentric.de/en/2011/12/spring-data-commons/)
## Build Status @ Travis CI ##
[](https://travis-ci.org/ttrelle/spring-data-examples)
## Usage
The projects are using a Maven based build. To run the tests on the command line use
mvn clean test
If you want to use an IDE like Eclipse run
mvn eclipse:eclipse
and set the Eclipse variable M2_REPO pointing to your local Maven repository. Or just import the project as an existing Maven project if you are using the m2 plugin.
================================================
FILE: mongodriver/.gitignore
================================================
/.settings/
/target/
================================================
FILE: mongodriver/pom.xml
================================================
4.0.0
de.codecentric
springdata-examples
1.0.0
mongodriver
3.10.0
org.mongodb
mongo-java-driver
${mongo.driver.version}
================================================
FILE: mongodriver/src/main/java/de/codecentric/Connection.java
================================================
package de.codecentric;
import com.mongodb.MongoClientURI;
abstract public class Connection {
public static final MongoClientURI URI = new MongoClientURI(
"mongodb://mongo1:27001,mongo2:27002,mongo3:27003/test?replicatSet=dev0"
// "mongodb://localhost:27001,localhost:27002,localhost:27003/test?replicatSet=dev0"
);
}
================================================
FILE: mongodriver/src/main/java/de/codecentric/driverclient/OrderExample.java
================================================
package de.codecentric.driverclient;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
/**
* Simple MongoDB client based on the MongoDB Java driver API.
*/
public class OrderExample {
/**
* CLI call.
* @param argv command line arguments
* @throws MongoException
* @throws UnknownHostException
* @throws UnsupportedEncodingException
*/
public static void main(String[] argv) throws UnknownHostException, MongoException, UnsupportedEncodingException {
MongoClient mongo;
// Default: localhost:27017
mongo = new MongoClient();
MongoDatabase db = mongo.getDatabase("test");
MongoCollection collection = db.getCollection("order");
insert(collection);
find(mongo);
}
private static void insert(MongoCollection collection) {
Document order;
List items = new ArrayList();
Document item;
// order
order = new Document();
order.put("date", new Date());
order.put("custInfo" , "Tobias Trelle");
order.put("items", items);
// items
item = new Document();
item.put("quantity", 1);
item.put("price", 47.11);
item.put("desc", "Item #1");
items.add(item);
item = new Document();
item.put("quantity", 2);
item.put("price", 42.0);
item.put("desc", "Item #2");
items.add(item);
collection.insertOne(order);
}
private static void find(MongoClient mongo) {
MongoDatabase db = mongo.getDatabase("test");
MongoCollection collection = db.getCollection("order");
Bson query;
FindIterable cursor;
query = new BasicDBObject("items.quantity", 2);
cursor = collection.find(query);
for(Document document: cursor ) {
println(document);
}
}
private static final void println(Object o) {
System.out.println(o);
}
}
================================================
FILE: mongodriver/src/main/java/de/codecentric/driverclient/ReplicaSetTimeout.java
================================================
package de.codecentric.driverclient;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.BulkWriteOptions;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.WriteModel;
public class ReplicaSetTimeout {
private static final WriteConcern WRITE_CONCERN = WriteConcern.ACKNOWLEDGED
.withW("majority")
.withWTimeout(200, TimeUnit.MILLISECONDS)
.withJournal(true)
;
private static final int BULK_SIZE = 10000;
public static void main(String[] argv) {
new ReplicaSetTimeout().execute();
}
public void execute() {
MongoClient mongo = null;
mongo = new MongoClient(Arrays.asList( //
new ServerAddress("localhost", 27001), //
new ServerAddress("localhost", 27002), //
new ServerAddress("localhost", 27003)));
try {
MongoDatabase db = mongo.getDatabase("test");
MongoCollection collection = db.getCollection("foo").withWriteConcern(WRITE_CONCERN);
System.out.println("WriteConcern: " + collection.getWriteConcern());
// remove
collection.deleteMany(new Document());
// bulk insert
BulkWriteOptions opts = new BulkWriteOptions();
opts.ordered(true);
long time = System.currentTimeMillis();
collection.bulkWrite( createBulk(), opts );
time = System.currentTimeMillis() - time;
System.out.println("*** runtime [ms]: " + time);
} catch (MongoException e) {
e.printStackTrace();
} finally {
if (mongo != null) {
mongo.close();
}
}
}
private List> createBulk() {
final List> ops = new ArrayList>();
Document payload;
for(int i=0; i(payload) );
}
return ops;
}
}
================================================
FILE: mongodriver/src/main/java/de/codecentric/driverclient/SimpleMongoClient.java
================================================
package de.codecentric.driverclient;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.Date;
import org.bson.BSON;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
/**
* Simple MongoDB client based on the MongoDB Java driver API.
*/
public class SimpleMongoClient {
/**
* CLI call.
* @param argv command line arguments
* @throws MongoException
* @throws UnknownHostException
* @throws UnsupportedEncodingException
*/
public static void main(String[] argv) throws UnknownHostException, MongoException, UnsupportedEncodingException {
MongoClient mongo = null;
try {
// Default: localhost:27017
mongo = new MongoClient();
// Sharding: mongos server
// mongo = new MongoClient("mongos-1", 4711);
// Replica set
// mongo = new MongoClient(
// s new MongoClientURI("mongodb://localhost:27001,localhost:27002,localhost:27003/replicaSet=demo-dev")
// );
// use database "test"
MongoDatabase db = mongo.getDatabase("test");
// get collection names
MongoIterable colls = db.listCollectionNames();
for (String s : colls) {
println(s);
}
// use collection "foo"
MongoCollection collection = db.getCollection("foo");
insert(collection);
find(collection);
// remove(collection);
// bsonize();
} finally {
if (mongo != null) {
mongo.close();
}
}
}
private static void remove(MongoCollection collection) {
// alle Dokuemente mit {i: 42}
Bson criteria = new BasicDBObject("i", 42);
collection.deleteOne(criteria);
// alle Dokumente
collection.deleteMany( new BasicDBObject() );
// schneller:
collection.drop();
}
private static void insert(MongoCollection collection) {
// Document speichern
Document doc = new Document();
doc.put("date", new Date());
doc.put("i", 42);
collection.insertOne(doc);
}
private static void find(MongoCollection collection) {
FindIterable cursor;
// alle Dokumente
cursor = collection.find();
for ( Document document: cursor ) {
println(document);
}
}
private static void find(MongoCollection collection, Bson query) {
FindIterable cursor;
// alle Dokumente
cursor = collection.find();
// Dokumente mit {i: 42}
cursor = collection.find( query );
for ( Document document: cursor ) {
println(document);
}
}
private static void bsonize() throws UnsupportedEncodingException {
final String key = "hello";
final String value = "MongoDB";
bsonize( new BasicDBObject(key, value) );
println( toString(key.getBytes("UTF-8")) );
println( toString(value.getBytes("UTF-8")) );
}
private static void bsonize(DBObject doc) {
final byte[] buff = BSON.encode(doc);
println( toString(buff) );
}
private static String toString(byte[] buff) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < buff.length; i++) {
sb.append("\\x");
String hex = Integer.toHexString(buff[i]);
if ( hex.length() < 2 ) {
sb.append("0");
}
sb.append(hex);
;
}
return sb.toString();
}
private static final void println(Object o) {
System.out.println(o);
}
}
================================================
FILE: mongodriver/src/main/java/de/codecentric/notifications/DocumentProducer.java
================================================
package de.codecentric.notifications;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import de.codecentric.Connection;
public class DocumentProducer {
public static void main(String[] args) throws Exception {
try (MongoClient client = new MongoClient(Connection.URI)) {
MongoCollection eventCollection =
client.getDatabase("test").getCollection("events");
long i = 0;
while (true) {
Document doc = new Document();
doc.put("i", i++);
doc.put("even", i % 2);
eventCollection.insertOne(doc);
//System.out.println("inserted: " + doc);
Thread.sleep(2000L + (long)(1000*Math.random()));
}
}
}
}
================================================
FILE: mongodriver/src/main/java/de/codecentric/notifications/EventListener.java
================================================
package de.codecentric.notifications;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.in;
import static java.util.Arrays.asList;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.ChangeStreamIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Aggregates;
import de.codecentric.Connection;
public class EventListener {
public static void main(String[] args) throws Exception {
try (MongoClient client = new MongoClient(Connection.URI)) {
MongoCollection eventCollection =
client.getDatabase("test").getCollection("events");
ChangeStreamIterable changes = eventCollection.watch(asList(
Aggregates.match( and( asList(
in("operationType", asList("insert")),
eq("fullDocument.even", 1L)))
)));
changes.iterator().forEachRemaining(
change -> System.out.println("received: " + change.getFullDocument())
);
}
}
}
================================================
FILE: mongodriver/src/main/java/de/codecentric/transaction/SimpleTransaction.java
================================================
package de.codecentric.transaction;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import de.codecentric.Connection;
/**
* Simple transaction example.
*/
public class SimpleTransaction {
/**
* CLI call.
*
* @param argv
* command line arguments
* @throws MongoException
* @throws UnknownHostException
* @throws UnsupportedEncodingException
*/
public static void main(String[] argv) throws UnknownHostException, MongoException, UnsupportedEncodingException {
try (MongoClient client = new MongoClient(Connection.URI)) {
// use database "test"
MongoDatabase db = client.getDatabase("test");
// collection must be created beforehand *outside* the transaction!
MongoCollection collection = db.getCollection("foo");
try (ClientSession clientSession = client.startSession()) {
clientSession.startTransaction();
collection.insertOne(clientSession, new Document("i", 1));
collection.insertOne(clientSession, new Document("i", 2));
clientSession.commitTransaction();
println("Transaction committed sucessfully.");
}
}
}
private static final void println(Object o) {
System.out.println(o);
}
}
================================================
FILE: pom.xml
================================================
4.0.0
de.codecentric
springdata-examples
1.0.0
pom
Spring Data Examples
springdata-mongodb
springdata-redis
springdata-neo4j
springdata-jpa
spring-boot-mongo
mongodriver
UTF-8
1.8
4.12
org.apache.maven.plugins
maven-compiler-plugin
3.5.1
${java.version}
${java.version}
codecentric AG
http://www.codecentric.de
Tobias Trelle
tobias.trelle@codecentric.de
================================================
FILE: spring-boot-mongo/.gitignore
================================================
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/
/.mvn/
================================================
FILE: spring-boot-mongo/docker-compose.yml
================================================
version: '3'
networks:
servicenet:
driver: bridge
services:
boot-rest-mongo:
image: mongoboot/spring-boot-mongo
ports:
- "8080:8080"
networks:
- servicenet
depends_on:
- mongo
environment:
SPRING_DATA_MONGODB_URI: mongodb://mongo:27017/test
mongo:
image: mongo:3.4.10
ports:
- "27017:27017"
networks:
- servicenet
volumes:
- /data/db:/data/db
================================================
FILE: spring-boot-mongo/mvnw
================================================
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
#
# Look for the Apple JDKs first to preserve the existing behaviour, and then look
# for the new JDKs provided by Oracle.
#
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
#
# Oracle JDKs
#
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
#
# Apple JDKs
#
export JAVA_HOME=`/usr/libexec/java_home`
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
local basedir=$(pwd)
local wdir=$(pwd)
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
wdir=$(cd "$wdir/.."; pwd)
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} "$@"
================================================
FILE: spring-boot-mongo/mvnw.cmd
================================================
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
set MAVEN_CMD_LINE_ARGS=%*
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
================================================
FILE: spring-boot-mongo/pom.xml
================================================
4.0.0
org.springframework.boot
spring-boot-starter-parent
1.5.8.RELEASE
de.codecentric
spring-boot-mongo
0.0.1-SNAPSHOT
jar
SpringBoot MongoDB REST
Demo project for Spring Boot MongoDB
UTF-8
UTF-8
1.8
0.4.11
org.springframework.boot
spring-boot-starter-data-mongodb
org.springframework.boot
spring-boot-starter-data-rest
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-actuator
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
docker
com.spotify
docker-maven-plugin
${docker-maven-plugin.version}
mongoboot/${project.artifactId}
${project.basedir}/src/main/docker
/
${project.build.directory}
${project.build.finalName}.jar
build-image
package
build
================================================
FILE: spring-boot-mongo/src/main/docker/Dockerfile
================================================
FROM java:8
VOLUME /tmp
ADD spring-boot-mongo*.jar mongorest.jar
RUN sh -c 'touch /mongorest.jar'
ENV JAVA_OPTS="-Xmx256m -Xms128m"
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /mongorest.jar" ]
================================================
FILE: spring-boot-mongo/src/main/java/de/codecentric/mongoboot/Item.java
================================================
package de.codecentric.mongoboot;
import org.springframework.data.mongodb.core.mapping.Field;
public class Item {
int quantity;
double price;
@Field("desc")
String description;
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
================================================
FILE: spring-boot-mongo/src/main/java/de/codecentric/mongoboot/Order.java
================================================
package de.codecentric.mongoboot;
import java.util.Date;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Field;
public class Order {
@Id String id;
@Field("custInfo")
String text;
@Field("date")
Date ordered;
List- items;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Date getOrdered() {
return ordered;
}
public void setOrdered(Date ordered) {
this.ordered = ordered;
}
public List
- getItems() {
return items;
}
public void setItems(List
- items) {
this.items = items;
}
}
================================================
FILE: spring-boot-mongo/src/main/java/de/codecentric/mongoboot/OrderRepository.java
================================================
package de.codecentric.mongoboot;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource()
public interface OrderRepository extends MongoRepository {
List findByText(@Param("name") String name);
}
================================================
FILE: spring-boot-mongo/src/main/java/de/codecentric/mongoboot/SpringBootMongoApplication.java
================================================
package de.codecentric.mongoboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootMongoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMongoApplication.class, args);
}
}
================================================
FILE: spring-boot-mongo/src/main/resources/application.properties
================================================
spring.data.rest.base-path=/rest
management.security.enabled=false
================================================
FILE: spring-boot-mongo/src/test/java/de/codecentric/mongoboot/SpringBootMongoApplicationTests.java
================================================
package de.codecentric.mongoboot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootMongoApplicationTests {
@Test
public void contextLoads() {
}
}
================================================
FILE: springdata-jpa/.gitignore
================================================
/target
/.settings
.classpath
.project
================================================
FILE: springdata-jpa/README.md
================================================
# Spring Data Blog Series
This projects holds the Java source examples for my blog post series on the Spring Data project:
* [GridFS Support in Spring Data MongoDB](http://blog.codecentric.de/en/2012/07/gridfs-support-in-spring-data-mongodb/)
* [Part 6: Spring Data Redis](http://blog.codecentric.de/en/2012/04/spring-data-redis/)
* [Part 5: Spring Data Neo4j](http://blog.codecentric.de/en/2012/02/spring-data-neo4j/)
* [Part 4: Geospatial Queries with Spring Data MongoDB](http://blog.codecentric.de/en/2012/02/spring-data-mongodb-geospatial-queries/)
* [Part 3: Spring Data MongoDB](http://blog.codecentric.de/en/2012/02/spring-data-mongodb/)
* [Part 2: Spring Data JPA](http://blog.codecentric.de/en/2012/01/spring-data-jpa/)
* [Part 1: Spring Data Commons](http://blog.codecentric.de/en/2011/12/spring-data-commons/)
## Usage
The projects are using a Maven based build. To run the tests on the command line use
mvn clean test
If you want to use an IDE like Eclipse run
mvn eclipse:eclipse
and set the Eclipse variable M2_REPO pointing to your local Maven repository. Or just import the project as an existing Maven project if you are using the m2 plugin.
================================================
FILE: springdata-jpa/pom.xml
================================================
4.0.0
de.codecentric
springdata-examples
1.0.0
springdata-jpa-examples
jar
Spring Data JPA Examples
https://github.com/ttrelle/spring-data-examples/tree/master/springdata-jpa
org.springframework.data
spring-data-jpa
1.9.4.RELEASE
org.hibernate
hibernate-entitymanager
4.2.21.Final
joda-time
joda-time
2.0
cglib
cglib-nodep
2.2
junit
junit
${junit.version}
test
org.springframework
spring-test
4.1.9.RELEASE
test
org.hsqldb
hsqldb
1.8.0.10
test
================================================
FILE: springdata-jpa/src/main/java/jpa/domain/User.java
================================================
package jpa.domain;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
@Entity
@NamedQueries( {
@NamedQuery( name="User.findByUser5", query = "SELECT u FROM User u where u.fullName = 'User 5'" ),
@NamedQuery( name="User.classicQuery", query = "SELECT u FROM User u where u.fullName = :fullName" )
})
public class User {
@Id private String id;
private String fullName;
private Date lastLogin;
public User() {}
public User(String id, String fullName) {
this.id = id;
this.fullName = fullName;
this.lastLogin = new Date();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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 (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
================================================
FILE: springdata-jpa/src/main/java/jpa/repo/ClassicUserRepository.java
================================================
package jpa.repo;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import jpa.domain.User;
import org.springframework.stereotype.Repository;
@Repository
public class ClassicUserRepository {
@PersistenceContext EntityManager em;
public List findByFullName(String fullName) {
return getEntityManger()
.createNamedQuery("User.classicQuery", User.class)
.setParameter("fullName", fullName)
.getResultList();
}
private EntityManager getEntityManger() {
return em;
}
}
================================================
FILE: springdata-jpa/src/main/java/jpa/repo/UserRepository.java
================================================
package jpa.repo;
import java.util.List;
import jpa.domain.User;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
public interface UserRepository extends JpaRepository {
List findByFullName(String fullName);
List findByFullName(String fullName, Sort sort);
List findByFullName(String fullName, Pageable paging);
List findByUser5();
List findByOrm();
@Transactional(timeout = 2, propagation = Propagation.REQUIRED)
@Query("SELECT u FROM User u WHERE u.fullName = 'User 3'")
List findByGivenQuery();
List findByIdAndFullName(@Param("id") String id, @Param("fullName") String fullname);
}
================================================
FILE: springdata-jpa/src/main/resources/META-INF/orm.xml
================================================
SELECT u FROM User u WHERE u.fullName = 'User 2'
================================================
FILE: springdata-jpa/src/main/resources/META-INF/persistence.xml
================================================
jpa.domain.User
================================================
FILE: springdata-jpa/src/test/java/jpa/repo/JpaRepoTest.java
================================================
package jpa.repo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.util.List;
import jpa.domain.User;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Tests for Spring Data JPA.
*
* @author Tobias Trelle
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class JpaRepoTest {
@Autowired UserRepository repo;
@Autowired ClassicUserRepository classicRepo;
@Before public void setUp() {
for ( int i = 0; i < 6; i++ ) {
repo.save( new User( String.format("user%02d", i), "User " + i ) );
}
}
@Test public void shouldUseClassicRepository() {
List users;
// when
users = classicRepo.findByFullName("User 1");
// then
assertUserByFullName(users, "User 1");
}
@Test public void shouldPageUsers() {
List users;
// when
Page page = repo.findAll( new PageRequest(2, 2 ) );
users = page.getContent();
// then
assertUserCount(users, 2);
}
@Test public void shouldFindByFullnameQuery() {
List users;
// when
users = repo.findByFullName("User 5");
// then
assertUserByFullName(users, "User 5");
}
@Test public void shouldFindByFullnameQueryWithSort() {
List users;
// when
users = repo.findByFullName("User 5", new Sort( new Sort.Order(Sort.Direction.DESC,"fullName")));
// then
assertUserByFullName(users, "User 5");
}
@Test public void shouldUseExistingNamedQuery() {
List users;
// when
users = repo.findByUser5();
// then
assertUserByFullName(users, "User 5");
}
@Test public void shouldUseXmlNamedQuery() {
List users;
// when
users = repo.findByOrm();
// then
assertUserByFullName(users, "User 2");
}
@Test public void shouldUseSpringDataQuery() {
List users;
// when
users = repo.findByGivenQuery();
// then
assertUserByFullName(users, "User 3");
}
@Test public void shouldIgnoreNullQueryParameters() {
List usersById, usersByFullName;
// when
usersById = repo.findByIdAndFullName("user01", null);
usersByFullName = repo.findByIdAndFullName(null, "User 01");
// then
assertUserCount(usersById, 0);
assertUserCount(usersByFullName, 0);
}
@Test public void shouldSortByTwoCriteria() {
List users;
// when
users = repo.findAll( new Sort(
new Sort.Order(Sort.Direction.ASC, "id"),
new Sort.Order(Sort.Direction.DESC, "fullName")
)
);
// then
assertUserCount(users, 6);
}
private static void assertUserByFullName(List users, String fullName) {
assertUserCount(users, 1);
assertThat( "Mismatch full name", users.get(0).getFullName(), is(fullName));
}
private static void assertUserCount(List users, int expected) {
assertThat( users, notNullValue() );
assertThat( "Mismatch user count", users.size(), is(expected));
}
}
================================================
FILE: springdata-jpa/src/test/resources/jpa/repo/JpaRepoTest-context.xml
================================================
================================================
FILE: springdata-mongodb/.gitignore
================================================
/target
/.settings
.classpath
.project
/maven-eclipse.xml
/.externalToolBuilders/
================================================
FILE: springdata-mongodb/README.md
================================================
# Spring Data Blog Series
This projects holds the Java source examples for my blog post series on the Spring Data project:
* [GridFS Support in Spring Data MongoDB](http://blog.codecentric.de/en/2012/07/gridfs-support-in-spring-data-mongodb/)
* [Part 6: Spring Data Redis](http://blog.codecentric.de/en/2012/04/spring-data-redis/)
* [Part 5: Spring Data Neo4j](http://blog.codecentric.de/en/2012/02/spring-data-neo4j/)
* [Part 4: Geospatial Queries with Spring Data MongoDB](http://blog.codecentric.de/en/2012/02/spring-data-mongodb-geospatial-queries/)
* [Part 3: Spring Data MongoDB](http://blog.codecentric.de/en/2012/02/spring-data-mongodb/)
* [Part 2: Spring Data JPA](http://blog.codecentric.de/en/2012/01/spring-data-jpa/)
* [Part 1: Spring Data Commons](http://blog.codecentric.de/en/2011/12/spring-data-commons/)
## Usage
The projects are using a Maven based build. To run the tests on the command line use
mvn clean test
If you want to use an IDE like Eclipse run
mvn eclipse:eclipse
and set the Eclipse variable M2_REPO pointing to your local Maven repository. Or just import the project as an existing Maven project if you are using the m2 plugin.
================================================
FILE: springdata-mongodb/pom.xml
================================================
4.0.0
de.codecentric
springdata-examples
1.0.0
springdata-mongodb-examples
jar
Spring Data MongoDB Examples
https://github.com/ttrelle/spring-data-examples/tree/master/springdata-mongodb
2.1.8.RELEASE
3.4.2
4.2.9.RELEASE
org.springframework.data
spring-data-mongodb
${spring.data.mongodb.version}
junit
junit
${junit.version}
test
org.springframework
spring-test
${spring.version}
test
src/misc/java
test-classes
src/misc/resources
test-classes
spring-snapshot
Spring Maven SNAPSHOT Repository
http://repo.springsource.org/libs-snapshot
================================================
FILE: springdata-mongodb/rs-dev0.yml
================================================
version: '3.4'
services:
# Primary
mongo1:
image: 'bitnami/mongodb:4.0.9'
container_name: 'rs-dev0-1'
environment:
- MONGODB_PORT_NUMBER=27001
- MONGODB_REPLICA_SET_NAME=dev0
- MONGODB_REPLICA_SET_MODE=primary
- MONGODB_ADVERTISED_HOSTNAME=mongo1
ports:
- "27001:27001"
# Secondary
mongo2:
image: 'bitnami/mongodb:4.0.9'
container_name: 'rs-dev0-2'
depends_on:
- mongo1
ports:
- "27002:27002"
environment:
- MONGODB_PORT_NUMBER=27002
- MONGODB_REPLICA_SET_NAME=dev0
- MONGODB_REPLICA_SET_MODE=secondary
- MONGODB_ADVERTISED_HOSTNAME=mongo2
- MONGODB_PRIMARY_HOST=mongo1
- MONGODB_PRIMARY_PORT_NUMBER=27001
# Arbiter
mongo3:
image: 'bitnami/mongodb:4.0.9'
container_name: 'rs-dev0-3'
depends_on:
- mongo1
ports:
- "27003:27003"
environment:
- MONGODB_PORT_NUMBER=27003
- MONGODB_REPLICA_SET_NAME=dev0
- MONGODB_REPLICA_SET_MODE=arbiter
- MONGODB_ADVERTISED_HOSTNAME=mongo3
- MONGODB_PRIMARY_HOST=mongo1
- MONGODB_PRIMARY_PORT_NUMBER=27001
volumes:
mongodb_master_data:
driver: local
================================================
FILE: springdata-mongodb/single-node.yml
================================================
version: "2"
services:
mongodb:
image: mongo:4.0.9
container_name: "mongodb"
volumes:
- ./datasets:/datasets
- ./uebungen:/uebungen
ports:
- 27017:27017
================================================
FILE: springdata-mongodb/src/main/bat/masterslave.bat
================================================
start mongod --rest --port 8000 --dbpath /var/master --replSet cluster0
start mongod --rest --port 8001 --dbpath /var/slave1 --replSet cluster0
start mongod --rest --port 8002 --dbpath /var/slave2 --replSet cluster0
================================================
FILE: springdata-mongodb/src/main/bat/shard.bat
================================================
start mongod --shardsvr --rest --port 9000 --dbpath /var/shard1
start mongod --shardsvr --rest --port 9001 --dbpath /var/shard2
start mongod --configsvr --rest --port 9002 --dbpath /var/conf1
pause
start mongos --port 9003 --configdb tmp-pc:9002 --chunkSize 1
================================================
FILE: springdata-mongodb/src/main/java/mongodb/Adresse.java
================================================
package mongodb;
public class Adresse {
}
================================================
FILE: springdata-mongodb/src/main/java/mongodb/PointOfInterest.java
================================================
package mongodb;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Document(collection = "pois")
public class PointOfInterest {
@Indexed private String typ;
private String tags;
@Field("desc") private String description;
private Adresse adresse;
private Point location;
public String getTyp() {
return typ;
}
public void setTyp(String typ) {
this.typ = typ;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Adresse getAdresse() {
return adresse;
}
public void setAdresse(Adresse adresse) {
this.adresse = adresse;
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
}
================================================
FILE: springdata-mongodb/src/main/java/mongodb/geo/Location.java
================================================
package mongodb.geo;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
/**
* A named location, using GeoJSON API.
* @author Tobias Trelle
*/
public class Location {
@Id private String id;
private GeoJsonPoint position;
public Location() {}
public Location(String id, double x, double y) {
this.id = id;
this.position = new GeoJsonPoint(x,y);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public GeoJsonPoint getPosition() {
return position;
}
public void setPosition(GeoJsonPoint pos) {
this.position = pos;
}
@Override
public String toString() {
return String.format("%s(%1.3f, %1.3f)", id, position.getX(), position.getY());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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;
Location other = (Location) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
================================================
FILE: springdata-mongodb/src/main/java/mongodb/geo/LocationRepository.java
================================================
package mongodb.geo;
import java.util.List;
import org.springframework.data.geo.Box;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
* Example of a repo using geospatial queries.
*
* @author Tobias Trelle
*/
public interface LocationRepository extends MongoRepository {
List findByPositionWithin(Circle c);
List findByPositionWithin(Box b);
List findByPositionNear(Point p, Distance d);
}
================================================
FILE: springdata-mongodb/src/main/java/mongodb/order/Item.java
================================================
package mongodb.order;
import org.springframework.data.mongodb.core.mapping.Field;
public class Item {
private int quantity;
private double price;
@Field("desc") private String description;
public Item() {
}
public Item(int quantity, double price, String description) {
super();
this.quantity = quantity;
this.price = price;
this.description = description;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
================================================
FILE: springdata-mongodb/src/main/java/mongodb/order/Order.java
================================================
package mongodb.order;
import java.util.Date;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Field;
public class Order {
@Id private String id;
private Date date;
@Field("custInfo") private String customerInfo;
List
- items;
public Order() {
this(null);
}
public Order(String customerInfo) {
super();
this.customerInfo = customerInfo;
}
public Order(String id, String customerInfo) {
this(customerInfo);
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getCustomerInfo() {
return customerInfo;
}
public void setCustomerInfo(String customerInfo) {
this.customerInfo = customerInfo;
}
public List
- getItems() {
return items;
}
public void setItems(List
- items) {
this.items = items;
}
}
================================================
FILE: springdata-mongodb/src/main/java/mongodb/order/OrderBeforeSaveListener.java
================================================
package mongodb.order;
import java.util.Date;
import org.bson.Document;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent;
import com.mongodb.DBObject;
/**
* Equivalent of a domain method annotated by
PrePersist.
*
* This handler shows how to implement your custom UUID generation.
* @author Tobias Trelle
*/
public class OrderBeforeSaveListener extends AbstractMongoEventListener {
@Override
public void onBeforeSave(BeforeSaveEvent event) {
Order o = event.getSource();
Document d = event.getDocument();
if ( o.getId() == null ) {
// TODO use a better UUID generator in production
d.put("_id","" + Math.random() );
}
if ( o.getDate() == null ) {
d.put("date", new Date());
}
}
}
================================================
FILE: springdata-mongodb/src/main/java/mongodb/order/OrderRepository.java
================================================
package mongodb.order;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
public interface OrderRepository extends MongoRepository {
List findByItemsQuantity(int quantity);
@Query("{ \"items.quantity\": ?0 }")
List findWithQuery(int quantity);
@Query( value = "{ custInfo: ?0 }", fields = "{_id:0, items:1}")
List findOnlyItems(String name);
}
================================================
FILE: springdata-mongodb/src/main/java/mongodb/user/User.java
================================================
package mongodb.user;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class User {
@Id
private String id;
@Indexed(unique=true)
private String fullName;
private Date lastLogin;
public User() {}
public User(String id, String fullName) {
this.id = id;
this.fullName = fullName;
this.lastLogin = new Date();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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 (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
================================================
FILE: springdata-mongodb/src/main/java/mongodb/user/UserRepository.java
================================================
package mongodb.user;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
public interface UserRepository extends MongoRepository {
@Query("{ fullName: ?0 }")
List findByTheUsersFullName(String fullName);
List findByFullNameLike(String fullName, Sort sort);
}
================================================
FILE: springdata-mongodb/src/misc/java/mongodb/CappedCollectionManipulationTest.java
================================================
package mongodb;
import static org.hamcrest.core.Is.*;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.CollectionOptions;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* This test shows that deletes and updates to capped collections fail silently.
*
* To run this test, a local mongod instance is required using the standard port.
*
* @author Tobias Trelle
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class CappedCollectionManipulationTest {
private static final String COLLECTION_NAME = "user";
@Autowired UserRepository repo;
@Autowired MongoOperations template;
/**
* Create a capped collection.
* If you create an uncapped collections the tests go green.
*/
@Before
public void setUp() {
template.dropCollection(COLLECTION_NAME);
// capped
template.createCollection(COLLECTION_NAME, new CollectionOptions(1000,5,true));
// uncapped
//template.createCollection(COLLECTION_NAME);
}
@Test
public void does_not_delete_from_capped_collection() {
// given
for ( int i = 0; i< 5; i++ ) {
repo.save(new User("user"+i, "Herr User Nr. " +i));
}
// when
repo.delete("user0");
// then
assertNull("User not deleted", repo.findOne("user0"));
}
@Test
public void does_not_update_capped_collection() {
// given
for ( int i = 0; i< 5; i++ ) {
repo.save(new User("user"+i, "Herr User Nr. " +i));
}
// when
User user;
user = repo.findOne("user0");
user.setFullName( "Something completely different" );
repo.save(user);
user = repo.findOne("user0");
// then
assertThat("Fullname mismatch",
user.getFullName(), is("Something completely different") );
}
}
================================================
FILE: springdata-mongodb/src/misc/java/mongodb/MongoDBMassTest.java
================================================
package mongodb;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.Box;
import org.springframework.data.mongodb.core.geo.Circle;
import org.springframework.data.mongodb.core.geo.Point;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Tests for Spring Data MongoDB - Geospatial queries.
*
* @author Tobias
* Trelle
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MongoDBMassTest {
private static final int N_POINTS = 100000;
private static final int N_QUERIES = 10000;
/** Radius for circle search. */
private static final double RADIUS = 0.1;
/** Half the width of a box with the same area as a circle with r = {@link #RADIUS}. */
private static final double HALF_BOX_WIDTH = RADIUS * Math.sqrt(Math.PI) / 2;
@Autowired
LocationRepository repo;
@Autowired
MongoTemplate template;
@Before
public void setUp() {
final List locations = new ArrayList();
// ensure geospatial index
template.indexOps(Location.class).ensureIndex( new GeospatialIndex("position") );
// prepare data
for ( int i = 0; i < N_POINTS; i++ ) {
locations.add( new Location(String.valueOf(i), rnd(), rnd()) );
}
out("Preparing data (" + N_POINTS + " locations) ...");
repo.save(locations);
out("Done.");
}
@Test
public void shouldPerformRandomQueries() {
long time_circle = 0;
long time_box = 0;
long singleRun = 0;
Circle c;
Box b;
long n_circle = 0;
long n_box = 0;
List result;
out( "Performing " + N_QUERIES + " queries ..." );
for (int i = 0; i < N_QUERIES; i++) {
double x = rnd(), y = rnd();
// circle search
c = new Circle( x, y, RADIUS);
// box search
b = new Box( new Point(x - HALF_BOX_WIDTH, y - HALF_BOX_WIDTH), new Point(x + HALF_BOX_WIDTH, y + HALF_BOX_WIDTH) );
// perform circle query
singleRun = System.currentTimeMillis();
result = repo.findByPositionWithin(c);
singleRun = System.currentTimeMillis() - singleRun;
n_circle += result.size();
time_circle += singleRun;
// peform box search
singleRun = System.currentTimeMillis();
result = repo.findByPositionWithin(b);
singleRun = System.currentTimeMillis() - singleRun;
n_box += result.size();
time_box += singleRun;
}
out( "Done.\n" );
out( "Search by circle:" );
out( "Overall time for " + N_QUERIES + " queries [ms]: " + time_circle );
out( "Average time per query [ms]: " + (double)time_circle / N_QUERIES );
out( "Average hits per query: " + n_circle / N_QUERIES );
out( "" );
out( "Search by box:" );
out( "Overall time for " + N_QUERIES + " queries [ms]: " + time_box );
out( "Average time per query [ms]: " + (double)time_box / N_QUERIES );
out( "Average hits per query: " + n_box / N_QUERIES );
}
@After
public void tearDown() {
repo.deleteAll();
}
private static double rnd() {
return 2 * Math.random() -1;
}
private static void out(Object o) {
System.out.println(o);
}
}
================================================
FILE: springdata-mongodb/src/misc/resources/CappedCollectionManipulationTest-context.xml
================================================
================================================
FILE: springdata-mongodb/src/misc/resources/MongoDBMassTest-context.xml
================================================
================================================
FILE: springdata-mongodb/src/test/java/mongodb/config/LocalhostMongoConfiguration.java
================================================
package mongodb.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import mongodb.order.OrderBeforeSaveListener;
/**
* Test configuration using localhost:27017
* @author Tobias Trelle
*/
@Configuration
@EnableMongoRepositories({"mongodb.geo", "mongodb.order", "mongodb.user"})
public class LocalhostMongoConfiguration extends AbstractMongoConfiguration {
@Bean
public OrderBeforeSaveListener beforeSaveListener() {
return new OrderBeforeSaveListener();
}
@Override
protected String getDatabaseName() {
return "odm_springdata";
}
@Override
public MongoClient mongoClient() {
return new MongoClient();
}
}
================================================
FILE: springdata-mongodb/src/test/java/mongodb/config/LocalhostMongoGridFSConfiguration.java
================================================
package mongodb.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
/**
* Test configuration for GridFS using localhost:27017
* @author Tobias Trelle
*/
@Configuration
public class LocalhostMongoGridFSConfiguration extends LocalhostMongoConfiguration {
@Bean
public GridFsTemplate gridTemplate() throws Exception {
return new GridFsTemplate( mongoDbFactory(), mappingMongoConverter() );
}
}
================================================
FILE: springdata-mongodb/src/test/java/mongodb/geo/LocationRepositoryTest.java
================================================
package mongodb.geo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Box;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
import org.springframework.data.mongodb.core.index.GeospatialIndex;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import mongodb.config.LocalhostMongoConfiguration;
/**
* Tests for Spring Data MongoDB - Geospatial queries.
*
* @author Tobias
* Trelle
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=LocalhostMongoConfiguration.class)
public class LocationRepositoryTest {
private static final Point DUS = new Point( 6.810036, 51.224088 );
@Autowired
private MongoTemplate template;
@Autowired
LocationRepository repo;
@Before public void setUp() {
template
.indexOps(Location.class)
.ensureIndex(new GeospatialIndex("position").typed(GeoSpatialIndexType.GEO_2DSPHERE));
// prepare data
repo.save( new Location("A", 0.001, -0.002) );
repo.save( new Location("B", 1, 1) );
repo.save( new Location("C", 0.5, 0.5) );
repo.save( new Location("D", -0.5, -0.5) );
repo.save( new Location("Berlin", 13.405838, 52.531261 ));
repo.save( new Location("Cologne", 6.921272, 50.960157 ));
repo.save( new Location("Düsseldorf", 6.810036, 51.224088 ) );
}
@Test public void shouldFindSelf() {
// when
List locations = repo.findByPositionNear(DUS , new Distance(1, Metrics.KILOMETERS) );
// then
assertLocations(locations, "Düsseldorf");
}
@Test public void shouldFindCologne() {
// when
List locations = repo.findByPositionNear(DUS , new Distance(70, Metrics.KILOMETERS) );
// then
assertLocations(locations, "Düsseldorf", "Cologne");
}
@Test public void shouldFindCologneAndBerlin() {
// when
List locations = repo.findByPositionNear(DUS , new Distance(350, Metrics.MILES) );
// then
assertLocations(locations, "Düsseldorf", "Cologne", "Berlin");
}
@Test public void shouldFindAll() {
// when
List locations = repo.findAll();
// then
assertLocations(locations, "A", "B", "C", "D", "Berlin", "Cologne", "Düsseldorf");
}
@Test public void shouldFindAroundOrigin() {
// when
List locations = repo.findByPositionWithin(new Circle(0, 0, 0.75));
// then
assertLocations(locations, "A", "C", "D");
}
@Test public void shouldFindWithinBox() {
// when
List locations = repo.findByPositionWithin(new Box(new Point(
0.25, 0.25), new Point(1, 1)));
// then
assertLocations(locations, "B", "C");
}
@After
public void tearDown() {
//repo.deleteAll();
}
private static void assertLocations(List locations, String... ids) {
assertThat( locations, notNullValue() );
out("-----------------------------");
for (Location l : locations) {
out(l);
}
assertThat("Mismatch location count", ids.length, is(locations.size()));
for (String id : ids) {
assertThat("Location " + id + " not found",
locations.contains(new Location(id, 0, 0)), is(true));
}
}
private static void out(Object o) {
System.out.println(o);
}
}
================================================
FILE: springdata-mongodb/src/test/java/mongodb/order/OrderRepositoryTest.java
================================================
package mongodb.order;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import mongodb.config.LocalhostMongoConfiguration;
import mongodb.order.Item;
import mongodb.order.Order;
import mongodb.order.OrderRepository;
/**
* Test cases for the {@link OrderRepository}.
*
* @author Tobias Trelle
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=LocalhostMongoConfiguration.class)
public class OrderRepositoryTest {
@Autowired OrderRepository repo;
@Before public void setUp() {
repo.deleteAll();
}
@Test public void shouldFindByItemsQuantity() {
// given
Order order = new Order("Tobias Trelle, gold customer");
List- items = new ArrayList
- ();
items.add( new Item(1, 47.11, "Item #1") );
items.add( new Item(2, 42.0, "Item #2") );
order.setItems(items);
repo.save(order);
// when
List orders = repo.findByItemsQuantity(2);
// then
assertThat(orders, notNullValue());
assertThat(orders.size(), is(1));
}
@Test public void shouldFindByAnnotatedQuery() {
// given
Order order = new Order("Tobias Trelle, gold customer");
List
- items = new ArrayList
- ();
items.add( new Item(1, 47.11, "Item #1") );
items.add( new Item(2, 42.0, "Item #2") );
order.setItems(items);
repo.save(order);
// when
List orders = repo.findWithQuery(2);
// then
assertThat(orders, notNullValue());
assertThat(orders.size(), is(1));
}
@Test public void use_field_projection() {
// given
Order order = new Order("Tobias Trelle, gold customer");
List
- items = new ArrayList
- ();
items.add( new Item(1, 47.11, "Item #1") );
items.add( new Item(2, 42.0, "Item #2") );
order.setItems(items);
repo.save(order);
// when
List orders = repo.findOnlyItems("Tobias Trelle, gold customer");
// then
assertThat(orders, notNullValue());
assertThat(orders.size(), is(1));
order = orders.get(0);
assertThat(order.getId(), nullValue());
assertThat(order.getCustomerInfo(), nullValue());
assertThat(order.getDate(), nullValue());
items = order.getItems();
assertThat(items, notNullValue());
assertThat(items.size(), is(2));
Item item = items.get(0);
assertThat( item.getDescription(), notNullValue());
assertThat( item.getPrice(), notNullValue());
assertThat( item.getQuantity(), notNullValue());
}
}
================================================
FILE: springdata-mongodb/src/test/java/mongodb/order/OrderSubListTest.java
================================================
package mongodb.order;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.project;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import mongodb.config.LocalhostMongoConfiguration;
import mongodb.order.Item;
import mongodb.order.Order;
import mongodb.order.OrderRepository;
/**
* Test cases for aggregations.
*
* @author Tobias Trelle
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=LocalhostMongoConfiguration.class)
public class OrderSubListTest {
@Autowired OrderRepository repo;
@Autowired MongoOperations template;
@Before public void setUp() {
repo.deleteAll();
}
@Test public void projection_by_aggregation() {
// given
Order order = new Order("Tobias Trelle, gold customer");
List
- items = new ArrayList
- ();
items.add( new Item(1, 47.11, "Item #1") );
items.add( new Item(2, 42.0, "Item #2") );
order.setItems(items);
repo.save(order);
// when
Aggregation agg = newAggregation(
project("items").andExclude("_id")
);
AggregationResults result = template.aggregate(agg, Order.class, Order.class);
// then
assertThat(result, notNullValue());
List orders = result.getMappedResults();
assertThat(orders, notNullValue());
assertThat(orders.size(), is(1));
items = orders.get(0).getItems();
assertThat(items, notNullValue());
assertThat(items.size(), is(2));
}
@Test public void projection_by_query() {
// given
Order order = new Order("Tobias Trelle, gold customer");
List
- items = new ArrayList
- ();
items.add( new Item(1, 47.11, "Item #1") );
items.add( new Item(2, 42.0, "Item #2") );
order.setItems(items);
repo.save(order);
// when
Aggregation agg = newAggregation(
project("items").andExclude("_id")
);
AggregationResults result = template.aggregate(agg, Order.class, Order.class);
// then
assertThat(result, notNullValue());
List orders = result.getMappedResults();
assertThat(orders, notNullValue());
assertThat(orders.size(), is(1));
items = orders.get(0).getItems();
assertThat(items, notNullValue());
assertThat(items.size(), is(2));
}
}
================================================
FILE: springdata-mongodb/src/test/java/mongodb/user/IndexViolationTest.java
================================================
package mongodb.user;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import mongodb.config.LocalhostMongoConfiguration;
import mongodb.user.User;
import mongodb.user.UserRepository;
/**
* This test shows that violation on indexes are ignored.
*
* To run this test, a local mongod instance is required using the standard port.
*
* @author Tobias Trelle
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=LocalhostMongoConfiguration.class)
public class IndexViolationTest {
private static final String COLLECTION_NAME = "user";
@Autowired UserRepository repo;
@Autowired MongoOperations template;
/**
* Create a target collection.
*/
@Before
public void setUp() {
template.dropCollection(COLLECTION_NAME);
template.createCollection(COLLECTION_NAME);
template.indexOps(COLLECTION_NAME).ensureIndex(new Index().on("fullName", Direction.ASC).unique());
}
@Test
public void does_not_detect_index_violation_on_id() {
// given
repo.save( new User("0", "User 0") ); // 1st param = _id field, 2nd = unique secondary index
// when
repo.save( new User("0", "User 1") );
// then
}
}
================================================
FILE: springdata-mongodb/src/test/java/mongodb/user/UserRepositoryTest.java
================================================
package mongodb.user;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import mongodb.config.LocalhostMongoConfiguration;
import mongodb.user.User;
import mongodb.user.UserRepository;
/**
* Tests for Spring Data MongoDB.
*
* @author Tobias Trelle
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=LocalhostMongoConfiguration.class)
public class UserRepositoryTest {
@Autowired UserRepository repo;
@Autowired MongoTemplate template;
@Before public void setUp() {
template.dropCollection("user");
template.createCollection("user");
repo.save(new User("root", "Superuser"));
for ( int i = 0; i < 6; i++ ) {
repo.save( new User( String.format("user%02d", i), "User " + i ) );
}
}
@Test public void shouldFindByCustomerQuery() {
List users;
// when
users = repo.findByTheUsersFullName("User 0");
// then
assertUserByFullName(users, "User 0");
}
@Test public void shouldFindByFullNameLike() {
List users;
// when
users = repo.findByFullNameLike("User", null);
// then
assertUserCount(users, 6);
}
@Test public void shouldPageUsers() {
List users;
// when
Page page = repo.findAll( new PageRequest(2, 2 ) );
users = page.getContent();
// then
assertUserCount(users, 2);
}
@After public void tearDown() {
repo.deleteAll();
}
private static void assertUserByFullName(List users, String fullName) {
assertUserCount(users, 1);
assertThat( "Mismatch full name", users.get(0).getFullName(), is(fullName));
}
private static void assertUserCount(List users, int expected) {
assertThat( users, notNullValue() );
assertThat( "Mismatch user count", users.size(), is(expected));
}
}
================================================
FILE: springdata-mongodb/src/test/resources/dummy.txt
================================================
A file to be uploaded via GridFS ....
================================================
FILE: springdata-neo4j/.gitignore
================================================
/target
/.settings
.classpath
.project
================================================
FILE: springdata-neo4j/README.md
================================================
# Spring Data Blog Series
This projects holds the Java source examples for my blog post series on the Spring Data project:
* [GridFS Support in Spring Data MongoDB](http://blog.codecentric.de/en/2012/07/gridfs-support-in-spring-data-mongodb/)
* [Part 6: Spring Data Redis](http://blog.codecentric.de/en/2012/04/spring-data-redis/)
* [Part 5: Spring Data Neo4j](http://blog.codecentric.de/en/2012/02/spring-data-neo4j/)
* [Part 4: Geospatial Queries with Spring Data MongoDB](http://blog.codecentric.de/en/2012/02/spring-data-mongodb-geospatial-queries/)
* [Part 3: Spring Data MongoDB](http://blog.codecentric.de/en/2012/02/spring-data-mongodb/)
* [Part 2: Spring Data JPA](http://blog.codecentric.de/en/2012/01/spring-data-jpa/)
* [Part 1: Spring Data Commons](http://blog.codecentric.de/en/2011/12/spring-data-commons/)
## Usage
The projects are using a Maven based build. To run the tests on the command line use
mvn clean test
If you want to use an IDE like Eclipse run
mvn eclipse:eclipse
and set the Eclipse variable M2_REPO pointing to your local Maven repository. Or just import the project as an existing Maven project if you are using the m2 plugin.
================================================
FILE: springdata-neo4j/pom.xml
================================================
4.0.0
de.codecentric
springdata-examples
1.0.0
springdata-neo4j-examples
jar
Spring Data Neo4j Examples
http://maven.apache.org
2.2.5
org.springframework.data
spring-data-neo4j
4.0.0.RELEASE
junit
junit
${junit.version}
test
org.springframework.data
spring-data-neo4j
4.0.0.RELEASE
test-jar
test
org.neo4j
neo4j-kernel
${neo4j.version}
test-jar
test
org.neo4j.test
neo4j-harness
${neo4j.version}
test
org.neo4j.app
neo4j-server
${neo4j.version}
test-jar
test
org.neo4j
neo4j-ogm
1.1.2
test-jar
test
cglib
cglib
2.2.2
javax.validation
validation-api
1.1.0.Final
org.springframework
spring-test
4.1.9.RELEASE
test
================================================
FILE: springdata-neo4j/src/main/java/neo4j/domain/User.java
================================================
package neo4j.domain;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.Index;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
/** Simple user class. */
@NodeEntity public class User {
@GraphId Long id;
@Index private String login;
private String fullName;
private Date lastLogin;
@Relationship(type = "knows")
Set friends;
public User() {}
public User(String login, String fullName) {
this.login = login;
this.fullName = fullName;
this.lastLogin = new Date();
this.friends = new HashSet();
}
public void knows(User user) {
friends.add(user);
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Set getFriends() {
return friends;
}
public void setFriends(Set friends) {
this.friends = friends;
}
public void setId(Long id) {
this.id = id;
}
}
================================================
FILE: springdata-neo4j/src/main/java/neo4j/repo/UserRepository.java
================================================
package neo4j.repo;
import java.util.List;
import neo4j.domain.User;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.GraphRepository;
/** Neo4j repository. */
public interface UserRepository extends GraphRepository {
User findByLogin(String login);
@Query("START root=node:User(login = 'root') MATCH root-[:knows]->friends RETURN friends")
List findFriendsOfRoot();
}
================================================
FILE: springdata-neo4j/src/test/java/neo4j/repo/Neo4jRepoTest.java
================================================
package neo4j.repo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.HashMap;
import java.util.List;
import neo4j.domain.User;
import neo4j.repo.UserRepository;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.neo4j.ogm.session.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.neo4j.template.Neo4jOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Neo4jTestConfig.class)
public class Neo4jRepoTest {
private static final int USER_COUNT = 4;
@Autowired
Neo4jOperations template;
@Autowired
UserRepository repo;
private long rootId;
@Before
public void setUp() {
// create index User(login)
Result result = template.query("CREATE INDEX ON :User(login)", new HashMap() );
User root = new User("root", "Superuser");
User[] user = new User[USER_COUNT];
for (int i = 0; i < user.length; i++) {
user[i] = new User(String.format("user%02d", i), "User" + i);
}
// build graph
for (int i = 0; i < user.length; i++) {
root.knows(user[i]);
for (int j = i; j < user.length; j++) {
user[i].knows(user[j]);
}
}
// save nodes
for (int i = 0; i < user.length; i++) {
repo.save(user[i]);
}
repo.save(root);
rootId = root.getId();
out("Root id: " + rootId);
}
@Test
public void shouldFindAll() {
// when
long n = repo.count();
// then
assertEquals("User count mismatch", USER_COUNT + 1, n);
}
@Test
public void shouldFindRootUserById() {
// when
User root = repo.findOne(rootId);
// then
assertNotNull("Root user not found", root);
}
@Test
public void shouldFindRootUserByLogin() {
// when
User root = repo.findByLogin("root");
// then
assertNotNull("Root user not found", root);
}
// TODO fixme
// Caused by: org.neo4j.ogm.session.result.ResultProcessingException: "errors":[{"code":"Neo.ClientError.Schema.NoSuchIndex
// ","message":"Index `User` does not exist"}]}
@Test
@Ignore
public void shouldFindFriendsOfRoot() {
// when
List users = repo.findFriendsOfRoot();
// then
assertNotNull("result is ", users);
assertEquals("mismatch @ friend count", USER_COUNT, users.size());
}
@After
public void tearDown() {
repo.deleteAll();
}
private static void out(Object o) {
System.out.println(o);
}
}
================================================
FILE: springdata-neo4j/src/test/java/neo4j/repo/Neo4jTestConfig.java
================================================
package neo4j.repo;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.server.InProcessServer;
import org.springframework.data.neo4j.server.Neo4jServer;
import org.springframework.data.neo4j.template.Neo4jTemplate;
@Configuration
@EnableNeo4jRepositories("neo4j.repo")
public class Neo4jTestConfig extends Neo4jConfiguration {
@Override
public Neo4jServer neo4jServer() {
return new InProcessServer();
}
@Override
public SessionFactory getSessionFactory() {
return new SessionFactory("neo4j.domain");
}
}
================================================
FILE: springdata-redis/.gitignore
================================================
/target
/.settings
.classpath
.project
================================================
FILE: springdata-redis/README.md
================================================
# Spring Data Blog Series
This projects holds the Java source examples for my blog post series on the Spring Data project:
* [GridFS Support in Spring Data MongoDB](http://blog.codecentric.de/en/2012/07/gridfs-support-in-spring-data-mongodb/)
* [Part 6: Spring Data Redis](http://blog.codecentric.de/en/2012/04/spring-data-redis/)
* [Part 5: Spring Data Neo4j](http://blog.codecentric.de/en/2012/02/spring-data-neo4j/)
* [Part 4: Geospatial Queries with Spring Data MongoDB](http://blog.codecentric.de/en/2012/02/spring-data-mongodb-geospatial-queries/)
* [Part 3: Spring Data MongoDB](http://blog.codecentric.de/en/2012/02/spring-data-mongodb/)
* [Part 2: Spring Data JPA](http://blog.codecentric.de/en/2012/01/spring-data-jpa/)
* [Part 1: Spring Data Commons](http://blog.codecentric.de/en/2011/12/spring-data-commons/)
## Usage
The projects are using a Maven based build. To run the tests on the command line use
mvn clean test
If you want to use an IDE like Eclipse run
mvn eclipse:eclipse
and set the Eclipse variable M2_REPO pointing to your local Maven repository. Or just import the project as an existing Maven project if you are using the m2 plugin.
================================================
FILE: springdata-redis/pom.xml
================================================
4.0.0
de.codecentric
springdata-examples
1.0.0
springdata-redis-examples
jar
Spring Data Redis Examples
https://github.com/ttrelle/spring-data-examples/tree/master/springdata-redis
org.springframework.data
spring-data-redis
1.6.4.RELEASE
org.slf4j
slf4j-simple
1.7.13
junit
junit
${junit.version}
test
org.springframework
spring-test
4.1.9.RELEASE
test
redis.clients
jedis
2.7.3
org.apache.commons
commons-pool2
2.2
test
org.codehaus.jackson
jackson-mapper-asl
1.8.8
test
com.fasterxml.jackson.core
jackson-core
2.6.4
test
com.fasterxml.jackson.core
jackson-databind
2.6.4
test
================================================
FILE: springdata-redis/src/main/java/redis/StringStringRepository.java
================================================
package redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
/**
* Simple repository to store key/value pairs of type String/String.
* @author tobias.trelle
*/
public class StringStringRepository {
@Autowired
private RedisTemplate template;
public void add(String key, String value) {
template.opsForValue().set(key, value);
}
public String getValue(String key) {
return template.opsForValue().get(key);
}
public void delete(String key) {
template.opsForValue().getOperations().delete(key);
}
}
================================================
FILE: springdata-redis/src/main/java/redis/User.java
================================================
package redis;
import java.util.Date;
/** Simple user class. */
public class User {
private String login;
private String fullName;
private Date lastLogin;
public User() {}
public User(String login, String fullName) {
this.login = login;
this.fullName = fullName;
this.lastLogin = new Date();
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
}
================================================
FILE: springdata-redis/src/main/java/redis/UserRepository.java
================================================
package redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
/**
* Repository for key/value pairs of type String/User.
* @author tobias.trelle
*/
public class UserRepository {
@Autowired
private RedisTemplate template;
public void add(User user) {
template.opsForValue().set(user.getLogin(), user);
}
public User get(String key) {
return template.opsForValue().get(key);
}
}
================================================
FILE: springdata-redis/src/test/java/redis/StringStringRepositoryTest.java
================================================
package redis;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class StringStringRepositoryTest {
@Autowired StringStringRepository repo;
@Before
public void setUp() {
repo.add("foo", "bar");
}
@Test
public void shouldFindValue() {
String value = repo.getValue("foo");
assertNotNull("Value is ", value);
assertEquals( "Value mismatch" , "bar", value);
}
}
================================================
FILE: springdata-redis/src/test/java/redis/UserRepositoryTest.java
================================================
package redis;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class UserRepositoryTest {
@Autowired UserRepository repo;
@Before
public void setUp() {
repo.add( new User("root", "Superuser") );
}
@Test
public void shouldFindValue() {
User user = repo.get("root");
assertNotNull("Value is ", user);
assertEquals( "login mismatch" , "root", user.getLogin());
assertEquals( "login mismatch" , "Superuser", user.getFullName());
}
}
================================================
FILE: springdata-redis/src/test/resources/redis/StringStringRepositoryTest-context.xml
================================================
================================================
FILE: springdata-redis/src/test/resources/redis/UserRepositoryTest-context.xml
================================================