rename module to couchbase (#2646)
* added updated example codes * updated example code StringToCharStream * deleted StringToCharStream.java locally * removed redundant file * added code for apache commons collection SetUtils * refactored example code * added example code for bytebuddy * added example code for PCollections * update pom * refactored tests for PCollections * spring security xml config * spring security xml config * remove redundant comment * example code for apache-shiro * updated example code for Vavr Collections * updated Vavr's Collection example * updated Vavr Collection file * updated example code for Apache Shiro * updated Vavr Collections example * added example code for N1QL * update example code for N1QL * added integration test for N1QL * update N1QL Example code * update the N1QL example Code * rename module to couchbase * rename module to couchbase * change module name in parent module and pom
This commit is contained in:
committed by
Grzegorz Piwowarek
parent
d626f9c2bf
commit
90a102ec47
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.couchbase.async;
|
||||
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.TestExecutionListeners;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class })
|
||||
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
|
||||
public abstract class AsyncIntegrationTest {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.couchbase.async;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "com.baeldung.couchbase.async" })
|
||||
public class AsyncIntegrationTestConfig {
|
||||
}
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
package com.baeldung.couchbase.async.person;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
|
||||
import com.baeldung.couchbase.async.AsyncIntegrationTest;
|
||||
import com.baeldung.couchbase.async.person.Person;
|
||||
import com.baeldung.couchbase.async.person.PersonCrudService;
|
||||
import com.baeldung.couchbase.async.person.PersonDocumentConverter;
|
||||
import com.baeldung.couchbase.async.service.BucketService;
|
||||
import com.couchbase.client.java.Bucket;
|
||||
import com.couchbase.client.java.document.JsonDocument;
|
||||
|
||||
public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private PersonCrudService personService;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("TutorialBucketService")
|
||||
private BucketService bucketService;
|
||||
|
||||
@Autowired
|
||||
private PersonDocumentConverter converter;
|
||||
|
||||
private Bucket bucket;
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
bucket = bucketService.getBucket();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenRandomPerson_whenCreate_thenPersonPersisted() {
|
||||
// create person
|
||||
Person person = randomPerson();
|
||||
personService.create(person);
|
||||
|
||||
// check results
|
||||
assertNotNull(person.getId());
|
||||
assertNotNull(bucket.get(person.getId()));
|
||||
|
||||
// cleanup
|
||||
bucket.remove(person.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenId_whenRead_thenReturnsPerson() {
|
||||
// create and insert person document
|
||||
String id = insertRandomPersonDocument().id();
|
||||
|
||||
// read person and check results
|
||||
assertNotNull(personService.read(id));
|
||||
|
||||
// cleanup
|
||||
bucket.remove(id);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenNewHometown_whenUpdate_thenNewHometownPersisted() {
|
||||
// create and insert person document
|
||||
JsonDocument doc = insertRandomPersonDocument();
|
||||
|
||||
// update person
|
||||
Person expected = converter.fromDocument(doc);
|
||||
String updatedHomeTown = RandomStringUtils.randomAlphabetic(12);
|
||||
expected.setHomeTown(updatedHomeTown);
|
||||
personService.update(expected);
|
||||
|
||||
// check results
|
||||
JsonDocument actual = bucket.get(expected.getId());
|
||||
assertNotNull(actual);
|
||||
assertNotNull(actual.content());
|
||||
assertEquals(expected.getHomeTown(), actual.content().getString("homeTown"));
|
||||
|
||||
// cleanup
|
||||
bucket.remove(expected.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenRandomPerson_whenDelete_thenPersonNotInBucket() {
|
||||
// create and insert person document
|
||||
String id = insertRandomPersonDocument().id();
|
||||
|
||||
// delete person and check results
|
||||
personService.delete(id);
|
||||
assertNull(bucket.get(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenIds_whenReadBulk_thenReturnsOnlyPersonsWithMatchingIds() {
|
||||
List<String> ids = new ArrayList<>();
|
||||
|
||||
// add some person documents
|
||||
for (int i = 0; i < 5; i++) {
|
||||
ids.add(insertRandomPersonDocument().id());
|
||||
}
|
||||
|
||||
// perform bulk read
|
||||
List<Person> persons = personService.readBulk(ids);
|
||||
|
||||
// check results
|
||||
for (Person person : persons) {
|
||||
assertTrue(ids.contains(person.getId()));
|
||||
}
|
||||
|
||||
// cleanup
|
||||
for (String id : ids) {
|
||||
bucket.remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenPersons_whenInsertBulk_thenPersonsAreInserted() {
|
||||
|
||||
// create some persons
|
||||
List<Person> persons = new ArrayList<>();
|
||||
for (int i = 0; i < 5; i++) {
|
||||
persons.add(randomPerson());
|
||||
}
|
||||
|
||||
// perform bulk insert
|
||||
personService.createBulk(persons);
|
||||
|
||||
// check results
|
||||
for (Person person : persons) {
|
||||
assertNotNull(bucket.get(person.getId()));
|
||||
}
|
||||
|
||||
// cleanup
|
||||
for (Person person : persons) {
|
||||
bucket.remove(person.getId());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenPersons_whenUpdateBulk_thenPersonsAreUpdated() {
|
||||
|
||||
List<String> ids = new ArrayList<>();
|
||||
|
||||
// add some person documents
|
||||
for (int i = 0; i < 5; i++) {
|
||||
ids.add(insertRandomPersonDocument().id());
|
||||
}
|
||||
|
||||
// load persons from Couchbase
|
||||
List<Person> persons = new ArrayList<>();
|
||||
for (String id : ids) {
|
||||
persons.add(converter.fromDocument(bucket.get(id)));
|
||||
}
|
||||
|
||||
// modify persons
|
||||
for (Person person : persons) {
|
||||
person.setHomeTown(RandomStringUtils.randomAlphabetic(10));
|
||||
}
|
||||
|
||||
// perform bulk update
|
||||
personService.updateBulk(persons);
|
||||
|
||||
// check results
|
||||
for (Person person : persons) {
|
||||
JsonDocument doc = bucket.get(person.getId());
|
||||
assertEquals(person.getName(), doc.content().getString("name"));
|
||||
assertEquals(person.getHomeTown(), doc.content().getString("homeTown"));
|
||||
}
|
||||
|
||||
// cleanup
|
||||
for (String id : ids) {
|
||||
bucket.remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIds_whenDeleteBulk_thenPersonsAreDeleted() {
|
||||
|
||||
List<String> ids = new ArrayList<>();
|
||||
|
||||
// add some person documents
|
||||
for (int i = 0; i < 5; i++) {
|
||||
ids.add(insertRandomPersonDocument().id());
|
||||
}
|
||||
|
||||
// perform bulk delete
|
||||
personService.deleteBulk(ids);
|
||||
|
||||
// check results
|
||||
for (String id : ids) {
|
||||
assertNull(bucket.get(id));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private JsonDocument insertRandomPersonDocument() {
|
||||
Person expected = randomPersonWithId();
|
||||
JsonDocument doc = converter.toDocument(expected);
|
||||
return bucket.insert(doc);
|
||||
}
|
||||
|
||||
private Person randomPerson() {
|
||||
return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build();
|
||||
}
|
||||
|
||||
private Person randomPersonWithId() {
|
||||
return Person.Builder.newInstance().id(UUID.randomUUID().toString()).name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build();
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.couchbase.async.service;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
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.TestExecutionListeners;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
|
||||
|
||||
import com.baeldung.couchbase.async.AsyncIntegrationTest;
|
||||
import com.baeldung.couchbase.async.AsyncIntegrationTestConfig;
|
||||
import com.baeldung.couchbase.async.service.ClusterService;
|
||||
import com.couchbase.client.java.Bucket;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class })
|
||||
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
|
||||
public class ClusterServiceIntegrationTest extends AsyncIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private ClusterService couchbaseService;
|
||||
|
||||
private Bucket defaultBucket;
|
||||
|
||||
@Test
|
||||
public void whenOpenBucket_thenBucketIsNotNull() throws Exception {
|
||||
defaultBucket = couchbaseService.openBucket("default", "");
|
||||
assertNotNull(defaultBucket);
|
||||
assertFalse(defaultBucket.isClosed());
|
||||
defaultBucket.close();
|
||||
}
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
package com.baeldung.couchbase.mapreduce;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.couchbase.client.java.document.JsonDocument;
|
||||
import com.couchbase.client.java.view.ViewResult;
|
||||
import com.couchbase.client.java.view.ViewRow;
|
||||
|
||||
public class StudentGradeServiceIntegrationTest {
|
||||
private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceIntegrationTest.class);
|
||||
|
||||
static StudentGradeService studentGradeService;
|
||||
static Set<String> gradeIds = new HashSet<>();
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpBeforeClass() throws Exception {
|
||||
studentGradeService = new StudentGradeService(new StudentGradeKeyGenerator());
|
||||
insertStudentGrade(new StudentGrade("John Doe", "History", 80, 3));
|
||||
insertStudentGrade(new StudentGrade("Jane Doe", "History", 89, 3));
|
||||
insertStudentGrade(new StudentGrade("Bob Smith", "History", 90, 3));
|
||||
insertStudentGrade(new StudentGrade("Mary Jones", "History", 92, 3));
|
||||
insertStudentGrade(new StudentGrade("Jane Doe", "Math", 59, 3));
|
||||
insertStudentGrade(new StudentGrade("Bob Smith", "Math", 91, 3));
|
||||
insertStudentGrade(new StudentGrade("Mary Jones", "Math", 86, 3));
|
||||
insertStudentGrade(new StudentGrade("John Doe", "Science", 85, 4));
|
||||
insertStudentGrade(new StudentGrade("Bob Smith", "Science", 97, 4));
|
||||
insertStudentGrade(new StudentGrade("Mary Jones", "Science", 84, 4));
|
||||
}
|
||||
|
||||
private static void insertStudentGrade(StudentGrade studentGrade) {
|
||||
try {
|
||||
String id = studentGradeService.insert(studentGrade);
|
||||
gradeIds.add(id);
|
||||
} catch (DuplicateKeyException e) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindAll_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findAll();
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindByCourse_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findByCourse("History");
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindByCourses_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findByCourses("History", "Science");
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindByGradeInRange_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findByGradeInRange(80, 89, true);
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindByGradeLessThan_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findByGradeLessThan(60);
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindByGradeGreaterThan_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findByGradeGreaterThan(90);
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindByCourseAndGradeInRange_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findByCourseAndGradeInRange("Math", 80, 89, true);
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindTopGradesByCourse_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findTopGradesByCourse("Science", 2);
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenCountStudentsByCourse_thenSuccess() {
|
||||
Map<String, Long> map = studentGradeService.countStudentsByCourse();
|
||||
printMap(map);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSumCreditHoursByStudent_thenSuccess() {
|
||||
Map<String, Long> map = studentGradeService.sumCreditHoursByStudent();
|
||||
printMap(map);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSumGradePointsByStudent_thenSuccess() {
|
||||
Map<String, Long> map = studentGradeService.sumGradePointsByStudent();
|
||||
printMap(map);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenCalculateGpaByStudent_thenSuccess() {
|
||||
Map<String, Float> map = studentGradeService.calculateGpaByStudent();
|
||||
printGpaMap(map);
|
||||
}
|
||||
|
||||
private void printMap(Map<String, Long> map) {
|
||||
for(Map.Entry<String, Long> entry : map.entrySet()) {
|
||||
logger.info(entry.getKey() + "=" + entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
private void printGpaMap(Map<String, Float> map) {
|
||||
for(Map.Entry<String, Float> entry : map.entrySet()) {
|
||||
logger.info(entry.getKey() + "=" + entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
private void printDocuments(List<JsonDocument> docs) {
|
||||
for(JsonDocument doc : docs) {
|
||||
String key = doc.id();
|
||||
logger.info(key + " = " + doc.content().toString());
|
||||
}
|
||||
}
|
||||
|
||||
private void printViewResultDocuments(ViewResult result) {
|
||||
for(ViewRow row : result.allRows()) {
|
||||
JsonDocument doc = row.document();
|
||||
String key = doc.id();
|
||||
logger.info(key + "=" + doc.content().toString());
|
||||
}
|
||||
}
|
||||
|
||||
private void printViewResultRows(ViewResult result) {
|
||||
for(ViewRow row : result.allRows()) {
|
||||
logger.info(row.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.couchbase.n1ql;
|
||||
|
||||
import com.couchbase.client.java.Cluster;
|
||||
import com.couchbase.client.java.CouchbaseCluster;
|
||||
import com.couchbase.client.java.env.CouchbaseEnvironment;
|
||||
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "com.baeldung.couchbase.n1ql" })
|
||||
public class IntegrationTestConfig {
|
||||
|
||||
@Bean
|
||||
public Cluster cluster() {
|
||||
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
|
||||
.connectTimeout(60000)
|
||||
.build();
|
||||
return CouchbaseCluster.create(env, "127.0.0.1");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package com.baeldung.couchbase.n1ql;
|
||||
|
||||
import com.couchbase.client.java.Bucket;
|
||||
import com.couchbase.client.java.Cluster;
|
||||
import com.couchbase.client.java.document.JsonDocument;
|
||||
import com.couchbase.client.java.document.json.JsonArray;
|
||||
import com.couchbase.client.java.document.json.JsonObject;
|
||||
import com.couchbase.client.java.query.N1qlQuery;
|
||||
import com.couchbase.client.java.query.N1qlQueryResult;
|
||||
import com.couchbase.client.java.query.N1qlQueryRow;
|
||||
import com.couchbase.client.java.query.Statement;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
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 rx.Observable;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult;
|
||||
import static com.couchbase.client.java.query.Select.select;
|
||||
import static com.couchbase.client.java.query.dsl.Expression.*;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { IntegrationTestConfig.class })
|
||||
public class N1QLIntegrationTest {
|
||||
|
||||
|
||||
@Autowired
|
||||
private Cluster cluster;
|
||||
|
||||
@Autowired
|
||||
private BucketFactory bucketFactory;
|
||||
|
||||
@Test
|
||||
public void givenAutowiredCluster_whenNotNull_thenNotNull() {
|
||||
assertNotNull(cluster);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBucketFactory_whenGetTestBucket_thenNotNull() {
|
||||
assertNotNull(bucketFactory.getTestBucket());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBucketFactory_whenGetTravelSampleBucket_thenNotNull() {
|
||||
assertNotNull(bucketFactory.getTravelSampleBucket());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDocument_whenInsert_thenResult() {
|
||||
Bucket bucket = bucketFactory.getTestBucket();
|
||||
JsonObject personObj = JsonObject.create()
|
||||
.put("name", "John")
|
||||
.put("email", "john@doe.com")
|
||||
.put("interests", JsonArray.from("Java", "Nigerian Jollof"));
|
||||
|
||||
String id = UUID.randomUUID().toString();
|
||||
JsonDocument doc = JsonDocument.create(id, personObj);
|
||||
bucket.insert(doc);
|
||||
assertNotNull(bucket.get(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBasicSelectQuery_thenGetQueryResult() {
|
||||
Bucket bucket = bucketFactory.getTravelSampleBucket();
|
||||
N1qlQueryResult result
|
||||
= bucket.query(N1qlQuery.simple("SELECT * FROM test"));
|
||||
|
||||
result.forEach(System.out::println);
|
||||
|
||||
System.out.println("result count: " + result.info().resultCount());
|
||||
System.out.println("error count: " + result.info().errorCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSelectStatement_whenQuery_thenResult() {
|
||||
Bucket bucket = bucketFactory.getTravelSampleBucket();
|
||||
String query = "SELECT name FROM `travel-sample` " +
|
||||
"WHERE type = 'airport' LIMIT 100";
|
||||
N1qlQueryResult result1 = bucket.query(N1qlQuery.simple(query));
|
||||
|
||||
System.out.println("Result Count " + result1.info().resultCount());
|
||||
|
||||
N1qlQueryRow row = result1.allRows().get(0);
|
||||
JsonObject rowJson = row.value();
|
||||
System.out.println("Name in First Row " + rowJson.get("name"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSelectStatement2_whenQuery_thenResult() {
|
||||
Bucket bucket = bucketFactory.getTravelSampleBucket();
|
||||
JsonObject pVal = JsonObject.create().put("type", "airport");
|
||||
String query = "SELECT * FROM `travel-sample` " +
|
||||
"WHERE type = $type LIMIT 100";
|
||||
N1qlQueryResult r2 = bucket.query(N1qlQuery.parameterized(query, pVal));
|
||||
|
||||
System.out.println(r2.allRows());
|
||||
|
||||
List<JsonNode> list = extractJsonResult(r2);
|
||||
System.out.println(
|
||||
list.get(0).get("travel-sample").get("airportname").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSelectDSL_whenQuery_thenResult() {
|
||||
Bucket bucket = bucketFactory.getTravelSampleBucket();
|
||||
Statement statement = select("*")
|
||||
.from(i("travel-sample"))
|
||||
.where(x("type").eq(s("airport")))
|
||||
.limit(100);
|
||||
N1qlQueryResult r3 = bucket.query(N1qlQuery.simple(statement));
|
||||
|
||||
List<JsonNode> list2 = extractJsonResult(r3);
|
||||
System.out.println("First Airport Name: " + list2.get(0).get("travel-sample").get("airportname").asText());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSelectStatementWithOperators_whenQuery_thenResult() {
|
||||
Bucket bucket = bucketFactory.getTravelSampleBucket();
|
||||
String query2 = "SELECT t.city, " +
|
||||
"t.airportname || \" (\" || t.faa || \")\" AS portname_faa " +
|
||||
"FROM `travel-sample` t " +
|
||||
"WHERE t.type=\"airport\"" +
|
||||
"AND t.country LIKE '%States'" +
|
||||
"AND t.geo.lat >= 70 " +
|
||||
"LIMIT 2";
|
||||
N1qlQueryResult r4 = bucket.query(N1qlQuery.simple(query2));
|
||||
List<JsonNode> list3 = extractJsonResult(r4);
|
||||
System.out.println("First Doc : " + list3.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSelectStatementWithDSL2_whenQuery_thenResult() {
|
||||
Bucket bucket = bucketFactory.getTravelSampleBucket();
|
||||
Statement st2 = select(
|
||||
x("t.city, t.airportname")
|
||||
.concat(s(" (")).concat(x("t.faa")).concat(s(")")).as("portname_faa"))
|
||||
.from(i("travel-sample").as("t"))
|
||||
.where( x("t.type").eq(s("airport"))
|
||||
.and(x("t.country").like(s("%States")))
|
||||
.and(x("t.geo.lat").gte(70)))
|
||||
.limit(2);
|
||||
N1qlQueryResult r5 = bucket.query(N1qlQuery.simple(st2));
|
||||
List<JsonNode> list5 = extractJsonResult(r5);
|
||||
System.out.println("First Doc : " + list5.get(0));
|
||||
System.out.println("Query from Statement2: " + st2.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInsertStatement_whenQuery_thenUpdate() {
|
||||
Bucket bucket = bucketFactory.getTravelSampleBucket();
|
||||
String query = "INSERT INTO `travel-sample` (KEY, VALUE) " +
|
||||
" VALUES(" +
|
||||
"\"cust1293\", " +
|
||||
"{\"id\":\"1293\",\"name\":\"Sample Airline\", \"type\":\"airline\"})" +
|
||||
" RETURNING META().id as docid, *";
|
||||
N1qlQueryResult r1 = bucket.query(N1qlQuery.simple(query));
|
||||
r1.forEach(System.out::println);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDocument_whenInsert_thenResults() {
|
||||
Bucket bucket = bucketFactory.getTravelSampleBucket();
|
||||
JsonObject ob = JsonObject.create()
|
||||
.put("id", "1293")
|
||||
.put("name", "Sample Airline")
|
||||
.put("type", "airline");
|
||||
bucket.insert(JsonDocument.create("cust1295", ob));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDocuments_whenBatchInsert_thenResult() {
|
||||
Bucket bucket = bucketFactory.getTravelSampleBucket();
|
||||
|
||||
List<JsonDocument> documents = IntStream.rangeClosed(0,10)
|
||||
.mapToObj( i -> {
|
||||
JsonObject content = JsonObject.create()
|
||||
.put("id", i)
|
||||
.put("type", "airline")
|
||||
.put("name", "Sample Airline " + i);
|
||||
return JsonDocument.create("cust_" + i, content);
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
List<JsonDocument> r5 = Observable
|
||||
.from(documents)
|
||||
.flatMap(doc -> bucket.async().insert(doc))
|
||||
.toList()
|
||||
.last()
|
||||
.toBlocking()
|
||||
.single();
|
||||
|
||||
r5.forEach(System.out::println);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUpdateStatement_whenQuery_thenUpdate() {
|
||||
Bucket bucket = bucketFactory.getTravelSampleBucket();
|
||||
String query2 = "UPDATE `travel-sample` USE KEYS \"cust_1\" " +
|
||||
"SET name=\"Sample Airline Updated\" RETURNING name";
|
||||
N1qlQueryResult result = bucket.query(N1qlQuery.simple(query2));
|
||||
result.forEach(System.out::println);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDocument_whenUpsert_thenUpdate() {
|
||||
Bucket bucket = bucketFactory.getTravelSampleBucket();
|
||||
JsonObject o2 = JsonObject.create()
|
||||
.put("name", "Sample Airline Updated");
|
||||
bucket.upsert(JsonDocument.create("cust_1", o2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnestUpdateStatement_whenQuery_thenResult() {
|
||||
Bucket bucket = bucketFactory.getTravelSampleBucket();
|
||||
String query3 = "UPDATE `travel-sample` USE KEYS \"cust_2\" " +
|
||||
"UNSET name RETURNING *";
|
||||
N1qlQueryResult result1 = bucket.query(N1qlQuery.simple(query3));
|
||||
result1.forEach(System.out::println);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDeleteStatement_whenQuery_thenDelete() {
|
||||
Bucket bucket = bucketFactory.getTravelSampleBucket();
|
||||
String query4 = "DELETE FROM `travel-sample` USE KEYS \"cust_50\"";
|
||||
N1qlQueryResult result4 = bucket.query(N1qlQuery.simple(query4));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDeleteStatement2_whenQuery_thenDelete() {
|
||||
Bucket bucket = bucketFactory.getTravelSampleBucket();
|
||||
String query5 = "DELETE FROM `travel-sample` WHERE id = 0 RETURNING *";
|
||||
N1qlQueryResult result5 = bucket.query(N1qlQuery.simple(query5));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.couchbase.spring;
|
||||
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.TestExecutionListeners;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { IntegrationTestConfig.class })
|
||||
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
|
||||
public abstract class IntegrationTest {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.couchbase.spring;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "com.baeldung.couchbase.spring" })
|
||||
public class IntegrationTestConfig {
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.baeldung.couchbase.spring.person;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import com.baeldung.couchbase.spring.IntegrationTest;
|
||||
|
||||
public class PersonCrudServiceIntegrationTest extends IntegrationTest {
|
||||
|
||||
private static final String CLARK_KENT = "Clark Kent";
|
||||
private static final String SMALLVILLE = "Smallville";
|
||||
private static final String CLARK_KENT_ID = "Person:ClarkKent";
|
||||
|
||||
private Person clarkKent;
|
||||
|
||||
@Autowired
|
||||
private PersonCrudService personService;
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
clarkKent = personService.read(CLARK_KENT_ID);
|
||||
if (clarkKent == null) {
|
||||
clarkKent = buildClarkKent();
|
||||
personService.create(clarkKent);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenRandomPerson_whenCreate_thenPersonPersisted() {
|
||||
Person person = randomPerson();
|
||||
personService.create(person);
|
||||
String id = person.getId();
|
||||
assertNotNull(personService.read(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenClarkKentId_whenRead_thenReturnsClarkKent() {
|
||||
Person person = personService.read(CLARK_KENT_ID);
|
||||
assertNotNull(person);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenNewHometown_whenUpdate_thenNewHometownPersisted() {
|
||||
Person expected = randomPerson();
|
||||
personService.create(expected);
|
||||
String updatedHomeTown = RandomStringUtils.randomAlphabetic(12);
|
||||
expected.setHomeTown(updatedHomeTown);
|
||||
personService.update(expected);
|
||||
Person actual = personService.read(expected.getId());
|
||||
assertNotNull(actual);
|
||||
assertEquals(expected.getHomeTown(), actual.getHomeTown());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenRandomPerson_whenDelete_thenPersonNotInBucket() {
|
||||
Person person = randomPerson();
|
||||
personService.create(person);
|
||||
String id = person.getId();
|
||||
personService.delete(id);
|
||||
assertNull(personService.read(id));
|
||||
}
|
||||
|
||||
private Person buildClarkKent() {
|
||||
return Person.Builder.newInstance().id(CLARK_KENT_ID).name(CLARK_KENT).homeTown(SMALLVILLE).build();
|
||||
}
|
||||
|
||||
private Person randomPerson() {
|
||||
return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build();
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.couchbase.spring.service;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
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.TestExecutionListeners;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
|
||||
|
||||
import com.baeldung.couchbase.spring.IntegrationTest;
|
||||
import com.baeldung.couchbase.spring.IntegrationTestConfig;
|
||||
import com.couchbase.client.java.Bucket;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { IntegrationTestConfig.class })
|
||||
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
|
||||
public class ClusterServiceIntegrationTest extends IntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private ClusterService couchbaseService;
|
||||
|
||||
private Bucket defaultBucket;
|
||||
|
||||
@Test
|
||||
public void whenOpenBucket_thenBucketIsNotNull() throws Exception {
|
||||
defaultBucket = couchbaseService.openBucket("default", "");
|
||||
assertNotNull(defaultBucket);
|
||||
assertFalse(defaultBucket.isClosed());
|
||||
defaultBucket.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user