Full Code of ttrelle/spring-data-examples for AI

master 80b3e307c4a6 cached
83 files
98.5 KB
29.6k tokens
249 symbols
1 requests
Download .txt
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 ##
[![Build Status](https://travis-ci.org/ttrelle/spring-data-examples.png?branch=master)](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
================================================
<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>de.codecentric</groupId>
		<artifactId>springdata-examples</artifactId>
		<version>1.0.0</version>
	</parent>
	<artifactId>mongodriver</artifactId>
	<properties>
		<!-- see
		https://docs.mongodb.com/manual/release-notes/4.0/?_ga=2.185922027.371293580.1535706960-1835450239.1502345082#drivers
		 -->
		<mongo.driver.version>3.10.0</mongo.driver.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>${mongo.driver.version}</version>
		</dependency>
	</dependencies>
</project>


================================================
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<Document> collection = db.getCollection("order");
		
		insert(collection);
		find(mongo);
	}
	
	private static void insert(MongoCollection<Document> collection) {
		Document order;
		List<Document> items = new ArrayList<Document>();
		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<Document> collection = db.getCollection("order");
		Bson query;
		FindIterable<Document> 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<Document> 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<WriteModel<Document>> createBulk() {
		final List<WriteModel<Document>> ops = new ArrayList<WriteModel<Document>>();
		Document payload;
		
		for(int i=0; i<BULK_SIZE; i++) {
			payload = new Document();
			payload.put("i", i);
			payload.put("t", new Date());
			
			ops.add( new InsertOneModel<Document>(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<String> colls = db.listCollectionNames();
			for (String s : colls) {
			    println(s);
			}
			
			// use collection "foo"
			MongoCollection<Document> collection = db.getCollection("foo");
			
			insert(collection);
			find(collection);
			
			// remove(collection);
			// bsonize();
			} finally {
				if (mongo != null) {
					mongo.close();
				}
			}
	}
	
	private static void remove(MongoCollection<Document> 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<Document> collection) {
		// Document speichern
		Document doc = new Document();
		doc.put("date", new Date());
		doc.put("i", 42);
		
		collection.insertOne(doc);
	}
	
	private static void find(MongoCollection<Document> collection) {
		FindIterable<Document> cursor;
		
		// alle Dokumente
		cursor = collection.find();

		for ( Document document: cursor ) {
			println(document);
		}
	}

	private static void find(MongoCollection<Document> collection, Bson query) {
		FindIterable<Document> 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<Document> 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<Document> eventCollection = 
    				client.getDatabase("test").getCollection("events");
	
    		ChangeStreamIterable<Document> 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<Document> 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
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>de.codecentric</groupId>
	<artifactId>springdata-examples</artifactId>
	<version>1.0.0</version>
	<packaging>pom</packaging>

	<name>Spring Data Examples</name>

	<modules>
		<module>springdata-mongodb</module>
		<module>springdata-redis</module>
		<module>springdata-neo4j</module>
		<module>springdata-jpa</module>
		<module>spring-boot-mongo</module>
		<module>mongodriver</module>
	</modules>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
		<junit.version>4.12</junit.version>		
	</properties>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<organization>
		<name>codecentric AG</name>
		<url>http://www.codecentric.de</url>
	</organization>

	<developers>
		<developer>
			<name>Tobias Trelle</name>
			<email>tobias.trelle@codecentric.de</email>
		</developer>
	</developers>

</project>


================================================
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
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.8.RELEASE</version>
		<relativePath/>
	</parent>

	<groupId>de.codecentric</groupId>
	<artifactId>spring-boot-mongo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>SpringBoot MongoDB REST</name>
	<description>Demo project for Spring Boot MongoDB</description>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
        <docker-maven-plugin.version>0.4.11</docker-maven-plugin.version>		
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-rest</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

	<profiles>
		<profile>
			<id>docker</id>
			<build>
				<plugins>
			        <plugin>
			            <groupId>com.spotify</groupId>
			            <artifactId>docker-maven-plugin</artifactId>
			            <version>${docker-maven-plugin.version}</version>	
			            <configuration>
			                <imageName>mongoboot/${project.artifactId}</imageName>
			                <dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
			                <resources>
			                    <resource>
			                        <targetPath>/</targetPath>
			                        <directory>${project.build.directory}</directory>
			                        <include>${project.build.finalName}.jar</include>
			                    </resource>
			                </resources>
			            </configuration>
			            <executions>
			                <execution>
			                    <id>build-image</id>
			                    <phase>package</phase>
			                    <goals>
			                        <goal>build</goal>
			                    </goals>
			                </execution>
			            </executions>
			        </plugin>	
				</plugins>
			</build>
		</profile>
	</profiles>

</project>


================================================
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<Item> 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<Item> getItems() {
		return items;
	}

	public void setItems(List<Item> 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<Order, String> {

	List<Order> 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
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>de.codecentric</groupId>
		<artifactId>springdata-examples</artifactId>
		<version>1.0.0</version>
	</parent>

	<artifactId>springdata-jpa-examples</artifactId>
	<packaging>jar</packaging>
	<name>Spring Data JPA Examples</name>
	<url>https://github.com/ttrelle/spring-data-examples/tree/master/springdata-jpa</url>

	<dependencies>

		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-jpa</artifactId>
			<version>1.9.4.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.2.21.Final</version>
		</dependency>
		<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
			<version>2.0</version>
		</dependency>

		<!-- <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> 
			<version>1.6.3</version> </dependency> -->

		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib-nodep</artifactId>
			<version>2.2</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.1.9.RELEASE</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hsqldb</groupId>
			<artifactId>hsqldb</artifactId>
			<version>1.8.0.10</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

</project>


================================================
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<User> 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<User, String> {

	List<User> findByFullName(String fullName);

	List<User> findByFullName(String fullName, Sort sort);

	List<User> findByFullName(String fullName, Pageable paging);
	
	List<User> findByUser5();

	List<User> findByOrm();
	
	@Transactional(timeout = 2, propagation = Propagation.REQUIRED)
	@Query("SELECT u FROM User u WHERE u.fullName = 'User 3'")
	List<User> findByGivenQuery();
	
	List<User> findByIdAndFullName(@Param("id") String id, @Param("fullName") String fullname);
	
}


================================================
FILE: springdata-jpa/src/main/resources/META-INF/orm.xml
================================================
<?xml version="1.0"?>
<entity-mappings 
	xmlns="http://java.sun.com/xml/ns/persistence/orm" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" 
	version="1.0">
	<entity class="jpa.domain.User">
		<named-query name="User.findByOrm">
			<query>
				SELECT u FROM User u WHERE u.fullName = 'User 2'
			</query>
		</named-query>
	</entity>
</entity-mappings>

================================================
FILE: springdata-jpa/src/main/resources/META-INF/persistence.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="pu1">
    	<class>jpa.domain.User</class>
    </persistence-unit>
</persistence>

================================================
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<User> users;

		 // when
		 users = classicRepo.findByFullName("User 1");
		 
		 // then
		 assertUserByFullName(users, "User 1");
	 }
	 
	 @Test public void shouldPageUsers() {
		 List<User> users;
		 
		 // when
		 Page<User> page = repo.findAll( new PageRequest(2, 2 ) );
		 users = page.getContent();
	 
		 // then
		 assertUserCount(users, 2);
	 }

	 @Test public void shouldFindByFullnameQuery() {
		 List<User> users;
		 
		 // when
		 users = repo.findByFullName("User 5");
		 
		 // then
		 assertUserByFullName(users, "User 5");
	 }

	 @Test public void shouldFindByFullnameQueryWithSort() {
		 List<User> 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<User> users;
		 
		 // when
		 users = repo.findByUser5();
		 
		 // then
		 assertUserByFullName(users, "User 5");
	 }
	 
	 @Test public void shouldUseXmlNamedQuery() {
		 List<User> users;
		 
		 // when
		 users = repo.findByOrm();
		 
		 // then
		 assertUserByFullName(users, "User 2");
	 }	 

	 @Test public void shouldUseSpringDataQuery() {
		 List<User> users;
		 
		 // when
		 users = repo.findByGivenQuery();
		 
		 // then
		 assertUserByFullName(users, "User 3");
	 }	 
	 
	 @Test public void shouldIgnoreNullQueryParameters() {
		 List<User> 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<User> 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<User> users, String fullName)  {
		 assertUserCount(users, 1);
		 assertThat( "Mismatch full name", users.get(0).getFullName(), is(fullName));
	 }

	 private static void assertUserCount(List<User> 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
================================================
<?xml version="1.0"?>
<beans
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns="http://www.springframework.org/schema/beans"
 	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee"	
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/jdbc 
        http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
        http://www.springframework.org/schema/data/jpa 
        http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/jee 
        http://www.springframework.org/schema/jee/spring-jee.xsd
        ">

	<jdbc:embedded-database id="dataSource" type="HSQL" />

	<!-- Scan for SD repos -->
	<jpa:repositories base-package="jpa.repo" query-lookup-strategy="create-if-not-found" />

 	<!-- EM factory -->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="generateDdl" value="true" />
            </bean>
        </property>
    </bean>
 
    <context:component-scan base-package="jpa.repo" />
    
    <context:annotation-config />

	<!--  TX Manager --> 
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" />
    <tx:annotation-driven />
	
</beans>

================================================
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
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>de.codecentric</groupId>
		<artifactId>springdata-examples</artifactId>
		<version>1.0.0</version>
	</parent>

	<artifactId>springdata-mongodb-examples</artifactId>
	<packaging>jar</packaging>
	<name>Spring Data MongoDB Examples</name>
	<url>https://github.com/ttrelle/spring-data-examples/tree/master/springdata-mongodb</url>

	<properties>
		<spring.data.mongodb.version>2.1.8.RELEASE</spring.data.mongodb.version>
		<mongo.driver.version>3.4.2</mongo.driver.version>
		<spring.version>4.2.9.RELEASE</spring.version>
	</properties>

	<dependencies>

		<!--  
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>${mongo.driver.version}</version>
		</dependency>
		-->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>${spring.data.mongodb.version}</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<resources>
			<resource>
				<directory>src/misc/java</directory>
				<targetPath>test-classes</targetPath>
			</resource>
			<resource>
				<directory>src/misc/resources</directory>
				<targetPath>test-classes</targetPath>
			</resource>
		</resources>
	</build>

	<repositories>
		<repository>
			<id>spring-snapshot</id>
			<name>Spring Maven SNAPSHOT Repository</name>
			<url>http://repo.springsource.org/libs-snapshot</url>
		</repository>
	</repositories>
</project>


================================================
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<Location, String> {

	List<Location> findByPositionWithin(Circle c);

	List<Location> findByPositionWithin(Box b);

	List<Location> 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<Item> 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<Item> getItems() {
		return items;
	}

	public void setItems(List<Item> 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 <code>PrePersist</code>.
 * <p/>
 * This handler shows how to implement your custom UUID generation.
 * @author Tobias Trelle
 */
public class OrderBeforeSaveListener extends AbstractMongoEventListener<Order>  {

	@Override
	public void onBeforeSave(BeforeSaveEvent<Order> 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<Order, String> {

	List<Order> findByItemsQuantity(int quantity);
	
	@Query("{ \"items.quantity\": ?0 }")
	List<Order> findWithQuery(int quantity);
	
	@Query( value = "{ custInfo: ?0 }", fields = "{_id:0, items:1}")
	List<Order> 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<User, String> {

	@Query("{ fullName: ?0 }")
	List<User> findByTheUsersFullName(String fullName);

	List<User> 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.
 * <p/>
 * 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 <a href="http://blog.codecentric.de/en/author/tobias-trelle">Tobias
 *         Trelle</a>
 */
@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<Location> locations = new ArrayList<Location>();
		
		 // 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<Location> 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
================================================
<?xml version="1.0"?>
<beans
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns="http://www.springframework.org/schema/beans"
 	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xmlns:tx="http://www.springframework.org/schema/tx"

	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/data/mongo
        http://www.springframework.org/schema/data/mongo/spring-mongo.xsd        
        ">

<!-- Connection to MongoDB server -->
<mongo:db-factory host="localhost" port="27017" dbname="test" />
<!-- MongoDB Template -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
  <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>

<!-- Package w/ automagic repositories -->
<mongo:repositories base-package="mongodb" />

	
</beans>

================================================
FILE: springdata-mongodb/src/misc/resources/MongoDBMassTest-context.xml
================================================
<?xml version="1.0"?>
<beans
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns="http://www.springframework.org/schema/beans"
 	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xmlns:tx="http://www.springframework.org/schema/tx"

	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/data/mongo
        http://www.springframework.org/schema/data/mongo/spring-mongo.xsd        
        ">

<!-- Connection to MongoDB server -->
<mongo:db-factory host="localhost" port="27017" dbname="perf" />
<!-- MongoDB Template -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
  <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>

<!-- Package w/ automagic repositories -->
<mongo:repositories base-package="mongodb" />

	
</beans>

================================================
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 <a href="http://blog.codecentric.de/en/author/tobias-trelle">Tobias
 *         Trelle</a>
 */
@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<Location> locations = repo.findByPositionNear(DUS , new Distance(1, Metrics.KILOMETERS) );

		// then
		assertLocations(locations, "Düsseldorf");
	}
	
	@Test public void shouldFindCologne() {
		// when
		List<Location> locations = repo.findByPositionNear(DUS , new Distance(70, Metrics.KILOMETERS) );

		// then
		assertLocations(locations, "Düsseldorf", "Cologne");
	}

	@Test public void shouldFindCologneAndBerlin() {
		// when
		List<Location> locations = repo.findByPositionNear(DUS , new Distance(350, Metrics.MILES) );

		// then
		assertLocations(locations, "Düsseldorf", "Cologne", "Berlin");
	}
	
	@Test public void shouldFindAll() {
		// when
		List<Location> locations = repo.findAll();

		// then
		assertLocations(locations, "A", "B", "C", "D", "Berlin", "Cologne", "Düsseldorf");
	}

	@Test public void shouldFindAroundOrigin() {
		// when
		List<Location> locations = repo.findByPositionWithin(new Circle(0, 0, 0.75));

		// then
		assertLocations(locations, "A", "C", "D");
	}

	@Test public void shouldFindWithinBox() {
		// when
		List<Location> 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<Location> 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<Item> items = new ArrayList<Item>();
		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<Order> 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<Item> items = new ArrayList<Item>();
		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<Order> 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<Item> items = new ArrayList<Item>();
		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<Order> 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<Item> items = new ArrayList<Item>();
		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<Order> result =  template.aggregate(agg, Order.class, Order.class);
		
		// then
		assertThat(result, notNullValue());
		List<Order> 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<Item> items = new ArrayList<Item>();
		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<Order> result =  template.aggregate(agg, Order.class, Order.class);
	
		// then
		assertThat(result, notNullValue());
		List<Order> 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.
 * <p/>
 * 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 <a href="http://blog.codecentric.de/en/author/tobias-trelle">Tobias Trelle</a>
 */
@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<User> users;
		 
		 // when
		 users = repo.findByTheUsersFullName("User 0");
		 
		 // then
		 assertUserByFullName(users, "User 0");
	 }
	 
	 
	 @Test public void shouldFindByFullNameLike() {
		 List<User> users;
		 
		 // when
		 users = repo.findByFullNameLike("User", null);
		 
		 // then
		 assertUserCount(users, 6);
	 }
	 
	 @Test public void shouldPageUsers() {
		 List<User> users;
		 
		 // when
		 Page<User> 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<User> users, String fullName)  {
		 assertUserCount(users, 1);
		 assertThat( "Mismatch full name", users.get(0).getFullName(), is(fullName));
	 }

	 private static void assertUserCount(List<User> 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
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>de.codecentric</groupId>
		<artifactId>springdata-examples</artifactId>
		<version>1.0.0</version>
	</parent>

	<artifactId>springdata-neo4j-examples</artifactId>
	<packaging>jar</packaging>
	<name>Spring Data Neo4j Examples</name>
	<url>http://maven.apache.org</url>

	<properties>
		<neo4j.version>2.2.5</neo4j.version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-neo4j</artifactId>
			<version>4.0.0.RELEASE</version>
		</dependency>

		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-neo4j</artifactId>
			<version>4.0.0.RELEASE</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.neo4j</groupId>
			<artifactId>neo4j-kernel</artifactId>
			<version>${neo4j.version}</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.neo4j.test</groupId>
			<artifactId>neo4j-harness</artifactId>
			<version>${neo4j.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.neo4j.app</groupId>
			<artifactId>neo4j-server</artifactId>
			<version>${neo4j.version}</version>
			<type>test-jar</type>			
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.neo4j</groupId>
			<artifactId>neo4j-ogm</artifactId>
			<version>1.1.2</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2.2</version>
		</dependency>

		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.1.0.Final</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.1.9.RELEASE</version>
			<scope>test</scope>
		</dependency>

	</dependencies>

</project>


================================================
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<User> friends;	
	
	public User() {}
	
	public User(String login, String fullName) {
		this.login = login;
		this.fullName = fullName;
		this.lastLogin = new Date();
		this.friends = new HashSet<User>();
	}	
	
	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<User> getFriends() {
		return friends;
	}

	public void setFriends(Set<User> 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> {
	
	User findByLogin(String login);
	
	@Query("START root=node:User(login = 'root') MATCH root-[:knows]->friends RETURN friends")
	List<User> 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<String, Object>() );
		
		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<User> users = repo.findFriendsOfRoot();

		// then
		assertNotNull("result is <null>", 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
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>de.codecentric</groupId>
		<artifactId>springdata-examples</artifactId>
		<version>1.0.0</version>
	</parent>

	<artifactId>springdata-redis-examples</artifactId>
	<packaging>jar</packaging>
	<name>Spring Data Redis Examples</name>
	<url>https://github.com/ttrelle/spring-data-examples/tree/master/springdata-redis</url>

	<dependencies>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.6.4.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>1.7.13</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.1.9.RELEASE</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.7.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-pool2</artifactId>
			<version>2.2</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.8.8</version>
			<scope>test</scope>
		</dependency>		
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.6.4</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.6.4</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

</project>


================================================
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<String, String> 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<String, User> 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 <null>", 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 <null>", user);
		assertEquals( "login mismatch" , "root", user.getLogin());
		assertEquals( "login mismatch" , "Superuser", user.getFullName());
	}
	
}


================================================
FILE: springdata-redis/src/test/resources/redis/StringStringRepositoryTest-context.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:redis="http://www.springframework.org/schema/redis"
  xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/redis http://www.springframework.org/schema/redis/spring-redis.xsd
        ">
    
<!-- Jedis Connection -->    
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
   p:host-name="localhost" p:port="6379" />
  
<!-- Redis Template -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
	<property name="connectionFactory" ref="jedisConnectionFactory" />
</bean>

<bean class="redis.StringStringRepository"/>

</beans>

================================================
FILE: springdata-redis/src/test/resources/redis/UserRepositoryTest-context.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:redis="http://www.springframework.org/schema/redis"
  xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/redis http://www.springframework.org/schema/redis/spring-redis.xsd
        ">
    
<!-- Jedis Connection -->    
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
   p:host-name="localhost" p:port="6379" />
  
<!-- Redis Template -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
	<property name="connectionFactory" ref="jedisConnectionFactory" />
	<property name="valueSerializer">
		<bean id="redisJsonSerializer" class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer">
			<constructor-arg type="java.lang.Class" value="redis.User"/>
		</bean>   
	</property>
</bean>

<bean class="redis.UserRepository"/>

</beans>
Download .txt
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
Download .txt
SYMBOL INDEX (249 symbols across 44 files)

FILE: mongodriver/src/main/java/de/codecentric/Connection.java
  class Connection (line 5) | abstract public class Connection {

FILE: mongodriver/src/main/java/de/codecentric/driverclient/OrderExample.java
  class OrderExample (line 22) | public class OrderExample {
    method main (line 31) | public static void main(String[] argv) throws UnknownHostException, Mo...
    method insert (line 44) | private static void insert(MongoCollection<Document> collection) {
    method find (line 69) | private static void find(MongoClient mongo) {
    method println (line 83) | private static final void println(Object o) {

FILE: mongodriver/src/main/java/de/codecentric/driverclient/ReplicaSetTimeout.java
  class ReplicaSetTimeout (line 21) | public class ReplicaSetTimeout {
    method main (line 31) | public static void main(String[] argv) {
    method execute (line 35) | public void execute() {
    method createBulk (line 71) | private List<WriteModel<Document>> createBulk() {

FILE: mongodriver/src/main/java/de/codecentric/driverclient/SimpleMongoClient.java
  class SimpleMongoClient (line 23) | public class SimpleMongoClient {
    method main (line 32) | public static void main(String[] argv) throws UnknownHostException, Mo...
    method remove (line 71) | private static void remove(MongoCollection<Document> collection) {
    method insert (line 84) | private static void insert(MongoCollection<Document> collection) {
    method find (line 93) | private static void find(MongoCollection<Document> collection) {
    method find (line 104) | private static void find(MongoCollection<Document> collection, Bson qu...
    method bsonize (line 119) | private static void bsonize() throws UnsupportedEncodingException {
    method bsonize (line 129) | private static void bsonize(DBObject doc) {
    method toString (line 135) | private static String toString(byte[] buff) {
    method println (line 153) | private static final void println(Object o) {

FILE: mongodriver/src/main/java/de/codecentric/notifications/DocumentProducer.java
  class DocumentProducer (line 10) | public class DocumentProducer  {
    method main (line 12) | public static void main(String[] args) throws Exception {

FILE: mongodriver/src/main/java/de/codecentric/notifications/EventListener.java
  class EventListener (line 17) | public class EventListener  {
    method main (line 19) | public static void main(String[] args) throws Exception {

FILE: mongodriver/src/main/java/de/codecentric/transaction/SimpleTransaction.java
  class SimpleTransaction (line 19) | public class SimpleTransaction {
    method main (line 30) | public static void main(String[] argv) throws UnknownHostException, Mo...
    method println (line 47) | private static final void println(Object o) {

FILE: spring-boot-mongo/src/main/java/de/codecentric/mongoboot/Item.java
  class Item (line 5) | public class Item {
    method getQuantity (line 14) | public int getQuantity() {
    method setQuantity (line 18) | public void setQuantity(int quantity) {
    method getPrice (line 22) | public double getPrice() {
    method setPrice (line 26) | public void setPrice(double price) {
    method getDescription (line 30) | public String getDescription() {
    method setDescription (line 34) | public void setDescription(String description) {

FILE: spring-boot-mongo/src/main/java/de/codecentric/mongoboot/Order.java
  class Order (line 9) | public class Order {
    method getId (line 21) | public String getId() {
    method setId (line 25) | public void setId(String id) {
    method getText (line 29) | public String getText() {
    method setText (line 33) | public void setText(String text) {
    method getOrdered (line 37) | public Date getOrdered() {
    method setOrdered (line 41) | public void setOrdered(Date ordered) {
    method getItems (line 45) | public List<Item> getItems() {
    method setItems (line 49) | public void setItems(List<Item> items) {

FILE: spring-boot-mongo/src/main/java/de/codecentric/mongoboot/OrderRepository.java
  type OrderRepository (line 9) | @RepositoryRestResource()
    method findByText (line 12) | List<Order> findByText(@Param("name") String name);

FILE: spring-boot-mongo/src/main/java/de/codecentric/mongoboot/SpringBootMongoApplication.java
  class SpringBootMongoApplication (line 6) | @SpringBootApplication
    method main (line 9) | public static void main(String[] args) {

FILE: spring-boot-mongo/src/test/java/de/codecentric/mongoboot/SpringBootMongoApplicationTests.java
  class SpringBootMongoApplicationTests (line 8) | @RunWith(SpringRunner.class)
    method contextLoads (line 12) | @Test

FILE: springdata-jpa/src/main/java/jpa/domain/User.java
  class User (line 10) | @Entity
    method User (line 23) | public User() {}
    method User (line 25) | public User(String id, String fullName) {
    method getId (line 32) | public String getId() {
    method setId (line 36) | public void setId(String id) {
    method getFullName (line 40) | public String getFullName() {
    method setFullName (line 44) | public void setFullName(String fullName) {
    method getLastLogin (line 48) | public Date getLastLogin() {
    method setLastLogin (line 52) | public void setLastLogin(Date lastLogin) {
    method hashCode (line 56) | @Override
    method equals (line 64) | @Override

FILE: springdata-jpa/src/main/java/jpa/repo/ClassicUserRepository.java
  class ClassicUserRepository (line 12) | @Repository
    method findByFullName (line 17) | public List<User> findByFullName(String fullName) {
    method getEntityManger (line 25) | private EntityManager getEntityManger() {

FILE: springdata-jpa/src/main/java/jpa/repo/UserRepository.java
  type UserRepository (line 15) | public interface UserRepository extends JpaRepository<User, String> {
    method findByFullName (line 17) | List<User> findByFullName(String fullName);
    method findByFullName (line 19) | List<User> findByFullName(String fullName, Sort sort);
    method findByFullName (line 21) | List<User> findByFullName(String fullName, Pageable paging);
    method findByUser5 (line 23) | List<User> findByUser5();
    method findByOrm (line 25) | List<User> findByOrm();
    method findByGivenQuery (line 27) | @Transactional(timeout = 2, propagation = Propagation.REQUIRED)
    method findByIdAndFullName (line 31) | List<User> findByIdAndFullName(@Param("id") String id, @Param("fullNam...

FILE: springdata-jpa/src/test/java/jpa/repo/JpaRepoTest.java
  class JpaRepoTest (line 26) | @RunWith(SpringJUnit4ClassRunner.class)
    method setUp (line 34) | @Before public void setUp() {
    method shouldUseClassicRepository (line 40) | @Test public void shouldUseClassicRepository() {
    method shouldPageUsers (line 50) | @Test public void shouldPageUsers() {
    method shouldFindByFullnameQuery (line 61) | @Test public void shouldFindByFullnameQuery() {
    method shouldFindByFullnameQueryWithSort (line 71) | @Test public void shouldFindByFullnameQueryWithSort() {
    method shouldUseExistingNamedQuery (line 81) | @Test public void shouldUseExistingNamedQuery() {
    method shouldUseXmlNamedQuery (line 91) | @Test public void shouldUseXmlNamedQuery() {
    method shouldUseSpringDataQuery (line 101) | @Test public void shouldUseSpringDataQuery() {
    method shouldIgnoreNullQueryParameters (line 111) | @Test public void shouldIgnoreNullQueryParameters() {
    method shouldSortByTwoCriteria (line 123) | @Test public void shouldSortByTwoCriteria() {
    method assertUserByFullName (line 137) | private static void assertUserByFullName(List<User> users, String full...
    method assertUserCount (line 142) | private static void assertUserCount(List<User> users, int expected) {

FILE: springdata-mongodb/src/main/java/mongodb/Adresse.java
  class Adresse (line 3) | public class Adresse {

FILE: springdata-mongodb/src/main/java/mongodb/PointOfInterest.java
  class PointOfInterest (line 8) | @Document(collection = "pois")
    method getTyp (line 19) | public String getTyp() {
    method setTyp (line 23) | public void setTyp(String typ) {
    method getTags (line 27) | public String getTags() {
    method setTags (line 31) | public void setTags(String tags) {
    method getDescription (line 35) | public String getDescription() {
    method setDescription (line 39) | public void setDescription(String description) {
    method getAdresse (line 43) | public Adresse getAdresse() {
    method setAdresse (line 47) | public void setAdresse(Adresse adresse) {
    method getLocation (line 51) | public Point getLocation() {
    method setLocation (line 55) | public void setLocation(Point location) {

FILE: springdata-mongodb/src/main/java/mongodb/geo/Location.java
  class Location (line 10) | public class Location {
    method Location (line 16) | public Location() {}
    method Location (line 18) | public Location(String id, double x, double y) {
    method getId (line 23) | public String getId() {
    method setId (line 27) | public void setId(String id) {
    method getPosition (line 31) | public GeoJsonPoint getPosition() {
    method setPosition (line 35) | public void setPosition(GeoJsonPoint pos) {
    method toString (line 39) | @Override
    method hashCode (line 44) | @Override
    method equals (line 52) | @Override

FILE: springdata-mongodb/src/main/java/mongodb/geo/LocationRepository.java
  type LocationRepository (line 16) | public interface LocationRepository extends MongoRepository<Location, St...
    method findByPositionWithin (line 18) | List<Location> findByPositionWithin(Circle c);
    method findByPositionWithin (line 20) | List<Location> findByPositionWithin(Box b);
    method findByPositionNear (line 22) | List<Location> findByPositionNear(Point p, Distance d);

FILE: springdata-mongodb/src/main/java/mongodb/order/Item.java
  class Item (line 5) | public class Item {
    method Item (line 13) | public Item() {
    method Item (line 16) | public Item(int quantity, double price, String description) {
    method getQuantity (line 23) | public int getQuantity() {
    method setQuantity (line 27) | public void setQuantity(int quantity) {
    method getPrice (line 31) | public double getPrice() {
    method setPrice (line 35) | public void setPrice(double price) {
    method getDescription (line 39) | public String getDescription() {
    method setDescription (line 43) | public void setDescription(String description) {

FILE: springdata-mongodb/src/main/java/mongodb/order/Order.java
  class Order (line 9) | public class Order {
    method Order (line 19) | public Order() {
    method Order (line 23) | public Order(String customerInfo) {
    method Order (line 28) | public Order(String id, String customerInfo) {
    method getId (line 34) | public String getId() {
    method setId (line 38) | public void setId(String id) {
    method getDate (line 42) | public Date getDate() {
    method setDate (line 46) | public void setDate(Date date) {
    method getCustomerInfo (line 50) | public String getCustomerInfo() {
    method setCustomerInfo (line 54) | public void setCustomerInfo(String customerInfo) {
    method getItems (line 58) | public List<Item> getItems() {
    method setItems (line 62) | public void setItems(List<Item> items) {

FILE: springdata-mongodb/src/main/java/mongodb/order/OrderBeforeSaveListener.java
  class OrderBeforeSaveListener (line 17) | public class OrderBeforeSaveListener extends AbstractMongoEventListener<...
    method onBeforeSave (line 19) | @Override

FILE: springdata-mongodb/src/main/java/mongodb/order/OrderRepository.java
  type OrderRepository (line 8) | public interface OrderRepository extends MongoRepository<Order, String> {
    method findByItemsQuantity (line 10) | List<Order> findByItemsQuantity(int quantity);
    method findWithQuery (line 12) | @Query("{ \"items.quantity\": ?0 }")
    method findOnlyItems (line 15) | @Query( value = "{ custInfo: ?0 }", fields = "{_id:0, items:1}")

FILE: springdata-mongodb/src/main/java/mongodb/user/User.java
  class User (line 9) | @Document
    method User (line 20) | public User() {}
    method User (line 22) | public User(String id, String fullName) {
    method getId (line 29) | public String getId() {
    method setId (line 33) | public void setId(String id) {
    method getFullName (line 37) | public String getFullName() {
    method setFullName (line 41) | public void setFullName(String fullName) {
    method getLastLogin (line 45) | public Date getLastLogin() {
    method setLastLogin (line 49) | public void setLastLogin(Date lastLogin) {
    method hashCode (line 53) | @Override
    method equals (line 61) | @Override

FILE: springdata-mongodb/src/main/java/mongodb/user/UserRepository.java
  type UserRepository (line 9) | public interface UserRepository extends MongoRepository<User, String> {
    method findByTheUsersFullName (line 11) | @Query("{ fullName: ?0 }")
    method findByFullNameLike (line 14) | List<User> findByFullNameLike(String fullName, Sort sort);

FILE: springdata-mongodb/src/misc/java/mongodb/CappedCollectionManipulationTest.java
  class CappedCollectionManipulationTest (line 22) | @RunWith(SpringJUnit4ClassRunner.class)
    method setUp (line 36) | @Before
    method does_not_delete_from_capped_collection (line 47) | @Test
    method does_not_update_capped_collection (line 61) | @Test

FILE: springdata-mongodb/src/misc/java/mongodb/MongoDBMassTest.java
  class MongoDBMassTest (line 26) | @RunWith(SpringJUnit4ClassRunner.class)
    method setUp (line 46) | @Before
    method shouldPerformRandomQueries (line 62) | @Test
    method tearDown (line 111) | @After
    method rnd (line 116) | private static double rnd() {
    method out (line 120) | private static void out(Object o) {

FILE: springdata-mongodb/src/test/java/mongodb/config/LocalhostMongoConfiguration.java
  class LocalhostMongoConfiguration (line 17) | @Configuration
    method beforeSaveListener (line 21) | @Bean
    method getDatabaseName (line 26) | @Override
    method mongoClient (line 31) | @Override

FILE: springdata-mongodb/src/test/java/mongodb/config/LocalhostMongoGridFSConfiguration.java
  class LocalhostMongoGridFSConfiguration (line 11) | @Configuration
    method gridTemplate (line 14) | @Bean

FILE: springdata-mongodb/src/test/java/mongodb/geo/LocationRepositoryTest.java
  class LocationRepositoryTest (line 33) | @RunWith(SpringJUnit4ClassRunner.class)
    method setUp (line 45) | @Before public void setUp() {
    method shouldFindSelf (line 61) | @Test public void shouldFindSelf() {
    method shouldFindCologne (line 69) | @Test public void shouldFindCologne() {
    method shouldFindCologneAndBerlin (line 77) | @Test public void shouldFindCologneAndBerlin() {
    method shouldFindAll (line 85) | @Test public void shouldFindAll() {
    method shouldFindAroundOrigin (line 93) | @Test public void shouldFindAroundOrigin() {
    method shouldFindWithinBox (line 101) | @Test public void shouldFindWithinBox() {
    method tearDown (line 110) | @After
    method assertLocations (line 115) | private static void assertLocations(List<Location> locations, String.....
    method out (line 128) | private static void out(Object o) {

FILE: springdata-mongodb/src/test/java/mongodb/order/OrderRepositoryTest.java
  class OrderRepositoryTest (line 28) | @RunWith(SpringJUnit4ClassRunner.class)
    method setUp (line 34) | @Before public void setUp() {
    method shouldFindByItemsQuantity (line 38) | @Test public void shouldFindByItemsQuantity() {
    method shouldFindByAnnotatedQuery (line 55) | @Test public void shouldFindByAnnotatedQuery() {
    method use_field_projection (line 72) | @Test public void use_field_projection() {

FILE: springdata-mongodb/src/test/java/mongodb/order/OrderSubListTest.java
  class OrderSubListTest (line 32) | @RunWith(SpringJUnit4ClassRunner.class)
    method setUp (line 40) | @Before public void setUp() {
    method projection_by_aggregation (line 44) | @Test public void projection_by_aggregation() {
    method projection_by_query (line 69) | @Test public void projection_by_query() {

FILE: springdata-mongodb/src/test/java/mongodb/user/IndexViolationTest.java
  class IndexViolationTest (line 24) | @RunWith(SpringJUnit4ClassRunner.class)
    method setUp (line 37) | @Before
    method does_not_detect_index_violation_on_id (line 44) | @Test

FILE: springdata-mongodb/src/test/java/mongodb/user/UserRepositoryTest.java
  class UserRepositoryTest (line 29) | @RunWith(SpringJUnit4ClassRunner.class)
    method setUp (line 37) | @Before public void setUp() {
    method shouldFindByCustomerQuery (line 48) | @Test public void shouldFindByCustomerQuery() {
    method shouldFindByFullNameLike (line 59) | @Test public void shouldFindByFullNameLike() {
    method shouldPageUsers (line 69) | @Test public void shouldPageUsers() {
    method tearDown (line 80) | @After public void tearDown() {
    method assertUserByFullName (line 84) | private static void assertUserByFullName(List<User> users, String full...
    method assertUserCount (line 89) | private static void assertUserCount(List<User> users, int expected) {

FILE: springdata-neo4j/src/main/java/neo4j/domain/User.java
  class User (line 13) | @NodeEntity public class User {
    method User (line 26) | public User() {}
    method User (line 28) | public User(String login, String fullName) {
    method knows (line 35) | public void knows(User user) {
    method getLogin (line 39) | public String getLogin() {
    method setLogin (line 43) | public void setLogin(String login) {
    method getFullName (line 47) | public String getFullName() {
    method setFullName (line 51) | public void setFullName(String fullName) {
    method getLastLogin (line 55) | public Date getLastLogin() {
    method setLastLogin (line 59) | public void setLastLogin(Date lastLogin) {
    method getId (line 63) | public long getId() {
    method setId (line 67) | public void setId(long id) {
    method getFriends (line 71) | public Set<User> getFriends() {
    method setFriends (line 75) | public void setFriends(Set<User> friends) {
    method setId (line 79) | public void setId(Long id) {

FILE: springdata-neo4j/src/main/java/neo4j/repo/UserRepository.java
  type UserRepository (line 11) | public interface UserRepository extends GraphRepository<User> {
    method findByLogin (line 13) | User findByLogin(String login);
    method findFriendsOfRoot (line 15) | @Query("START root=node:User(login = 'root') MATCH root-[:knows]->frie...

FILE: springdata-neo4j/src/test/java/neo4j/repo/Neo4jRepoTest.java
  class Neo4jRepoTest (line 23) | @RunWith(SpringJUnit4ClassRunner.class)
    method setUp (line 37) | @Before
    method shouldFindAll (line 67) | @Test
    method shouldFindRootUserById (line 76) | @Test
    method shouldFindRootUserByLogin (line 85) | @Test
    method shouldFindFriendsOfRoot (line 97) | @Test
    method tearDown (line 108) | @After
    method out (line 113) | private static void out(Object o) {

FILE: springdata-neo4j/src/test/java/neo4j/repo/Neo4jTestConfig.java
  class Neo4jTestConfig (line 12) | @Configuration
    method neo4jServer (line 16) | @Override
    method getSessionFactory (line 21) | @Override

FILE: springdata-redis/src/main/java/redis/StringStringRepository.java
  class StringStringRepository (line 10) | public class StringStringRepository {
    method add (line 15) | public void add(String key, String value) {
    method getValue (line 19) | public String getValue(String key) {
    method delete (line 23) | public void delete(String key) {

FILE: springdata-redis/src/main/java/redis/User.java
  class User (line 6) | public class User {
    method User (line 14) | public User() {}
    method User (line 16) | public User(String login, String fullName) {
    method getLogin (line 22) | public String getLogin() {
    method setLogin (line 26) | public void setLogin(String login) {
    method getFullName (line 30) | public String getFullName() {
    method setFullName (line 34) | public void setFullName(String fullName) {
    method getLastLogin (line 38) | public Date getLastLogin() {
    method setLastLogin (line 42) | public void setLastLogin(Date lastLogin) {

FILE: springdata-redis/src/main/java/redis/UserRepository.java
  class UserRepository (line 10) | public class UserRepository {
    method add (line 15) | public void add(User user) {
    method get (line 19) | public User get(String key) {

FILE: springdata-redis/src/test/java/redis/StringStringRepositoryTest.java
  class StringStringRepositoryTest (line 13) | @RunWith(SpringJUnit4ClassRunner.class)
    method setUp (line 19) | @Before
    method shouldFindValue (line 24) | @Test

FILE: springdata-redis/src/test/java/redis/UserRepositoryTest.java
  class UserRepositoryTest (line 13) | @RunWith(SpringJUnit4ClassRunner.class)
    method setUp (line 19) | @Before
    method shouldFindValue (line 24) | @Test
Condensed preview — 83 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (117K chars).
[
  {
    "path": ".gitignore",
    "chars": 38,
    "preview": "/target\n/.settings\n.classpath\n.project"
  },
  {
    "path": ".travis.yml",
    "chars": 163,
    "preview": "language: java\njdk:\n  - openjdk11\nservices:  \n  - mongodb\n  - redis\naddons:\n  apt:\n    sources:\n    - mongodb-3.4-precis"
  },
  {
    "path": "README.md",
    "chars": 1377,
    "preview": "# Spring Data Blog Series\r\n\r\nThis projects holds the Java source examples for my blog post series on the Spring Data pro"
  },
  {
    "path": "mongodriver/.gitignore",
    "chars": 21,
    "preview": "/.settings/\n/target/\n"
  },
  {
    "path": "mongodriver/pom.xml",
    "chars": 857,
    "preview": "<?xml version=\"1.0\"?>\n<project\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-"
  },
  {
    "path": "mongodriver/src/main/java/de/codecentric/Connection.java",
    "chars": 333,
    "preview": "package de.codecentric;\n\nimport com.mongodb.MongoClientURI;\n\nabstract public class Connection {\n\n\tpublic static final Mo"
  },
  {
    "path": "mongodriver/src/main/java/de/codecentric/driverclient/OrderExample.java",
    "chars": 2167,
    "preview": "package de.codecentric.driverclient;\n\nimport java.io.UnsupportedEncodingException;\nimport java.net.UnknownHostException;"
  },
  {
    "path": "mongodriver/src/main/java/de/codecentric/driverclient/ReplicaSetTimeout.java",
    "chars": 2207,
    "preview": "package de.codecentric.driverclient;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Date;\nimport"
  },
  {
    "path": "mongodriver/src/main/java/de/codecentric/driverclient/SimpleMongoClient.java",
    "chars": 3603,
    "preview": "package de.codecentric.driverclient;\n\nimport java.io.UnsupportedEncodingException;\nimport java.net.UnknownHostException;"
  },
  {
    "path": "mongodriver/src/main/java/de/codecentric/notifications/DocumentProducer.java",
    "chars": 760,
    "preview": "package de.codecentric.notifications;\n\nimport org.bson.Document;\n\nimport com.mongodb.MongoClient;\nimport com.mongodb.cli"
  },
  {
    "path": "mongodriver/src/main/java/de/codecentric/notifications/EventListener.java",
    "chars": 1101,
    "preview": "package de.codecentric.notifications;\n\nimport static com.mongodb.client.model.Filters.and;\nimport static com.mongodb.cli"
  },
  {
    "path": "mongodriver/src/main/java/de/codecentric/transaction/SimpleTransaction.java",
    "chars": 1435,
    "preview": "package de.codecentric.transaction;\n\nimport java.io.UnsupportedEncodingException;\nimport java.net.UnknownHostException;\n"
  },
  {
    "path": "pom.xml",
    "chars": 1390,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLoca"
  },
  {
    "path": "spring-boot-mongo/.gitignore",
    "chars": 257,
    "preview": "target/\n!.mvn/wrapper/maven-wrapper.jar\n\n### STS ###\n.apt_generated\n.classpath\n.factorypath\n.project\n.settings\n.springBe"
  },
  {
    "path": "spring-boot-mongo/docker-compose.yml",
    "chars": 440,
    "preview": "version: '3'\n\nnetworks:\n  servicenet:\n    driver: bridge\n    \nservices:\n\n  boot-rest-mongo:\n    image: mongoboot/spring-"
  },
  {
    "path": "spring-boot-mongo/mvnw",
    "chars": 7058,
    "preview": "#!/bin/sh\n# ----------------------------------------------------------------------------\n# Licensed to the Apache Softwa"
  },
  {
    "path": "spring-boot-mongo/mvnw.cmd",
    "chars": 5006,
    "preview": "@REM ----------------------------------------------------------------------------\n@REM Licensed to the Apache Software F"
  },
  {
    "path": "spring-boot-mongo/pom.xml",
    "chars": 3123,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2"
  },
  {
    "path": "spring-boot-mongo/src/main/docker/Dockerfile",
    "chars": 236,
    "preview": "FROM java:8\nVOLUME /tmp\nADD spring-boot-mongo*.jar mongorest.jar\nRUN sh -c 'touch /mongorest.jar'\nENV JAVA_OPTS=\"-Xmx256"
  },
  {
    "path": "spring-boot-mongo/src/main/java/de/codecentric/mongoboot/Item.java",
    "chars": 580,
    "preview": "package de.codecentric.mongoboot;\n\nimport org.springframework.data.mongodb.core.mapping.Field;\n\npublic class Item {\n\n\tin"
  },
  {
    "path": "spring-boot-mongo/src/main/java/de/codecentric/mongoboot/Order.java",
    "chars": 762,
    "preview": "package de.codecentric.mongoboot;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.springframework.data.annota"
  },
  {
    "path": "spring-boot-mongo/src/main/java/de/codecentric/mongoboot/OrderRepository.java",
    "chars": 419,
    "preview": "package de.codecentric.mongoboot;\n\nimport java.util.List;\n\nimport org.springframework.data.mongodb.repository.MongoRepos"
  },
  {
    "path": "spring-boot-mongo/src/main/java/de/codecentric/mongoboot/SpringBootMongoApplication.java",
    "chars": 334,
    "preview": "package de.codecentric.mongoboot;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.au"
  },
  {
    "path": "spring-boot-mongo/src/main/resources/application.properties",
    "chars": 66,
    "preview": "spring.data.rest.base-path=/rest\nmanagement.security.enabled=false"
  },
  {
    "path": "spring-boot-mongo/src/test/java/de/codecentric/mongoboot/SpringBootMongoApplicationTests.java",
    "chars": 350,
    "preview": "package de.codecentric.mongoboot;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.bo"
  },
  {
    "path": "springdata-jpa/.gitignore",
    "chars": 43,
    "preview": "/target\n\r\n/.settings\n\r\n.classpath\r\n.project"
  },
  {
    "path": "springdata-jpa/README.md",
    "chars": 1202,
    "preview": "# Spring Data Blog Series\r\n\r\nThis projects holds the Java source examples for my blog post series on the Spring Data pro"
  },
  {
    "path": "springdata-jpa/pom.xml",
    "chars": 1807,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLoca"
  },
  {
    "path": "springdata-jpa/src/main/java/jpa/domain/User.java",
    "chars": 1520,
    "preview": "package jpa.domain;\n\nimport java.util.Date;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax."
  },
  {
    "path": "springdata-jpa/src/main/java/jpa/repo/ClassicUserRepository.java",
    "chars": 574,
    "preview": "package jpa.repo;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.PersistenceC"
  },
  {
    "path": "springdata-jpa/src/main/java/jpa/repo/UserRepository.java",
    "chars": 1045,
    "preview": "package jpa.repo;\r\n\r\nimport java.util.List;\r\n\r\nimport jpa.domain.User;\r\n\r\nimport org.springframework.data.domain.Pageabl"
  },
  {
    "path": "springdata-jpa/src/main/resources/META-INF/orm.xml",
    "chars": 489,
    "preview": "<?xml version=\"1.0\"?>\r\n<entity-mappings \r\n\txmlns=\"http://java.sun.com/xml/ns/persistence/orm\" \r\n\txmlns:xsi=\"http://www.w"
  },
  {
    "path": "springdata-jpa/src/main/resources/META-INF/persistence.xml",
    "chars": 400,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<persistence version=\"2.0\" xmlns=\"http://java.sun.com/xml/ns/persistence\" xmlns:"
  },
  {
    "path": "springdata-jpa/src/test/java/jpa/repo/JpaRepoTest.java",
    "chars": 3577,
    "preview": "package jpa.repo;\r\n\r\nimport static org.hamcrest.CoreMatchers.is;\r\nimport static org.hamcrest.CoreMatchers.notNullValue;\r"
  },
  {
    "path": "springdata-jpa/src/test/resources/jpa/repo/JpaRepoTest-context.xml",
    "chars": 2034,
    "preview": "<?xml version=\"1.0\"?>\n<beans\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n\txmlns=\"http://www.springframework."
  },
  {
    "path": "springdata-mongodb/.gitignore",
    "chars": 82,
    "preview": "/target\n/.settings\n.classpath\n.project\n/maven-eclipse.xml\n/.externalToolBuilders/\n"
  },
  {
    "path": "springdata-mongodb/README.md",
    "chars": 1202,
    "preview": "# Spring Data Blog Series\r\n\r\nThis projects holds the Java source examples for my blog post series on the Spring Data pro"
  },
  {
    "path": "springdata-mongodb/pom.xml",
    "chars": 2004,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLoca"
  },
  {
    "path": "springdata-mongodb/rs-dev0.yml",
    "chars": 1192,
    "preview": "version: '3.4'\n\nservices:\n\n  # Primary\n  mongo1:\n    image: 'bitnami/mongodb:4.0.9'\n    container_name: 'rs-dev0-1'\n    "
  },
  {
    "path": "springdata-mongodb/single-node.yml",
    "chars": 206,
    "preview": "version: \"2\"\n\nservices:\n  mongodb:\n      image: mongo:4.0.9\n      container_name: \"mongodb\"\n      volumes:\n        - ./d"
  },
  {
    "path": "springdata-mongodb/src/main/bat/masterslave.bat",
    "chars": 217,
    "preview": "start mongod --rest --port 8000 --dbpath /var/master --replSet cluster0\r\nstart mongod --rest --port 8001 --dbpath /var/s"
  },
  {
    "path": "springdata-mongodb/src/main/bat/shard.bat",
    "chars": 267,
    "preview": "start mongod --shardsvr --rest --port 9000 --dbpath /var/shard1\r\nstart mongod --shardsvr --rest --port 9001 --dbpath /va"
  },
  {
    "path": "springdata-mongodb/src/main/java/mongodb/Adresse.java",
    "chars": 44,
    "preview": "package mongodb;\n\npublic class Adresse {\n\n}\n"
  },
  {
    "path": "springdata-mongodb/src/main/java/mongodb/PointOfInterest.java",
    "chars": 1081,
    "preview": "package mongodb;\n\nimport org.springframework.data.geo.Point;\nimport org.springframework.data.mongodb.core.index.Indexed;"
  },
  {
    "path": "springdata-mongodb/src/main/java/mongodb/geo/Location.java",
    "chars": 1354,
    "preview": "package mongodb.geo;\r\n\r\nimport org.springframework.data.annotation.Id;\r\nimport org.springframework.data.mongodb.core.geo"
  },
  {
    "path": "springdata-mongodb/src/main/java/mongodb/geo/LocationRepository.java",
    "chars": 608,
    "preview": "package mongodb.geo;\n\nimport java.util.List;\n\nimport org.springframework.data.geo.Box;\nimport org.springframework.data.g"
  },
  {
    "path": "springdata-mongodb/src/main/java/mongodb/order/Item.java",
    "chars": 834,
    "preview": "package mongodb.order;\r\n\r\nimport org.springframework.data.mongodb.core.mapping.Field;\r\n\r\npublic class Item {\r\n\r\n\t privat"
  },
  {
    "path": "springdata-mongodb/src/main/java/mongodb/order/Order.java",
    "chars": 1083,
    "preview": "package mongodb.order;\r\n\r\nimport java.util.Date;\r\nimport java.util.List;\r\n\r\nimport org.springframework.data.annotation.I"
  },
  {
    "path": "springdata-mongodb/src/main/java/mongodb/order/OrderBeforeSaveListener.java",
    "chars": 901,
    "preview": "package mongodb.order;\r\n\r\nimport java.util.Date;\r\n\r\nimport org.bson.Document;\r\nimport org.springframework.data.mongodb.c"
  },
  {
    "path": "springdata-mongodb/src/main/java/mongodb/order/OrderRepository.java",
    "chars": 508,
    "preview": "package mongodb.order;\r\n\r\nimport java.util.List;\r\n\r\nimport org.springframework.data.mongodb.repository.MongoRepository;\r"
  },
  {
    "path": "springdata-mongodb/src/main/java/mongodb/user/User.java",
    "chars": 1438,
    "preview": "package mongodb.user;\r\n\r\nimport java.util.Date;\r\n\r\nimport org.springframework.data.annotation.Id;\r\nimport org.springfram"
  },
  {
    "path": "springdata-mongodb/src/main/java/mongodb/user/UserRepository.java",
    "chars": 451,
    "preview": "package mongodb.user;\r\n\r\nimport java.util.List;\r\n\r\nimport org.springframework.data.domain.Sort;\r\nimport org.springframew"
  },
  {
    "path": "springdata-mongodb/src/misc/java/mongodb/CappedCollectionManipulationTest.java",
    "chars": 2068,
    "preview": "package mongodb;\n\nimport static org.hamcrest.core.Is.*;\nimport static org.junit.Assert.*;\n\nimport org.junit.Before;\nimpo"
  },
  {
    "path": "springdata-mongodb/src/misc/java/mongodb/MongoDBMassTest.java",
    "chars": 3503,
    "preview": "package mongodb;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n\nimport org.junit.After;\nimport org.junit.Before;\n"
  },
  {
    "path": "springdata-mongodb/src/misc/resources/CappedCollectionManipulationTest-context.xml",
    "chars": 991,
    "preview": "<?xml version=\"1.0\"?>\n<beans\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n\txmlns=\"http://www.springframework."
  },
  {
    "path": "springdata-mongodb/src/misc/resources/MongoDBMassTest-context.xml",
    "chars": 991,
    "preview": "<?xml version=\"1.0\"?>\n<beans\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n\txmlns=\"http://www.springframework."
  },
  {
    "path": "springdata-mongodb/src/test/java/mongodb/config/LocalhostMongoConfiguration.java",
    "chars": 918,
    "preview": "package mongodb.config;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotati"
  },
  {
    "path": "springdata-mongodb/src/test/java/mongodb/config/LocalhostMongoGridFSConfiguration.java",
    "chars": 537,
    "preview": "package mongodb.config;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotati"
  },
  {
    "path": "springdata-mongodb/src/test/java/mongodb/geo/LocationRepositoryTest.java",
    "chars": 3821,
    "preview": "package mongodb.geo;\n\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.CoreMatchers.notNullValue;\n"
  },
  {
    "path": "springdata-mongodb/src/test/java/mongodb/order/OrderRepositoryTest.java",
    "chars": 2839,
    "preview": "package mongodb.order;\n\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.CoreMatchers.notNullValue"
  },
  {
    "path": "springdata-mongodb/src/test/java/mongodb/order/OrderSubListTest.java",
    "chars": 2901,
    "preview": "package mongodb.order;\n\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.CoreMatchers.notNullValue"
  },
  {
    "path": "springdata-mongodb/src/test/java/mongodb/user/IndexViolationTest.java",
    "chars": 1583,
    "preview": "package mongodb.user;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.sprin"
  },
  {
    "path": "springdata-mongodb/src/test/java/mongodb/user/UserRepositoryTest.java",
    "chars": 2448,
    "preview": "package mongodb.user;\n\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.CoreMatchers.notNullValue;"
  },
  {
    "path": "springdata-mongodb/src/test/resources/dummy.txt",
    "chars": 37,
    "preview": "A file to be uploaded via GridFS ...."
  },
  {
    "path": "springdata-neo4j/.gitignore",
    "chars": 43,
    "preview": "/target\n\r\n/.settings\n\r\n.classpath\r\n.project"
  },
  {
    "path": "springdata-neo4j/README.md",
    "chars": 1202,
    "preview": "# Spring Data Blog Series\r\n\r\nThis projects holds the Java source examples for my blog post series on the Spring Data pro"
  },
  {
    "path": "springdata-neo4j/pom.xml",
    "chars": 2369,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLoca"
  },
  {
    "path": "springdata-neo4j/src/main/java/neo4j/domain/User.java",
    "chars": 1387,
    "preview": "package neo4j.domain;\n\nimport java.util.Date;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport org.neo4j.ogm.anno"
  },
  {
    "path": "springdata-neo4j/src/main/java/neo4j/repo/UserRepository.java",
    "chars": 450,
    "preview": "package neo4j.repo;\n\nimport java.util.List;\n\nimport neo4j.domain.User;\n\nimport org.springframework.data.neo4j.annotation"
  },
  {
    "path": "springdata-neo4j/src/test/java/neo4j/repo/Neo4jRepoTest.java",
    "chars": 2631,
    "preview": "package neo4j.repo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\n\nimport "
  },
  {
    "path": "springdata-neo4j/src/test/java/neo4j/repo/Neo4jTestConfig.java",
    "chars": 811,
    "preview": "package neo4j.repo;\n\nimport org.neo4j.ogm.session.SessionFactory;\nimport org.springframework.context.annotation.Bean;\nim"
  },
  {
    "path": "springdata-redis/.gitignore",
    "chars": 43,
    "preview": "/target\n\r\n/.settings\n\r\n.classpath\r\n.project"
  },
  {
    "path": "springdata-redis/README.md",
    "chars": 1202,
    "preview": "# Spring Data Blog Series\r\n\r\nThis projects holds the Java source examples for my blog post series on the Spring Data pro"
  },
  {
    "path": "springdata-redis/pom.xml",
    "chars": 2083,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLoca"
  },
  {
    "path": "springdata-redis/src/main/java/redis/StringStringRepository.java",
    "chars": 643,
    "preview": "package redis;\r\n\r\nimport org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.data.redis."
  },
  {
    "path": "springdata-redis/src/main/java/redis/User.java",
    "chars": 743,
    "preview": "package redis;\r\n\r\nimport java.util.Date;\r\n\r\n/** Simple user class. */\r\npublic class User {\r\n\t\r\n\tprivate String login;\r\n\t"
  },
  {
    "path": "springdata-redis/src/main/java/redis/UserRepository.java",
    "chars": 510,
    "preview": "package redis;\r\n\r\nimport org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.data.redis."
  },
  {
    "path": "springdata-redis/src/test/java/redis/StringStringRepositoryTest.java",
    "chars": 780,
    "preview": "package redis;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\n\nimport org.j"
  },
  {
    "path": "springdata-redis/src/test/java/redis/UserRepositoryTest.java",
    "chars": 855,
    "preview": "package redis;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\n\nimport org.j"
  },
  {
    "path": "springdata-redis/src/test/resources/redis/StringStringRepositoryTest-context.xml",
    "chars": 981,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\r\n  xmlns:xsi=\"http://"
  },
  {
    "path": "springdata-redis/src/test/resources/redis/UserRepositoryTest-context.xml",
    "chars": 1214,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\r\n  xmlns:xsi=\"http://"
  }
]

// ... and 2 more files (download for full content)

About this extraction

This page contains the full source code of the ttrelle/spring-data-examples GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 83 files (98.5 KB), approximately 29.6k tokens, and a symbol index with 249 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!