Merge branch 'eugenp:master' into JAVA-18149
This commit is contained in:
@@ -67,6 +67,8 @@ ethereum/logs/
|
||||
jmeter/src/main/resources/*-JMeter.csv
|
||||
jmeter/src/main/resources/*-Basic*.csv
|
||||
jmeter/src/main/resources/*-JMeter*.csv
|
||||
jmeter/src/main/resources/*ReportsDashboard*.csv
|
||||
jmeter/src/main/resources/dashboard/*ReportsDashboard*.csv
|
||||
|
||||
ninja/devDb.mv.db
|
||||
|
||||
|
||||
+7
-3
@@ -80,16 +80,20 @@ public class BaeldungIntegrationTest {
|
||||
private void marshalCourseRepo(CourseRepo courseRepo) throws Exception {
|
||||
AegisWriter<XMLStreamWriter> writer = context.createXMLStreamWriter();
|
||||
AegisType aegisType = context.getTypeMapping().getType(CourseRepo.class);
|
||||
XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(fileName));
|
||||
final FileOutputStream stream = new FileOutputStream(fileName);
|
||||
XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(stream);
|
||||
writer.write(courseRepo, new QName("http://aegis.cxf.baeldung.com", "baeldung"), false, xmlWriter, aegisType);
|
||||
xmlWriter.close();
|
||||
stream.close();
|
||||
}
|
||||
|
||||
private CourseRepo unmarshalCourseRepo() throws Exception {
|
||||
AegisReader<XMLStreamReader> reader = context.createXMLStreamReader();
|
||||
XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(fileName));
|
||||
final FileInputStream stream = new FileInputStream(fileName);
|
||||
XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
|
||||
CourseRepo courseRepo = (CourseRepo) reader.read(xmlReader, context.getTypeMapping().getType(CourseRepo.class));
|
||||
xmlReader.close();
|
||||
stream.close();
|
||||
return courseRepo;
|
||||
}
|
||||
|
||||
@@ -97,7 +101,7 @@ public class BaeldungIntegrationTest {
|
||||
public void cleanup(){
|
||||
File testFile = new File(fileName);
|
||||
if (testFile.exists()) {
|
||||
testFile.delete();
|
||||
testFile.deleteOnExit();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,7 @@
|
||||
<org.apache.httpcomponents.version>4.5.2</org.apache.httpcomponents.version>
|
||||
<velocity-version>1.7</velocity-version>
|
||||
<velocity-tools-version>2.0</velocity-tools-version>
|
||||
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+4
-4
@@ -62,10 +62,10 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<asciidoctor-maven-plugin.version>1.5.6</asciidoctor-maven-plugin.version>
|
||||
<asciidoctorj.version>1.5.6</asciidoctorj.version>
|
||||
<asciidoctorj-pdf.version>1.5.0-alpha.15</asciidoctorj-pdf.version>
|
||||
<asciidoctorj-pdf.plugin.version>1.5.0-alpha.15</asciidoctorj-pdf.plugin.version>
|
||||
<asciidoctor-maven-plugin.version>2.2.2</asciidoctor-maven-plugin.version>
|
||||
<asciidoctorj.version>2.5.7</asciidoctorj.version>
|
||||
<asciidoctorj-pdf.version>2.3.4</asciidoctorj-pdf.version>
|
||||
<asciidoctorj-pdf.plugin.version>2.3.4</asciidoctorj-pdf.plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -77,6 +77,7 @@
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@@ -92,6 +93,7 @@
|
||||
<properties>
|
||||
<spring.version>2.2.1.RELEASE</spring.version>
|
||||
<awssdk.version>2.17.283</awssdk.version>
|
||||
<lombok.version>1.18.20</lombok.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.argsVsvarargs;
|
||||
|
||||
public class StringArrayAndVarargs {
|
||||
public static void capitalizeNames(String[] args) {
|
||||
for(int i = 0; i < args.length; i++){
|
||||
args[i] = args[i].toUpperCase();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static String[] firstLetterOfWords(String... args) {
|
||||
String[] firstLetter = new String[args.length];
|
||||
for(int i = 0; i < args.length; i++){
|
||||
firstLetter[i] = String.valueOf(args[i].charAt(0));
|
||||
}
|
||||
return firstLetter;
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.argsVsvarargs;
|
||||
|
||||
import static com.baeldung.argsVsvarargs.StringArrayAndVarargs.capitalizeNames;
|
||||
import static com.baeldung.argsVsvarargs.StringArrayAndVarargs.firstLetterOfWords;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class StringArrayAndVarargsUnitTest {
|
||||
|
||||
@Test
|
||||
void whenCheckingArgumentClassName_thenNameShouldBeStringArray() {
|
||||
String[] names = {"john", "ade", "kofi", "imo"};
|
||||
assertNotNull(names);
|
||||
assertEquals("java.lang.String[]", names.getClass().getTypeName());
|
||||
capitalizeNames(names);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCheckingReturnedObjectClass_thenClassShouldBeStringArray() {
|
||||
assertEquals(String[].class, firstLetterOfWords("football", "basketball", "volleyball").getClass());
|
||||
assertEquals(3, firstLetterOfWords("football", "basketball", "volleyball").length);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.baeldung.array.isobjectarray;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CheckObjectIsArrayUnitTest {
|
||||
private static final Object ARRAY_INT = new int[] { 1, 2, 3, 4, 5 };
|
||||
private static final Object ARRAY_PERSON = new Person[] { new Person("Jackie Chan", "Hong Kong"), new Person("Tom Hanks", "United States") };
|
||||
|
||||
boolean isArray(Object obj) {
|
||||
return obj instanceof Object[] || obj instanceof boolean[] || obj instanceof byte[] || obj instanceof short[] || obj instanceof char[] || obj instanceof int[] || obj instanceof long[] || obj instanceof float[] || obj instanceof double[];
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAnArrayObject_whenUsingInstanceof_getExpectedResult() {
|
||||
assertTrue(ARRAY_PERSON instanceof Object[]);
|
||||
assertFalse(ARRAY_INT instanceof Object[]);
|
||||
assertTrue(ARRAY_INT instanceof int[]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAnArrayObject_whenUsingOurIsArray_getExpectedResult() {
|
||||
assertTrue(isArray(ARRAY_PERSON));
|
||||
assertTrue(isArray(ARRAY_INT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAnArrayObject_whenUsingClassIsArray_getExpectedResult() {
|
||||
assertTrue(ARRAY_INT.getClass()
|
||||
.isArray());
|
||||
assertTrue(ARRAY_PERSON.getClass()
|
||||
.isArray());
|
||||
|
||||
assertEquals(Person.class, ARRAY_PERSON.getClass()
|
||||
.getComponentType());
|
||||
assertEquals(int.class, ARRAY_INT.getClass()
|
||||
.getComponentType());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAnArrayObject_whenUsingArrayGet_getExpectedElement() {
|
||||
if (ARRAY_PERSON.getClass()
|
||||
.isArray() && ARRAY_PERSON.getClass()
|
||||
.getComponentType() == Person.class) {
|
||||
Person person = (Person) Array.get(ARRAY_PERSON, 1);
|
||||
assertEquals("Tom Hanks", person.getName());
|
||||
}
|
||||
if (ARRAY_INT.getClass()
|
||||
.isArray() && ARRAY_INT.getClass()
|
||||
.getComponentType() == int.class) {
|
||||
assertEquals(2, ((int) Array.get(ARRAY_INT, 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Person {
|
||||
private String name;
|
||||
private String Location;
|
||||
|
||||
public Person(String name, String location) {
|
||||
this.name = name;
|
||||
this.Location = location;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getLocation() {
|
||||
return Location;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package com.baeldung.concurrent.atomic;
|
||||
|
||||
public class SafeCounterWithLock {
|
||||
private volatile int counter;
|
||||
private int counter;
|
||||
|
||||
int getValue() {
|
||||
return counter;
|
||||
|
||||
+1
-7
@@ -10,12 +10,6 @@ public class SafeCounterWithoutLock {
|
||||
}
|
||||
|
||||
void increment() {
|
||||
while(true) {
|
||||
int existingValue = getValue();
|
||||
int newValue = existingValue + 1;
|
||||
if(counter.compareAndSet(existingValue, newValue)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
counter.incrementAndGet();
|
||||
}
|
||||
}
|
||||
|
||||
+24
-4
@@ -17,8 +17,8 @@ public class ThreadSafeCounterIntegrationTest {
|
||||
SafeCounterWithLock safeCounter = new SafeCounterWithLock();
|
||||
|
||||
IntStream.range(0, 1000)
|
||||
.forEach(count -> service.submit(safeCounter::increment));
|
||||
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
.forEach(count -> service.execute(safeCounter::increment));
|
||||
shutdownAndAwaitTermination(service);
|
||||
|
||||
assertEquals(1000, safeCounter.getValue());
|
||||
}
|
||||
@@ -29,10 +29,30 @@ public class ThreadSafeCounterIntegrationTest {
|
||||
SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock();
|
||||
|
||||
IntStream.range(0, 1000)
|
||||
.forEach(count -> service.submit(safeCounter::increment));
|
||||
service.awaitTermination(100, TimeUnit.MILLISECONDS);
|
||||
.forEach(count -> service.execute(safeCounter::increment));
|
||||
shutdownAndAwaitTermination(service);
|
||||
|
||||
assertEquals(1000, safeCounter.getValue());
|
||||
}
|
||||
|
||||
private void shutdownAndAwaitTermination(ExecutorService pool) {
|
||||
// Disable new tasks from being submitted
|
||||
pool.shutdown();
|
||||
try {
|
||||
// Wait a while for existing tasks to terminate
|
||||
if (!pool.awaitTermination(100, TimeUnit.MILLISECONDS)) {
|
||||
// Cancel currently executing tasks forcefully
|
||||
pool.shutdownNow();
|
||||
// Wait a while for tasks to respond to being cancelled
|
||||
if (!pool.awaitTermination(100, TimeUnit.MILLISECONDS))
|
||||
System.err.println("Pool did not terminate");
|
||||
}
|
||||
} catch (InterruptedException ex) {
|
||||
// (Re-)Cancel if current thread also interrupted
|
||||
pool.shutdownNow();
|
||||
// Preserve interrupt status
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?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>
|
||||
<artifactId>core-java-hex</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-hex</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.hextorgb;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class HexToRgbUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenHexCode_whenConvertedToRgb_thenCorrectRgbValuesAreReturned() {
|
||||
String hexCode = "FF9933";
|
||||
int red = 255;
|
||||
int green = 153;
|
||||
int blue = 51;
|
||||
|
||||
int resultRed = Integer.valueOf(hexCode.substring(0, 2), 16);
|
||||
int resultGreen = Integer.valueOf(hexCode.substring(2, 4), 16);
|
||||
int resultBlue = Integer.valueOf(hexCode.substring(4, 6), 16);
|
||||
|
||||
assertEquals(red, resultRed);
|
||||
assertEquals(green, resultGreen);
|
||||
assertEquals(blue, resultBlue);
|
||||
}
|
||||
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.firstocurrenceofaninteger;
|
||||
|
||||
public class FirstOccurrenceOfAnInteger {
|
||||
|
||||
static Integer findFirstInteger(String s) {
|
||||
int i = 0;
|
||||
while (i < s.length() && !Character.isDigit(s.charAt(i))) {
|
||||
i++;
|
||||
}
|
||||
int j = i;
|
||||
while (j < s.length() && Character.isDigit(s.charAt(j))) {
|
||||
j++;
|
||||
}
|
||||
return Integer.parseInt(s.substring(i, j));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.firstocurrenceofaninteger;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
class FirstOccurrenceOfAnIntegerUnitTest {
|
||||
|
||||
@Test
|
||||
void whenUsingPatternMatcher_findFirstInteger() {
|
||||
String s = "ba31dung123";
|
||||
Matcher matcher = Pattern.compile("\\d+").matcher(s);
|
||||
matcher.find();
|
||||
int i = Integer.parseInt(matcher.group());
|
||||
Assertions.assertEquals(31, i);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingScanner_findFirstInteger() {
|
||||
int i = new Scanner("ba31dung123").useDelimiter("\\D+").nextInt();
|
||||
Assertions.assertEquals(31, i);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingSplit_findFirstInteger() {
|
||||
String str = "ba31dung123";
|
||||
List<String> tokens = Arrays.stream(str.split("\\D+"))
|
||||
.filter(s -> s.length() > 0).collect(Collectors.toList());
|
||||
Assertions.assertEquals(31, Integer.parseInt(tokens.get(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingCustomMethod_findFirstInteger() {
|
||||
String str = "ba31dung123";
|
||||
Integer i = FirstOccurrenceOfAnInteger.findFirstInteger(str);
|
||||
Assertions.assertEquals(31, i);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -62,6 +62,7 @@
|
||||
<module>core-java-exceptions-4</module>
|
||||
<module>core-java-function</module>
|
||||
<module>core-java-functional</module>
|
||||
<module>core-java-hex</module>
|
||||
<module>core-java-io</module>
|
||||
<module>core-java-io-2</module>
|
||||
<module>core-java-io-3</module>
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<guice.version>4.1.0</guice.version>
|
||||
<guice.version>5.0.1</guice.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+1
-1
@@ -136,7 +136,7 @@
|
||||
<resultsDirectory>${project.basedir}/src/main/resources/dashboard</resultsDirectory>
|
||||
<generateReports>true</generateReports>
|
||||
<ignoreResultFailures>true</ignoreResultFailures>
|
||||
<testResultsTimestamp>false</testResultsTimestamp>
|
||||
<testResultsTimestamp>true</testResultsTimestamp>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>rethinkdb</artifactId>
|
||||
<name>rethinkdb</name>
|
||||
<description>Code snippets for RethinkDB articles</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.rethinkdb</groupId>
|
||||
<artifactId>rethinkdb-driver</artifactId>
|
||||
<version>2.4.4</version>
|
||||
</dependency>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.rethinkdb;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static com.rethinkdb.RethinkDB.r;
|
||||
|
||||
/**
|
||||
* Some tests demonstrating inserting data.
|
||||
*/
|
||||
public class InsertIntegrationTest extends TestBase {
|
||||
/**
|
||||
* Create a table for the tests.
|
||||
*/
|
||||
@BeforeEach
|
||||
public void createTable() {
|
||||
r.db(DB_NAME).tableCreate(tableName).run(conn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a single simple record into the database.
|
||||
*/
|
||||
@Test
|
||||
public void insertSimpleRecord() {
|
||||
r.db(DB_NAME).table(tableName)
|
||||
.insert(
|
||||
r.hashMap()
|
||||
.with("name", "Baeldung")
|
||||
)
|
||||
.run(conn);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void insertMap() {
|
||||
r.db(DB_NAME).table(tableName)
|
||||
.insert(
|
||||
Map.of("name", "Baeldung")
|
||||
)
|
||||
.run(conn);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void insertComplex() {
|
||||
r.db(DB_NAME).table(tableName)
|
||||
.insert(
|
||||
r.hashMap()
|
||||
.with("name", "Baeldung")
|
||||
.with("articles", r.array(
|
||||
r.hashMap()
|
||||
.with("name", "String Interpolation in Java")
|
||||
.with("url", "https://www.baeldung.com/java-string-interpolation"),
|
||||
r.hashMap()
|
||||
.with("name", "Access HTTPS REST Service Using Spring RestTemplate")
|
||||
.with("url", "https://www.baeldung.com/spring-resttemplate-secure-https-service")
|
||||
)
|
||||
)
|
||||
)
|
||||
.run(conn);
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package com.baeldung.rethinkdb;
|
||||
|
||||
import com.rethinkdb.net.Result;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.rethinkdb.RethinkDB.r;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Some tests demonstrating querying data.
|
||||
*/
|
||||
public class QueryIntegrationTest extends TestBase {
|
||||
/**
|
||||
* Create a table for the tests.
|
||||
*/
|
||||
@BeforeEach
|
||||
public void createTable() {
|
||||
r.db(DB_NAME).tableCreate(tableName).run(conn);
|
||||
|
||||
r.db(DB_NAME).table(tableName)
|
||||
.insert(
|
||||
r.hashMap()
|
||||
.with("id", "article1")
|
||||
.with("name", "String Interpolation in Java")
|
||||
.with("url", "https://www.baeldung.com/java-string-interpolation")
|
||||
).run(conn);
|
||||
r.db(DB_NAME).table(tableName)
|
||||
.insert(
|
||||
r.hashMap()
|
||||
.with("id", "article2")
|
||||
.with("name", "Access HTTPS REST Service Using Spring RestTemplate")
|
||||
.with("url", "https://www.baeldung.com/spring-resttemplate-secure-https-service")
|
||||
).run(conn);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listAll() {
|
||||
Result<Map> results = r.db(DB_NAME).table(tableName).run(conn, Map.class);
|
||||
|
||||
// We can't ensure the order the results come back in.
|
||||
Set<String> expected = new HashSet<>(Set.of(
|
||||
"String Interpolation in Java",
|
||||
"Access HTTPS REST Service Using Spring RestTemplate"
|
||||
));
|
||||
|
||||
for (Map result : results) {
|
||||
assertTrue(expected.remove(result.get("name")));
|
||||
}
|
||||
|
||||
assertTrue(expected.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listSome() {
|
||||
Result<Map> results = r.db(DB_NAME)
|
||||
.table(tableName)
|
||||
.filter(r -> r.g("name").eq("String Interpolation in Java"))
|
||||
.run(conn, Map.class);
|
||||
|
||||
// We can't ensure the order the results come back in.
|
||||
Set<String> expected = Set.of("https://www.baeldung.com/java-string-interpolation");
|
||||
|
||||
assertEquals(expected, results.stream()
|
||||
.map(r -> r.get("url"))
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getByKey() {
|
||||
Result<Map> results = r.db(DB_NAME).table(tableName).get("article1").run(conn, Map.class);
|
||||
|
||||
assertEquals("String Interpolation in Java", results.first().get("name"));
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package com.baeldung.rethinkdb;
|
||||
|
||||
import com.rethinkdb.net.Result;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.rethinkdb.RethinkDB.r;
|
||||
|
||||
/**
|
||||
* Some tests demonstrating streaming live changes to data.
|
||||
*/
|
||||
public class StreamingIntegrationTest extends TestBase {
|
||||
@Test
|
||||
public void getLiveInserts() throws InterruptedException {
|
||||
ExecutorService executorService = Executors.newCachedThreadPool();
|
||||
|
||||
r.db(DB_NAME).tableCreate(tableName).run(conn);
|
||||
|
||||
r.db(DB_NAME).table(tableName).insert(r.hashMap().with("index", 0)).run(conn);
|
||||
|
||||
executorService.submit(() -> {
|
||||
Result<Map> cursor = r.db(DB_NAME).table(tableName).changes().run(conn, Map.class);
|
||||
|
||||
cursor.stream().forEach(record -> System.out.println("Record: " + record));
|
||||
});
|
||||
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
r.db(DB_NAME).table(tableName).insert(r.hashMap().with("index", i)).run(conn);
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
}
|
||||
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getSomeLiveInserts() throws InterruptedException {
|
||||
ExecutorService executorService = Executors.newCachedThreadPool();
|
||||
|
||||
r.db(DB_NAME).tableCreate(tableName).run(conn);
|
||||
|
||||
r.db(DB_NAME).table(tableName).insert(r.hashMap().with("index", 0)).run(conn);
|
||||
|
||||
executorService.submit(() -> {
|
||||
Result<Map> cursor = r.db(DB_NAME).table(tableName)
|
||||
.filter(r -> r.g("index").eq(5))
|
||||
.changes()
|
||||
.run(conn, Map.class);
|
||||
|
||||
cursor.stream().forEach(record -> System.out.println("Record: " + record));
|
||||
});
|
||||
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
r.db(DB_NAME).table(tableName).insert(r.hashMap().with("index", i)).run(conn);
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
}
|
||||
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getLiveUpdates() throws InterruptedException {
|
||||
ExecutorService executorService = Executors.newCachedThreadPool();
|
||||
|
||||
r.db(DB_NAME).tableCreate(tableName).run(conn);
|
||||
|
||||
r.db(DB_NAME).table(tableName).insert(r.hashMap().with("index", 0)).run(conn);
|
||||
|
||||
executorService.submit(() -> {
|
||||
Result<Map> cursor = r.db(DB_NAME).table(tableName).changes().run(conn, Map.class);
|
||||
|
||||
cursor.stream().forEach(record -> System.out.println("Record: " + record));
|
||||
});
|
||||
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
r.db(DB_NAME).table(tableName).update(r.hashMap().with("index", i)).run(conn);
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
}
|
||||
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getLiveDeletes() throws InterruptedException {
|
||||
ExecutorService executorService = Executors.newCachedThreadPool();
|
||||
|
||||
r.db(DB_NAME).tableCreate(tableName).run(conn);
|
||||
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
r.db(DB_NAME).table(tableName).insert(r.hashMap().with("index", i)).run(conn);
|
||||
}
|
||||
|
||||
executorService.submit(() -> {
|
||||
Result<Map> cursor = r.db(DB_NAME).table(tableName).changes().run(conn, Map.class);
|
||||
|
||||
cursor.stream().forEach(record -> System.out.println("Record: " + record));
|
||||
});
|
||||
|
||||
r.db(DB_NAME).table(tableName)
|
||||
.filter(r -> r.g("index").eq(1))
|
||||
.delete()
|
||||
.run(conn);
|
||||
r.db(DB_NAME).table(tableName)
|
||||
.filter(r -> r.g("index").eq(3))
|
||||
.delete()
|
||||
.run(conn);
|
||||
r.db(DB_NAME).table(tableName)
|
||||
.filter(r -> r.g("index").eq(5))
|
||||
.delete()
|
||||
.run(conn);
|
||||
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.rethinkdb;
|
||||
|
||||
import com.rethinkdb.gen.exc.ReqlOpFailedError;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static com.rethinkdb.RethinkDB.r;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Some tests demonstrating working with tables.
|
||||
*/
|
||||
public class TablesIntegrationTest extends TestBase {
|
||||
|
||||
@Test
|
||||
public void createTable() {
|
||||
r.db(DB_NAME).tableCreate(tableName).run(conn);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createTableTwice() {
|
||||
r.db(DB_NAME).tableCreate(tableName).run(conn);
|
||||
|
||||
Assertions.assertThrows(ReqlOpFailedError.class, () -> {
|
||||
r.db(DB_NAME).tableCreate(tableName).run(conn);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listTables() {
|
||||
r.db(DB_NAME).tableCreate(tableName).run(conn);
|
||||
|
||||
List<String> tables = r.db(DB_NAME).tableList().run(conn, List.class).first();
|
||||
|
||||
assertTrue(tables.contains(tableName));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.rethinkdb;
|
||||
|
||||
import com.rethinkdb.net.Connection;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static com.rethinkdb.RethinkDB.r;
|
||||
|
||||
/**
|
||||
* Base class for RethinkDB tests.
|
||||
*/
|
||||
public class TestBase {
|
||||
/** The database name to work with */
|
||||
protected static final String DB_NAME = "test";
|
||||
|
||||
/** A randomly generated table name so they never collide */
|
||||
protected final String tableName = UUID.randomUUID().toString().replaceAll("-","");
|
||||
|
||||
/** A database connection */
|
||||
protected Connection conn;
|
||||
|
||||
/**
|
||||
* Connect to the database for each test
|
||||
*/
|
||||
@BeforeEach
|
||||
public void connect() {
|
||||
conn = r.connection()
|
||||
.hostname("localhost")
|
||||
.port(28015)
|
||||
.connect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect from the database after each test
|
||||
*/
|
||||
@AfterEach
|
||||
public void disconnect() {
|
||||
if (this.conn != null) {
|
||||
conn.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.rethinkdb;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static com.rethinkdb.RethinkDB.r;
|
||||
|
||||
/**
|
||||
* Some tests demonstrating updating data.
|
||||
*/
|
||||
public class UpdateIntegrationTest extends TestBase {
|
||||
/**
|
||||
* Create a table for the tests.
|
||||
*/
|
||||
@BeforeEach
|
||||
public void createTable() {
|
||||
r.db(DB_NAME).tableCreate(tableName).run(conn);
|
||||
|
||||
r.db(DB_NAME).table(tableName)
|
||||
.insert(
|
||||
r.hashMap()
|
||||
.with("id", "article1")
|
||||
.with("name", "String Interpolation in Java")
|
||||
.with("url", "https://www.baeldung.com/java-string-interpolation")
|
||||
).run(conn);
|
||||
r.db(DB_NAME).table(tableName)
|
||||
.insert(
|
||||
r.hashMap()
|
||||
.with("id", "article2")
|
||||
.with("name", "Access HTTPS REST Service Using Spring RestTemplate")
|
||||
.with("url", "https://www.baeldung.com/spring-resttemplate-secure-https-service")
|
||||
).run(conn);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updateAll() {
|
||||
r.db(DB_NAME).table(tableName).update(r.hashMap().with("site", "Baeldung")).run(conn);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updateSome() {
|
||||
r.db(DB_NAME).table(tableName)
|
||||
.filter(r -> r.g("name").eq("String Interpolation in Java"))
|
||||
.update(r.hashMap().with("category", "java"))
|
||||
.run(conn);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void delete() {
|
||||
r.db(DB_NAME).table(tableName)
|
||||
.filter(r -> r.g("name").eq("String Interpolation in Java"))
|
||||
.delete()
|
||||
.run(conn);
|
||||
}
|
||||
}
|
||||
-12
@@ -4,8 +4,6 @@ import org.bson.BsonBinary;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.mongodb.client.vault.ClientEncryption;
|
||||
|
||||
@Configuration
|
||||
public class EncryptionConfig {
|
||||
|
||||
@@ -21,18 +19,8 @@ public class EncryptionConfig {
|
||||
@Value("${com.baeldung.csfle.auto-decryption:false}")
|
||||
private Boolean autoDecryption;
|
||||
|
||||
private ClientEncryption encryption;
|
||||
|
||||
private BsonBinary dataKeyId;
|
||||
|
||||
public void setEncryption(ClientEncryption encryption) {
|
||||
this.encryption = encryption;
|
||||
}
|
||||
|
||||
public ClientEncryption getEncryption() {
|
||||
return encryption;
|
||||
}
|
||||
|
||||
public void setDataKeyId(BsonBinary dataKeyId) {
|
||||
this.dataKeyId = dataKeyId;
|
||||
}
|
||||
|
||||
+18
-17
@@ -11,12 +11,12 @@ import org.bson.Document;
|
||||
import org.bson.conversions.Bson;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
|
||||
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
|
||||
|
||||
import com.baeldung.boot.csfle.config.converter.IntegerConverter;
|
||||
import com.baeldung.boot.csfle.config.converter.StringConverter;
|
||||
import com.baeldung.boot.csfle.config.converter.BinaryConverter;
|
||||
import com.mongodb.AutoEncryptionSettings;
|
||||
import com.mongodb.ClientEncryptionSettings;
|
||||
import com.mongodb.ConnectionString;
|
||||
@@ -52,16 +52,17 @@ public class MongoClientConfig extends AbstractMongoClientConfiguration {
|
||||
|
||||
@Override
|
||||
public MongoCustomConversions customConversions() {
|
||||
return new MongoCustomConversions(Arrays.asList(new StringConverter(encryptionConfig), new IntegerConverter(encryptionConfig)));
|
||||
return new MongoCustomConversions(Arrays.asList(new BinaryConverter()));
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Override
|
||||
public MongoClient mongoClient() {
|
||||
MongoClient client;
|
||||
try {
|
||||
client = MongoClients.create(clientSettings());
|
||||
|
||||
ClientEncryption encryption = createClientEncryption();
|
||||
ClientEncryption encryption = clientEncryption();
|
||||
encryptionConfig.setDataKeyId(createOrRetrieveDataKey(client, encryption));
|
||||
|
||||
return client;
|
||||
@@ -70,6 +71,19 @@ public class MongoClientConfig extends AbstractMongoClientConfiguration {
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ClientEncryption clientEncryption() throws FileNotFoundException, IOException {
|
||||
Map<String, Map<String, Object>> kmsProviders = LocalKmsUtils.providersMap(encryptionConfig.getMasterKeyPath());
|
||||
|
||||
ClientEncryptionSettings encryptionSettings = ClientEncryptionSettings.builder()
|
||||
.keyVaultMongoClientSettings(clientSettings())
|
||||
.keyVaultNamespace(encryptionConfig.getKeyVaultNamespace())
|
||||
.kmsProviders(kmsProviders)
|
||||
.build();
|
||||
|
||||
return ClientEncryptions.create(encryptionSettings);
|
||||
}
|
||||
|
||||
private BsonBinary createOrRetrieveDataKey(MongoClient client, ClientEncryption encryption) {
|
||||
MongoNamespace namespace = new MongoNamespace(encryptionConfig.getKeyVaultNamespace());
|
||||
MongoCollection<Document> keyVault = client.getDatabase(namespace.getDatabaseName())
|
||||
@@ -92,19 +106,6 @@ public class MongoClientConfig extends AbstractMongoClientConfiguration {
|
||||
}
|
||||
}
|
||||
|
||||
private ClientEncryption createClientEncryption() throws FileNotFoundException, IOException {
|
||||
Map<String, Map<String, Object>> kmsProviders = LocalKmsUtils.providersMap(encryptionConfig.getMasterKeyPath());
|
||||
|
||||
ClientEncryptionSettings encryptionSettings = ClientEncryptionSettings.builder()
|
||||
.keyVaultMongoClientSettings(clientSettings())
|
||||
.keyVaultNamespace(encryptionConfig.getKeyVaultNamespace())
|
||||
.kmsProviders(kmsProviders)
|
||||
.build();
|
||||
|
||||
encryptionConfig.setEncryption(ClientEncryptions.create(encryptionSettings));
|
||||
return encryptionConfig.getEncryption();
|
||||
}
|
||||
|
||||
private MongoClientSettings clientSettings() throws FileNotFoundException, IOException {
|
||||
Builder settings = MongoClientSettings.builder()
|
||||
.applyConnectionString(new ConnectionString(uri));
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.boot.csfle.config.converter;
|
||||
|
||||
import org.bson.BsonBinary;
|
||||
import org.bson.types.Binary;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
|
||||
public class BinaryConverter implements Converter<Binary, BsonBinary> {
|
||||
|
||||
@Override
|
||||
public BsonBinary convert(Binary source) {
|
||||
return new BsonBinary(source.getType(), source.getData());
|
||||
}
|
||||
}
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.boot.csfle.config.converter;
|
||||
|
||||
import org.bson.BsonBinary;
|
||||
import org.bson.BsonValue;
|
||||
import org.bson.types.Binary;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
|
||||
import com.baeldung.boot.csfle.config.EncryptionConfig;
|
||||
|
||||
public class IntegerConverter implements Converter<Binary, Integer> {
|
||||
|
||||
private EncryptionConfig encryptionConfig;
|
||||
|
||||
public IntegerConverter(EncryptionConfig config) {
|
||||
this.encryptionConfig = config;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer convert(Binary source) {
|
||||
BsonBinary bin = new BsonBinary(source.getType(), source.getData());
|
||||
BsonValue value = encryptionConfig.getEncryption()
|
||||
.decrypt(bin);
|
||||
|
||||
return value.asInt32()
|
||||
.getValue();
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user