[BAEL-3348] Moved code to algorithm-4

This commit is contained in:
dupirefr
2019-11-01 00:35:30 +01:00
parent db85c8f275
commit fee1da6091
20514 changed files with 1642355 additions and 0 deletions
@@ -0,0 +1,5 @@
.classpath
.project
.settings
target
build
@@ -0,0 +1,11 @@
## MongoDB
This module contains articles about MongoDB in Java.
### Relevant articles:
- [A Guide to MongoDB with Java](http://www.baeldung.com/java-mongodb)
- [A Simple Tagging Implementation with MongoDB](http://www.baeldung.com/mongodb-tagging)
- [MongoDB BSON Guide](https://www.baeldung.com/mongodb-bson)
- [Geospatial Support in MongoDB](https://www.baeldung.com/mongodb-geospatial-support)
- [Introduction to Morphia Java ODM for MongoDB](https://www.baeldung.com/mongodb-morphia)
+49
View File
@@ -0,0 +1,49 @@
<?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>
<groupId>com.baeldung</groupId>
<artifactId>java-mongodb</artifactId>
<version>1.0-SNAPSHOT</version>
<name>java-mongodb</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>de.flapdoodle.embedmongo</groupId>
<artifactId>de.flapdoodle.embedmongo</artifactId>
<version>${flapdoodle.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>${mongo.version}</version>
</dependency>
<dependency>
<groupId>dev.morphia.morphia</groupId>
<artifactId>core</artifactId>
<version>${morphia.version}</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<mongo.version>3.10.1</mongo.version>
<flapdoodle.version>1.11</flapdoodle.version>
<morphia.version>1.5.3</morphia.version>
</properties>
</project>
@@ -0,0 +1,79 @@
package com.baeldung;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MongoBsonExample
{
public static void main(String[] args)
{
//
// 4.1 Connect to cluster (default is localhost:27017)
//
MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("myDB");
MongoCollection<Document> collection = database.getCollection("employees");
//
// 4.2 Insert new document
//
Document employee = new Document()
.append("first_name", "Joe")
.append("last_name", "Smith")
.append("title", "Java Developer")
.append("years_of_service", 3)
.append("skills", Arrays.asList("java", "spring", "mongodb"))
.append("manager", new Document()
.append("first_name", "Sally")
.append("last_name", "Johanson"));
collection.insertOne(employee);
//
// 4.3 Find documents
//
Document query = new Document("last_name", "Smith");
List results = new ArrayList<>();
collection.find(query).into(results);
query =
new Document("$or", Arrays.asList(
new Document("last_name", "Smith"),
new Document("first_name", "Joe")));
results = new ArrayList<>();
collection.find(query).into(results);
//
// 4.4 Update document
//
query = new Document(
"skills",
new Document(
"$elemMatch",
new Document("$eq", "spring")));
Document update = new Document(
"$push",
new Document("skills", "security"));
collection.updateMany(query, update);
//
// 4.5 Delete documents
//
query = new Document(
"years_of_service",
new Document("$lt", 0));
collection.deleteMany(query);
}
}
@@ -0,0 +1,53 @@
package com.baeldung;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
public class MongoExample {
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB database = mongoClient.getDB("myMongoDb");
// print existing databases
mongoClient.getDatabaseNames().forEach(System.out::println);
database.createCollection("customers", null);
// print all collections in customers database
database.getCollectionNames().forEach(System.out::println);
// create data
DBCollection collection = database.getCollection("customers");
BasicDBObject document = new BasicDBObject();
document.put("name", "Shubham");
document.put("company", "Baeldung");
collection.insert(document);
// update data
BasicDBObject query = new BasicDBObject();
query.put("name", "Shubham");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "John");
BasicDBObject updateObject = new BasicDBObject();
updateObject.put("$set", newDocument);
collection.update(query, updateObject);
// read data
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "John");
DBCursor cursor = collection.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
// delete data
BasicDBObject deleteQuery = new BasicDBObject();
deleteQuery.put("name", "John");
collection.remove(deleteQuery);
}
}
@@ -0,0 +1,31 @@
package com.baeldung.morphia.domain;
import java.util.List;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id;
@Entity
public class Author {
@Id
private String name;
private List<String> books;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getBooks() {
return books;
}
public void setBooks(List<String> books) {
this.books = books;
}
}
@@ -0,0 +1,116 @@
package com.baeldung.morphia.domain;
import java.util.HashSet;
import java.util.Set;
import dev.morphia.annotations.Embedded;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Field;
import dev.morphia.annotations.Id;
import dev.morphia.annotations.Index;
import dev.morphia.annotations.IndexOptions;
import dev.morphia.annotations.Indexes;
import dev.morphia.annotations.Property;
import dev.morphia.annotations.Reference;
import dev.morphia.annotations.Validation;
@Entity("Books")
@Indexes({ @Index(fields = @Field("title"), options = @IndexOptions(name = "book_title")) })
@Validation("{ price : { $gt : 0 } }")
public class Book {
@Id
private String isbn;
@Property
private String title;
private String author;
@Embedded
private Publisher publisher;
@Property("price")
private double cost;
@Reference
private Set<Book> companionBooks;
public Book() {
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public double getCost() {
return cost;
}
public void addCompanionBooks(Book book) {
if (companionBooks != null)
this.companionBooks.add(book);
}
public Book(String isbn, String title, String author, double cost, Publisher publisher) {
this.isbn = isbn;
this.title = title;
this.author = author;
this.cost = cost;
this.publisher = publisher;
this.companionBooks = new HashSet<>();
}
@Override
public String toString() {
return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
long temp;
temp = Double.doubleToLongBits(cost);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((isbn == null) ? 0 : isbn.hashCode());
result = prime * result + ((publisher == null) ? 0 : publisher.hashCode());
result = prime * result + ((title == null) ? 0 : title.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;
Book other = (Book) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (Double.doubleToLongBits(cost) != Double.doubleToLongBits(other.cost))
return false;
if (isbn == null) {
if (other.isbn != null)
return false;
} else if (!isbn.equals(other.isbn))
return false;
if (publisher == null) {
if (other.publisher != null)
return false;
} else if (!publisher.equals(other.publisher))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
}
@@ -0,0 +1,70 @@
package com.baeldung.morphia.domain;
import org.bson.types.ObjectId;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id;
@Entity
public class Publisher {
@Id
private ObjectId id;
private String name;
public Publisher() {
}
public Publisher(ObjectId id, String name) {
this.id = id;
this.name = name;
}
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Catalog [id=" + id + ", name=" + name + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.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;
Publisher other = (Publisher) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
@@ -0,0 +1,142 @@
package com.baeldung.tagging;
import java.util.List;
/**
* Model for a blog post.
*
* @author Donato Rimenti
*
*/
public class Post {
/**
* Title of the post. Must be unique.
*/
private String title;
/**
* Author of the post.
*/
private String author;
/**
* Tags of the post.
*/
private List<String> tags;
/**
* Gets the {@link #title}.
*
* @return the {@link #title}
*/
public String getTitle() {
return title;
}
/**
* Sets the {@link #title}.
*
* @param title
* the new {@link #title}
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Gets the {@link #author}.
*
* @return the {@link #author}
*/
public String getAuthor() {
return author;
}
/**
* Sets the {@link #author}.
*
* @param author
* the new {@link #author}
*/
public void setAuthor(String author) {
this.author = author;
}
/**
* Gets the {@link #tags}.
*
* @return the {@link #tags}
*/
public List<String> getTags() {
return tags;
}
/**
* Sets the {@link #tags}.
*
* @param tags
* the new {@link #tags}
*/
public void setTags(List<String> tags) {
this.tags = tags;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
result = prime * result + ((tags == null) ? 0 : tags.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Post other = (Post) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (tags == null) {
if (other.tags != null)
return false;
} else if (!tags.equals(other.tags))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Post [title=" + title + ", author=" + author + ", tags=" + tags + "]";
}
}
@@ -0,0 +1,153 @@
package com.baeldung.tagging;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;
/**
* Repository used to manage tags for a blog post.
*
* @author Donato Rimenti
*
*/
public class TagRepository implements Closeable {
/**
* Document field which holds the blog tags.
*/
private static final String TAGS_FIELD = "tags";
/**
* The post collection.
*/
private MongoCollection<Document> collection;
/**
* The MongoDB client, stored in a field in order to close it later.
*/
private MongoClient mongoClient;
/**
* Instantiates a new TagRepository by opening the DB connection.
*/
public TagRepository() {
mongoClient = new MongoClient("localhost", 27018);
MongoDatabase database = mongoClient.getDatabase("blog");
collection = database.getCollection("posts");
}
/**
* Returns a list of posts which contains one or more of the tags passed as
* argument.
*
* @param tags
* a list of tags
* @return a list of posts which contains at least one of the tags passed as
* argument
*/
public List<Post> postsWithAtLeastOneTag(String... tags) {
FindIterable<Document> results = collection.find(Filters.in(TAGS_FIELD, tags));
return StreamSupport.stream(results.spliterator(), false).map(TagRepository::documentToPost)
.collect(Collectors.toList());
}
/**
* Returns a list of posts which contains all the tags passed as argument.
*
* @param tags
* a list of tags
* @return a list of posts which contains all the tags passed as argument
*/
public List<Post> postsWithAllTags(String... tags) {
FindIterable<Document> results = collection.find(Filters.all(TAGS_FIELD, tags));
return StreamSupport.stream(results.spliterator(), false).map(TagRepository::documentToPost)
.collect(Collectors.toList());
}
/**
* Returns a list of posts which contains none of the tags passed as
* argument.
*
* @param tags
* a list of tags
* @return a list of posts which contains none of the tags passed as
* argument
*/
public List<Post> postsWithoutTags(String... tags) {
FindIterable<Document> results = collection.find(Filters.nin(TAGS_FIELD, tags));
return StreamSupport.stream(results.spliterator(), false).map(TagRepository::documentToPost)
.collect(Collectors.toList());
}
/**
* Adds a list of tags to the blog post with the given title.
*
* @param title
* the title of the blog post
* @param tags
* a list of tags to add
* @return the outcome of the operation
*/
public boolean addTags(String title, List<String> tags) {
UpdateResult result = collection.updateOne(new BasicDBObject(DBCollection.ID_FIELD_NAME, title),
Updates.addEachToSet(TAGS_FIELD, tags));
return result.getModifiedCount() == 1;
}
/**
* Removes a list of tags to the blog post with the given title.
*
* @param title
* the title of the blog post
* @param tags
* a list of tags to remove
* @return the outcome of the operation
*/
public boolean removeTags(String title, List<String> tags) {
UpdateResult result = collection.updateOne(new BasicDBObject(DBCollection.ID_FIELD_NAME, title),
Updates.pullAll(TAGS_FIELD, tags));
return result.getModifiedCount() == 1;
}
/**
* Utility method used to map a MongoDB document into a {@link Post}.
*
* @param document
* the document to map
* @return a {@link Post} object equivalent to the document passed as
* argument
*/
@SuppressWarnings("unchecked")
private static Post documentToPost(Document document) {
Post post = new Post();
post.setTitle(document.getString(DBCollection.ID_FIELD_NAME));
post.setAuthor(document.getString("author"));
post.setTags((List<String>) document.get(TAGS_FIELD));
return post;
}
/*
* (non-Javadoc)
*
* @see java.io.Closeable#close()
*/
@Override
public void close() throws IOException {
mongoClient.close();
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,72 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import de.flapdoodle.embedmongo.MongoDBRuntime;
import de.flapdoodle.embedmongo.MongodExecutable;
import de.flapdoodle.embedmongo.MongodProcess;
import de.flapdoodle.embedmongo.config.MongodConfig;
import de.flapdoodle.embedmongo.distribution.Version;
import de.flapdoodle.embedmongo.runtime.Network;
public class AppLiveTest {
private static final String DB_NAME = "myMongoDb";
private MongodExecutable mongodExe;
private MongodProcess mongod;
private Mongo mongo;
private DB db;
private DBCollection collection;
@Before
public void setup() throws Exception {
// Creating Mongodbruntime instance
MongoDBRuntime runtime = MongoDBRuntime.getDefaultInstance();
// Creating MongodbExecutable
mongodExe = runtime.prepare(new MongodConfig(Version.V2_0_1, 12345, Network.localhostIsIPv6()));
// Starting Mongodb
mongod = mongodExe.start();
mongo = new Mongo("localhost", 12345);
// Creating DB
db = mongo.getDB(DB_NAME);
// Creating collection Object and adding values
collection = db.getCollection("customers");
}
@After
public void teardown() throws Exception {
mongod.stop();
mongodExe.cleanup();
}
@Test
public void testAddressPersistance() {
BasicDBObject contact = new BasicDBObject();
contact.put("name", "John");
contact.put("company", "Baeldung");
// Inserting document
collection.insert(contact);
DBCursor cursorDoc = collection.find();
BasicDBObject contact1 = new BasicDBObject();
while (cursorDoc.hasNext()) {
contact1 = (BasicDBObject) cursorDoc.next();
System.out.println(contact1);
}
assertEquals(contact1.get("name"), "John");
}
}
@@ -0,0 +1,110 @@
package com.baeldung.geo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Indexes;
import com.mongodb.client.model.geojson.Point;
import com.mongodb.client.model.geojson.Polygon;
import com.mongodb.client.model.geojson.Position;
public class MongoGeospatialLiveTest {
private MongoClient mongoClient;
private MongoDatabase db;
private MongoCollection<Document> collection;
@Before
public void setup() {
if (mongoClient == null) {
mongoClient = new MongoClient();
db = mongoClient.getDatabase("myMongoDb");
collection = db.getCollection("places");
collection.deleteMany(new Document());
collection.createIndex(Indexes.geo2dsphere("location"));
collection.insertOne(Document.parse("{'name':'Big Ben','location': {'coordinates':[-0.1268194,51.5007292],'type':'Point'}}"));
collection.insertOne(Document.parse("{'name':'Hyde Park','location': {'coordinates': [[[-0.159381,51.513126],[-0.189615,51.509928],[-0.187373,51.502442], [-0.153019,51.503464],[-0.159381,51.513126]]],'type':'Polygon'}}"));
}
}
@Test
public void givenNearbyLocation_whenSearchNearby_thenFound() {
Point currentLoc = new Point(new Position(-0.126821, 51.495885));
FindIterable<Document> result = collection.find(Filters.near("location", currentLoc, 1000.0, 10.0));
assertNotNull(result.first());
assertEquals("Big Ben", result.first().get("name"));
}
@Test
public void givenFarLocation_whenSearchNearby_thenNotFound() {
Point currentLoc = new Point(new Position(-0.5243333, 51.4700223));
FindIterable<Document> result = collection.find(Filters.near("location", currentLoc, 5000.0, 10.0));
assertNull(result.first());
}
@Test
public void givenNearbyLocation_whenSearchWithinCircleSphere_thenFound() {
double distanceInRad = 5.0 / 6371;
FindIterable<Document> result = collection.find(Filters.geoWithinCenterSphere("location", -0.1435083, 51.4990956, distanceInRad));
assertNotNull(result.first());
assertEquals("Big Ben", result.first().get("name"));
}
@Test
public void givenNearbyLocation_whenSearchWithinBox_thenFound() {
double lowerLeftX = -0.1427638;
double lowerLeftY = 51.4991288;
double upperRightX = -0.1256209;
double upperRightY = 51.5030272;
FindIterable<Document> result = collection.find(Filters.geoWithinBox("location", lowerLeftX, lowerLeftY, upperRightX, upperRightY));
assertNotNull(result.first());
assertEquals("Big Ben", result.first().get("name"));
}
@Test
public void givenNearbyLocation_whenSearchWithinPolygon_thenFound() {
ArrayList<List<Double>> points = new ArrayList<List<Double>>();
points.add(Arrays.asList(-0.1439, 51.4952)); // victoria station
points.add(Arrays.asList(-0.1121, 51.4989));// Lambeth North
points.add(Arrays.asList(-0.13, 51.5163));// Tottenham Court Road
points.add(Arrays.asList(-0.1439, 51.4952)); // victoria station
FindIterable<Document> result = collection.find(Filters.geoWithinPolygon("location", points));
assertNotNull(result.first());
assertEquals("Big Ben", result.first().get("name"));
}
@Test
public void givenNearbyLocation_whenSearchUsingIntersect_thenFound() {
ArrayList<Position> positions = new ArrayList<Position>();
positions.add(new Position(-0.1439, 51.4952));
positions.add(new Position(-0.1346, 51.4978));
positions.add(new Position(-0.2177, 51.5135));
positions.add(new Position(-0.1439, 51.4952));
Polygon geometry = new Polygon(positions);
FindIterable<Document> result = collection.find(Filters.geoIntersects("location", geometry));
assertNotNull(result.first());
assertEquals("Hyde Park", result.first().get("name"));
}
}
@@ -0,0 +1,131 @@
package com.baeldung.morphia;
import static dev.morphia.aggregation.Group.grouping;
import static dev.morphia.aggregation.Group.push;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Iterator;
import java.util.List;
import org.bson.types.ObjectId;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import com.baeldung.morphia.domain.Author;
import com.baeldung.morphia.domain.Book;
import com.baeldung.morphia.domain.Publisher;
import com.mongodb.MongoClient;
import dev.morphia.Datastore;
import dev.morphia.Morphia;
import dev.morphia.query.Query;
import dev.morphia.query.UpdateOperations;
@Ignore
public class MorphiaIntegrationTest {
private static Datastore datastore;
private static ObjectId id = new ObjectId();
@BeforeClass
public static void setUp() {
Morphia morphia = new Morphia();
morphia.mapPackage("com.baeldung.morphia");
datastore = morphia.createDatastore(new MongoClient(), "library");
datastore.ensureIndexes();
}
@Test
public void givenDataSource_whenCreateEntity_thenEntityCreated() {
Publisher publisher = new Publisher(id, "Awsome Publisher");
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
Book companionBook = new Book("9789332575103", "Java Performance Companion", "Tom Kirkman", 1.95, publisher);
book.addCompanionBooks(companionBook);
datastore.save(companionBook);
datastore.save(book);
List<Book> books = datastore.createQuery(Book.class)
.field("title")
.contains("Learning Java")
.find()
.toList();
assertEquals(1, books.size());
assertEquals(book, books.get(0));
}
@Test
public void givenDocument_whenUpdated_thenUpdateReflected() {
Publisher publisher = new Publisher(id, "Awsome Publisher");
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
datastore.save(book);
Query<Book> query = datastore.createQuery(Book.class)
.field("title")
.contains("Learning Java");
UpdateOperations<Book> updates = datastore.createUpdateOperations(Book.class)
.inc("price", 1);
datastore.update(query, updates);
List<Book> books = datastore.createQuery(Book.class)
.field("title")
.contains("Learning Java")
.find()
.toList();
assertEquals(4.95, books.get(0)
.getCost());
}
@Test
public void givenDocument_whenDeleted_thenDeleteReflected() {
Publisher publisher = new Publisher(id, "Awsome Publisher");
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
datastore.save(book);
Query<Book> query = datastore.createQuery(Book.class)
.field("title")
.contains("Learning Java");
datastore.delete(query);
List<Book> books = datastore.createQuery(Book.class)
.field("title")
.contains("Learning Java")
.find()
.toList();
assertEquals(0, books.size());
}
@Test
public void givenDocument_whenAggregated_thenResultsCollected() {
Publisher publisher = new Publisher(id, "Awsome Publisher");
datastore.save(new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher));
datastore.save(new Book("9781449313142", "Learning Perl", "Mark Pence", 2.95, publisher));
datastore.save(new Book("9787564100476", "Learning Python", "Mark Pence", 5.95, publisher));
datastore.save(new Book("9781449368814", "Learning Scala", "Mark Pence", 6.95, publisher));
datastore.save(new Book("9781784392338", "Learning Go", "Jonathan Sawyer", 8.95, publisher));
Iterator<Author> authors = datastore.createAggregation(Book.class)
.group("author", grouping("books", push("title")))
.out(Author.class);
assertTrue(authors.hasNext());
}
@Test
public void givenDocument_whenProjected_thenOnlyProjectionReceived() {
Publisher publisher = new Publisher(id, "Awsome Publisher");
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
datastore.save(book);
List<Book> books = datastore.createQuery(Book.class)
.field("title")
.contains("Learning Java")
.project("title", true)
.find()
.toList();
assertEquals(books.size(), 1);
assertEquals("Learning Java", books.get(0)
.getTitle());
assertNull(books.get(0)
.getAuthor());
}
}
@@ -0,0 +1,178 @@
package com.baeldung.tagging;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.StreamSupport;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Test for {@link TagRepository}.
*
* @author Donato Rimenti
*
*/
public class TaggingLiveTest {
/**
* Object to test.
* Object to test.
*/
private TagRepository repository;
/**
* Sets the test up by instantiating the object to test.
*/
@Before
public void setup() {
repository = new TagRepository();
}
/**
* Tests {@link TagRepository#postsWithAtLeastOneTag(String...)} with 1 tag.
*/
@Test
public void givenTagRepository_whenPostsWithAtLeastOneTagMongoDB_then3Results() {
List<Post> results = repository.postsWithAtLeastOneTag("MongoDB");
results.forEach(System.out::println);
Assert.assertEquals(3, results.size());
results.forEach(post -> {
Assert.assertTrue(post.getTags().contains("MongoDB"));
});
}
/**
* Tests {@link TagRepository#postsWithAtLeastOneTag(String...)} with 2
* tags.
*/
@Test
public void givenTagRepository_whenPostsWithAtLeastOneTagMongoDBJava8_then4Results() {
List<Post> results = repository.postsWithAtLeastOneTag("MongoDB", "Java 8");
results.forEach(System.out::println);
Assert.assertEquals(4, results.size());
results.forEach(post -> {
Assert.assertTrue(post.getTags().contains("MongoDB") || post.getTags().contains("Java 8"));
});
}
/**
* Tests {@link TagRepository#postsWithAllTags(String...)} with 1 tag.
*/
@Test
public void givenTagRepository_whenPostsWithAllTagsMongoDB_then3Results() {
List<Post> results = repository.postsWithAllTags("MongoDB");
results.forEach(System.out::println);
Assert.assertEquals(3, results.size());
results.forEach(post -> {
Assert.assertTrue(post.getTags().contains("MongoDB"));
});
}
/**
* Tests {@link TagRepository#postsWithAllTags(String...)} with 2 tags.
*/
@Test
public void givenTagRepository_whenPostsWithAllTagsMongoDBJava8_then2Results() {
List<Post> results = repository.postsWithAllTags("MongoDB", "Java 8");
results.forEach(System.out::println);
Assert.assertEquals(2, results.size());
results.forEach(post -> {
Assert.assertTrue(post.getTags().contains("MongoDB"));
Assert.assertTrue(post.getTags().contains("Java 8"));
});
}
/**
* Tests {@link TagRepository#postsWithoutTags(String...)} with 1 tag.
*/
@Test
public void givenTagRepository_whenPostsWithoutTagsMongoDB_then1Result() {
List<Post> results = repository.postsWithoutTags("MongoDB");
results.forEach(System.out::println);
Assert.assertEquals(1, results.size());
results.forEach(post -> {
Assert.assertFalse(post.getTags().contains("MongoDB"));
});
}
/**
* Tests {@link TagRepository#postsWithoutTags(String...)} with 2 tags.
*/
@Test
public void givenTagRepository_whenPostsWithoutTagsMongoDBJava8_then0Results() {
List<Post> results = repository.postsWithoutTags("MongoDB", "Java 8");
results.forEach(System.out::println);
Assert.assertEquals(0, results.size());
results.forEach(post -> {
Assert.assertFalse(post.getTags().contains("MongoDB"));
Assert.assertFalse(post.getTags().contains("Java 8"));
});
}
/**
* Tests {@link TagRepository#addTags(String, List)} and
* {@link TagRepository#removeTags(String, List)}. These tests run together
* to keep the database in a consistent state.
*/
@Test
public void givenTagRepository_whenAddingRemovingElements_thenNoDuplicates() {
// Adds one element and checks the result.
boolean result = repository.addTags("Post 1", Arrays.asList("jUnit", "jUnit5"));
Assert.assertTrue(result);
// We add the same elements again to check that there's no duplication.
result = repository.addTags("Post 1", Arrays.asList("jUnit", "jUnit5"));
Assert.assertFalse(result);
// Fetches the element back to check if the elements have been added.
List<Post> postsAfterAddition = repository.postsWithAllTags("jUnit", "jUnit5");
Assert.assertEquals(1, postsAfterAddition.size());
postsAfterAddition.forEach(post -> {
Assert.assertTrue(post.getTags().contains("jUnit"));
Assert.assertTrue(post.getTags().contains("jUnit5"));
});
// Checks for duplication.
long countDuplicateTags = StreamSupport.stream(postsAfterAddition.get(0).getTags().spliterator(), false)
.filter(x -> x.equals("jUnit5")).count();
Assert.assertEquals(1, countDuplicateTags);
// Tries to remove the tags added.
result = repository.removeTags("Post 1", Arrays.asList("jUnit", "jUnit5"));
Assert.assertTrue(result);
// We remove the same elements again to check for errors.
result = repository.removeTags("Post 1", Arrays.asList("jUnit", "jUnit5"));
Assert.assertFalse(result);
// Fetches the element back to check if the elements have been removed.
List<Post> postsAfterDeletion = repository.postsWithAllTags("jUnit", "jUnit5");
Assert.assertEquals(0, postsAfterDeletion.size());
postsAfterDeletion = repository.postsWithAtLeastOneTag("jUnit");
Assert.assertEquals(0, postsAfterDeletion.size());
postsAfterDeletion = repository.postsWithAtLeastOneTag("jUnit5");
Assert.assertEquals(0, postsAfterDeletion.size());
}
/**
* Cleans up the test by deallocating memory.
*
* @throws IOException
*/
@After
public void teardown() throws IOException {
repository.close();
}
}