Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-14776
This commit is contained in:
@@ -1,3 +0,0 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables)
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package org.baeldung.java.collections;
|
||||
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Spliterator;
|
||||
import java.util.Spliterators;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.apache.commons.collections4.IterableUtils;
|
||||
import org.apache.commons.collections4.IteratorUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class IterableToCollectionUnitTest {
|
||||
|
||||
Iterable<String> iterable = Arrays.asList("john", "tom", "jane");
|
||||
Iterator<String> iterator = iterable.iterator();
|
||||
|
||||
@Test
|
||||
public void whenConvertIterableToListUsingJava_thenSuccess() {
|
||||
List<String> result = new ArrayList<String>();
|
||||
for (String str : iterable) {
|
||||
result.add(str);
|
||||
}
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIterableToListUsingJava8_thenSuccess() {
|
||||
List<String> result = new ArrayList<String>();
|
||||
iterable.forEach(result::add);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIterableToListUsingJava8WithSpliterator_thenSuccess() {
|
||||
List<String> result = StreamSupport.stream(iterable.spliterator(), false)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIterableToListUsingGuava_thenSuccess() {
|
||||
List<String> result = Lists.newArrayList(iterable);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIterableToImmutableListUsingGuava_thenSuccess() {
|
||||
List<String> result = ImmutableList.copyOf(iterable);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIterableToListUsingApacheCommons_thenSuccess() {
|
||||
List<String> result = IterableUtils.toList(iterable);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
// ======================== Iterator
|
||||
|
||||
@Test
|
||||
public void whenConvertIteratorToListUsingJava_thenSuccess() {
|
||||
List<String> result = new ArrayList<String>();
|
||||
while (iterator.hasNext()) {
|
||||
result.add(iterator.next());
|
||||
}
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIteratorToListUsingJava8_thenSuccess() {
|
||||
List<String> result = new ArrayList<String>();
|
||||
iterator.forEachRemaining(result::add);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIteratorToListUsingJava8WithSpliterator_thenSuccess() {
|
||||
List<String> result = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIteratorToListUsingGuava_thenSuccess() {
|
||||
List<String> result = Lists.newArrayList(iterator);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIteratorToImmutableListUsingGuava_thenSuccess() {
|
||||
List<String> result = ImmutableList.copyOf(iterator);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertIteratorToListUsingApacheCommons_thenSuccess() {
|
||||
List<String> result = IteratorUtils.toList(iterator);
|
||||
|
||||
assertThat(result, contains("john", "tom", "jane"));
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,17 @@
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>${spring-boot-starter.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.openhft</groupId>
|
||||
<artifactId>chronicle-map</artifactId>
|
||||
<version>${chronicle.map.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>com.sun.java</groupId>
|
||||
<artifactId>tools</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- Dependencies for response decoder with okhttp -->
|
||||
<dependency>
|
||||
@@ -95,6 +106,7 @@
|
||||
<classgraph.version>4.8.28</classgraph.version>
|
||||
<jbpm.version>6.0.0.Final</jbpm.version>
|
||||
<picocli.version>3.9.6</picocli.version>
|
||||
<chronicle.map.version>3.17.2</chronicle.map.version>
|
||||
<crawler4j.version>4.4.0</crawler4j.version>
|
||||
<spring-boot-starter.version>2.1.4.RELEASE</spring-boot-starter.version>
|
||||
</properties>
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.baeldung.chroniclemap;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import net.openhft.chronicle.core.values.LongValue;
|
||||
import net.openhft.chronicle.map.ChronicleMap;
|
||||
import net.openhft.chronicle.map.ExternalMapQueryContext;
|
||||
import net.openhft.chronicle.map.MapEntry;
|
||||
import net.openhft.chronicle.values.Values;
|
||||
|
||||
public class ChronicleMapUnitTest {
|
||||
|
||||
static ChronicleMap<LongValue, CharSequence> persistedCountryMap = null;
|
||||
|
||||
static ChronicleMap<LongValue, CharSequence> inMemoryCountryMap = null;
|
||||
|
||||
static ChronicleMap<Integer, Set<Integer>> multiMap = null;
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@BeforeClass
|
||||
public static void init() {
|
||||
try {
|
||||
inMemoryCountryMap = ChronicleMap.of(LongValue.class, CharSequence.class)
|
||||
.name("country-map")
|
||||
.entries(50)
|
||||
.averageValue("America")
|
||||
.create();
|
||||
|
||||
persistedCountryMap = ChronicleMap.of(LongValue.class, CharSequence.class)
|
||||
.name("country-map")
|
||||
.entries(50)
|
||||
.averageValue("America")
|
||||
.createPersistedTo(new File(System.getProperty("user.home") + "/country-details.dat"));
|
||||
|
||||
Set<Integer> averageValue = IntStream.of(1, 2)
|
||||
.boxed()
|
||||
.collect(Collectors.toSet());
|
||||
multiMap = ChronicleMap.of(Integer.class, (Class<Set<Integer>>) (Class) Set.class)
|
||||
.name("multi-map")
|
||||
.entries(50)
|
||||
.averageValue(averageValue)
|
||||
.create();
|
||||
|
||||
LongValue qatarKey = Values.newHeapInstance(LongValue.class);
|
||||
qatarKey.setValue(1);
|
||||
inMemoryCountryMap.put(qatarKey, "Qatar");
|
||||
|
||||
LongValue key = Values.newHeapInstance(LongValue.class);
|
||||
key.setValue(1);
|
||||
persistedCountryMap.put(key, "Romania");
|
||||
key.setValue(2);
|
||||
persistedCountryMap.put(key, "India");
|
||||
|
||||
Set<Integer> set1 = new HashSet<>();
|
||||
set1.add(1);
|
||||
set1.add(2);
|
||||
multiMap.put(1, set1);
|
||||
|
||||
Set<Integer> set2 = new HashSet<>();
|
||||
set2.add(3);
|
||||
multiMap.put(2, set2);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGetQuery_whenCalled_shouldReturnResult() {
|
||||
LongValue key = Values.newHeapInstance(LongValue.class);
|
||||
key.setValue(1);
|
||||
CharSequence country = inMemoryCountryMap.get(key);
|
||||
assertThat(country.toString(), is(equalTo("Qatar")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGetUsingQuery_whenCalled_shouldReturnResult() {
|
||||
LongValue key = Values.newHeapInstance(LongValue.class);
|
||||
StringBuilder country = new StringBuilder();
|
||||
key.setValue(1);
|
||||
persistedCountryMap.getUsing(key, country);
|
||||
assertThat(country.toString(), is(equalTo("Romania")));
|
||||
key.setValue(2);
|
||||
persistedCountryMap.getUsing(key, country);
|
||||
assertThat(country.toString(), is(equalTo("India")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleKeyQuery_whenProcessed_shouldChangeTheValue() {
|
||||
try (ExternalMapQueryContext<Integer, Set<Integer>, ?> fistContext = multiMap.queryContext(1)) {
|
||||
try (ExternalMapQueryContext<Integer, Set<Integer>, ?> secondContext = multiMap.queryContext(2)) {
|
||||
fistContext.updateLock()
|
||||
.lock();
|
||||
secondContext.updateLock()
|
||||
.lock();
|
||||
MapEntry<Integer, Set<Integer>> firstEntry = fistContext.entry();
|
||||
Set<Integer> firstSet = firstEntry.value()
|
||||
.get();
|
||||
firstSet.remove(2);
|
||||
MapEntry<Integer, Set<Integer>> secondEntry = secondContext.entry();
|
||||
Set<Integer> secondSet = secondEntry.value()
|
||||
.get();
|
||||
secondSet.add(4);
|
||||
firstEntry.doReplaceValue(fistContext.wrapValueAsData(firstSet));
|
||||
secondEntry.doReplaceValue(secondContext.wrapValueAsData(secondSet));
|
||||
}
|
||||
} finally {
|
||||
assertThat(multiMap.get(1)
|
||||
.size(), is(equalTo(1)));
|
||||
assertThat(multiMap.get(2)
|
||||
.size(), is(equalTo(2)));
|
||||
}
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void finish() {
|
||||
persistedCountryMap.close();
|
||||
inMemoryCountryMap.close();
|
||||
multiMap.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
HELP.md
|
||||
/target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
/build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
@@ -0,0 +1,31 @@
|
||||
<?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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>elasticsearch</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>elasticsearch</name>
|
||||
<description>Demo project for Java Elasticsearch libraries</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.searchbox</groupId>
|
||||
<artifactId>jest</artifactId>
|
||||
<version>6.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.9.6</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.jest;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Employee {
|
||||
String name;
|
||||
String title;
|
||||
List<String> skills;
|
||||
int yearsOfService;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public List<String> getSkills() {
|
||||
return skills;
|
||||
}
|
||||
|
||||
public void setSkills(List<String> skills) {
|
||||
this.skills = skills;
|
||||
}
|
||||
|
||||
public int getYearsOfService() {
|
||||
return yearsOfService;
|
||||
}
|
||||
|
||||
public void setYearsOfService(int yearsOfService) {
|
||||
this.yearsOfService = yearsOfService;
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
package com.baeldung.jest;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.searchbox.client.JestClient;
|
||||
import io.searchbox.client.JestClientFactory;
|
||||
import io.searchbox.client.JestResult;
|
||||
import io.searchbox.client.JestResultHandler;
|
||||
import io.searchbox.client.config.HttpClientConfig;
|
||||
import io.searchbox.core.*;
|
||||
import io.searchbox.indices.CreateIndex;
|
||||
import io.searchbox.indices.IndicesExists;
|
||||
import io.searchbox.indices.aliases.AddAliasMapping;
|
||||
import io.searchbox.indices.aliases.ModifyAliases;
|
||||
import io.searchbox.indices.aliases.RemoveAliasMapping;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
public class JestDemoApplication {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
|
||||
// Demo the JestClient
|
||||
JestClient jestClient = jestClient();
|
||||
|
||||
// Check an index
|
||||
JestResult result = jestClient.execute(new IndicesExists.Builder("employees").build());
|
||||
if(!result.isSucceeded()) {
|
||||
System.out.println(result.getErrorMessage());
|
||||
}
|
||||
|
||||
// Create an index
|
||||
jestClient.execute(new CreateIndex.Builder("employees").build());
|
||||
|
||||
// Create an index with options
|
||||
Map<String, Object> settings = new HashMap<>();
|
||||
settings.put("number_of_shards", 11);
|
||||
settings.put("number_of_replicas", 2);
|
||||
jestClient.execute(new CreateIndex.Builder("employees").settings(settings).build());
|
||||
|
||||
// Create an alias, then remove it
|
||||
jestClient.execute(new ModifyAliases.Builder(
|
||||
new AddAliasMapping.Builder(
|
||||
"employees",
|
||||
"e")
|
||||
.build())
|
||||
.build());
|
||||
JestResult jestResult = jestClient.execute(new ModifyAliases.Builder(
|
||||
new RemoveAliasMapping.Builder(
|
||||
"employees",
|
||||
"e")
|
||||
.build())
|
||||
.build());
|
||||
|
||||
if(jestResult.isSucceeded()) {
|
||||
System.out.println("Success!");
|
||||
}
|
||||
else {
|
||||
System.out.println(jestResult.getErrorMessage());
|
||||
}
|
||||
|
||||
// Sample JSON for indexing
|
||||
|
||||
// {
|
||||
// "name": "Michael Pratt",
|
||||
// "title": "Java Developer",
|
||||
// "skills": ["java", "spring", "elasticsearch"],
|
||||
// "yearsOfService": 2
|
||||
// }
|
||||
|
||||
// Index a document from String
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
JsonNode employeeJsonNode = mapper.createObjectNode()
|
||||
.put("name", "Michael Pratt")
|
||||
.put("title", "Java Developer")
|
||||
.put("yearsOfService", 2)
|
||||
.set("skills", mapper.createArrayNode()
|
||||
.add("java")
|
||||
.add("spring")
|
||||
.add("elasticsearch"));
|
||||
jestClient.execute(new Index.Builder(employeeJsonNode.toString()).index("employees").build());
|
||||
|
||||
// Index a document from Map
|
||||
Map<String, Object> employeeHashMap = new LinkedHashMap<>();
|
||||
employeeHashMap.put("name", "Michael Pratt");
|
||||
employeeHashMap.put("title", "Java Developer");
|
||||
employeeHashMap.put("yearsOfService", 2);
|
||||
employeeHashMap.put("skills", Arrays.asList("java", "spring", "elasticsearch"));
|
||||
jestClient.execute(new Index.Builder(employeeHashMap).index("employees").build());
|
||||
|
||||
// Index a document from POJO
|
||||
Employee employee = new Employee();
|
||||
employee.setName("Michael Pratt");
|
||||
employee.setTitle("Java Developer");
|
||||
employee.setYearsOfService(2);
|
||||
employee.setSkills(Arrays.asList("java", "spring", "elasticsearch"));
|
||||
jestClient.execute(new Index.Builder(employee).index("employees").build());
|
||||
|
||||
// Read document by ID
|
||||
Employee getResult = jestClient.execute(new Get.Builder("employees", "1").build()).getSourceAsObject(Employee.class);
|
||||
|
||||
// Search documents
|
||||
String search = "{\n" +
|
||||
" \"query\": {\n" +
|
||||
" \"bool\": {\n" +
|
||||
" \"must\": [\n" +
|
||||
" { \"match\": { \"name\": \"Michael Pratt\" }}\n" +
|
||||
" ]\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
List<SearchResult.Hit<Employee, Void>> searchResults =
|
||||
jestClient.execute(new Search.Builder(search).build())
|
||||
.getHits(Employee.class);
|
||||
|
||||
searchResults.forEach(hit -> {
|
||||
System.out.println(String.format("Document %s has score %s", hit.id, hit.score));
|
||||
});
|
||||
|
||||
// Update document
|
||||
employee.setYearsOfService(3);
|
||||
jestClient.execute(new Update.Builder(employee).index("employees").id("1").build());
|
||||
|
||||
// Delete documents
|
||||
jestClient.execute(new Delete.Builder("2") .index("employees") .build());
|
||||
|
||||
// Bulk operations
|
||||
Employee employeeObject1 = new Employee();
|
||||
employee.setName("John Smith");
|
||||
employee.setTitle("Python Developer");
|
||||
employee.setYearsOfService(10);
|
||||
employee.setSkills(Arrays.asList("python"));
|
||||
|
||||
Employee employeeObject2 = new Employee();
|
||||
employee.setName("Kate Smith");
|
||||
employee.setTitle("Senior JavaScript Developer");
|
||||
employee.setYearsOfService(10);
|
||||
employee.setSkills(Arrays.asList("javascript", "angular"));
|
||||
|
||||
jestClient.execute(new Bulk.Builder().defaultIndex("employees")
|
||||
.addAction(new Index.Builder(employeeObject1).build())
|
||||
.addAction(new Index.Builder(employeeObject2).build())
|
||||
.addAction(new Delete.Builder("3").build()) .build());
|
||||
|
||||
// Async operations
|
||||
Employee employeeObject3 = new Employee();
|
||||
employee.setName("Jane Doe");
|
||||
employee.setTitle("Manager");
|
||||
employee.setYearsOfService(20);
|
||||
employee.setSkills(Arrays.asList("managing"));
|
||||
|
||||
jestClient.executeAsync( new Index.Builder(employeeObject3).build(), new JestResultHandler<JestResult>() {
|
||||
@Override public void completed(JestResult result) {
|
||||
// handle result
|
||||
}
|
||||
@Override public void failed(Exception ex) {
|
||||
// handle exception
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static JestClient jestClient()
|
||||
{
|
||||
JestClientFactory factory = new JestClientFactory();
|
||||
factory.setHttpClientConfig(
|
||||
new HttpClientConfig.Builder("http://localhost:9200")
|
||||
.multiThreaded(true)
|
||||
.defaultMaxTotalConnectionPerRoute(2)
|
||||
.maxTotalConnection(20)
|
||||
.build());
|
||||
return factory.getObject();
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
<module>apache-cayenne</module>
|
||||
<module>core-java-persistence</module>
|
||||
<module>deltaspike</module>
|
||||
<module>elasticsearch</module>
|
||||
<module>flyway</module>
|
||||
<module>hbase</module>
|
||||
<module>hibernate5</module>
|
||||
|
||||
@@ -46,6 +46,13 @@
|
||||
<artifactId>reactor-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.cassandraunit</groupId>
|
||||
<artifactId>cassandra-unit-spring</artifactId>
|
||||
<version>${cassandra-unit-spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
@@ -53,6 +60,7 @@
|
||||
<project.reporting.outputEncoding>UTF-8
|
||||
</project.reporting.outputEncoding>
|
||||
<spring-data-cassandra.version>2.1.2.RELEASE</spring-data-cassandra.version>
|
||||
<cassandra-unit-spring.version>3.11.2.0</cassandra-unit-spring.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+21
-2
@@ -1,13 +1,23 @@
|
||||
package com.baeldung.cassandra.reactive;
|
||||
|
||||
import com.baeldung.cassandra.reactive.model.Employee;
|
||||
import com.baeldung.cassandra.reactive.repository.EmployeeRepository;
|
||||
import org.cassandraunit.spring.CassandraDataSet;
|
||||
import org.cassandraunit.spring.CassandraUnitDependencyInjectionTestExecutionListener;
|
||||
import org.cassandraunit.spring.CassandraUnitTestExecutionListener;
|
||||
import org.cassandraunit.spring.EmbeddedCassandra;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.TestExecutionListeners;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
|
||||
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
|
||||
import org.springframework.test.context.web.ServletTestExecutionListener;
|
||||
|
||||
import com.baeldung.cassandra.reactive.model.Employee;
|
||||
import com.baeldung.cassandra.reactive.repository.EmployeeRepository;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
@@ -15,6 +25,15 @@ import reactor.test.StepVerifier;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@TestExecutionListeners(listeners = {
|
||||
CassandraUnitDependencyInjectionTestExecutionListener.class,
|
||||
CassandraUnitTestExecutionListener.class,
|
||||
ServletTestExecutionListener.class,
|
||||
DependencyInjectionTestExecutionListener.class,
|
||||
DirtiesContextTestExecutionListener.class
|
||||
})
|
||||
@EmbeddedCassandra(timeout = 60000, configuration = "cassandra-server.yaml")
|
||||
@CassandraDataSet(value = {"cassandra-init.cql"}, keyspace = "practice")
|
||||
public class ReactiveEmployeeRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE employee(
|
||||
id int PRIMARY KEY,
|
||||
name text,
|
||||
address text,
|
||||
email text,
|
||||
age int
|
||||
);
|
||||
+590
File diff suppressed because it is too large
Load Diff
+5
-1
@@ -1,10 +1,13 @@
|
||||
package com.baeldung.reactive.errorhandling;
|
||||
|
||||
import java.io.IOException;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.http.MediaType;
|
||||
@@ -15,6 +18,7 @@ import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
|
||||
@WithMockUser
|
||||
@AutoConfigureWebTestClient(timeout = "10000")
|
||||
public class ErrorHandlingIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
|
||||
+2
@@ -3,6 +3,7 @@ package com.baeldung.reactive.filters;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
@@ -14,6 +15,7 @@ import static org.junit.Assert.assertEquals;
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
@WithMockUser
|
||||
@AutoConfigureWebTestClient(timeout = "10000")
|
||||
public class PlayerHandlerIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ public class PostExecutionUnitTest {
|
||||
.expectComplete()
|
||||
.verifyThenAssertThat()
|
||||
.hasDropped(4)
|
||||
.tookLessThan(Duration.ofMillis(1050));
|
||||
.tookLessThan(Duration.ofMillis(1500));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@@ -9,6 +10,7 @@ import com.baeldung.activitiwithspring.ActivitiWithSpringApplication;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = ActivitiWithSpringApplication.class)
|
||||
@AutoConfigureTestDatabase
|
||||
public class SpringContextIntegrationTest {
|
||||
|
||||
@Test
|
||||
|
||||
+2
@@ -4,6 +4,7 @@ import org.activiti.engine.IdentityService;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
@@ -14,6 +15,7 @@ import com.baeldung.activiti.security.withspring.ActivitiSpringSecurityApplicati
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = ActivitiSpringSecurityApplication.class)
|
||||
@WebAppConfiguration
|
||||
@AutoConfigureTestDatabase
|
||||
public class ActivitiSpringSecurityIntegrationTest {
|
||||
@Autowired
|
||||
private IdentityService identityService;
|
||||
|
||||
+3
-1
@@ -2,11 +2,13 @@ package com.baeldung.activitiwithspring;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@SpringBootTest(classes = ActivitiWithSpringApplication.class)
|
||||
@AutoConfigureTestDatabase
|
||||
public class ActivitiWithSpringApplicationIntegrationTest {
|
||||
|
||||
@Test
|
||||
|
||||
+6
-1
@@ -4,7 +4,7 @@ import org.activiti.engine.ProcessEngine;
|
||||
import org.activiti.engine.ProcessEngineConfiguration;
|
||||
import org.activiti.engine.ProcessEngines;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.junit.After;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
@@ -62,4 +62,9 @@ public class ProcessEngineCreationIntegrationTest {
|
||||
assertNotNull(processEngine);
|
||||
assertEquals("sa", processEngine.getProcessEngineConfiguration().getJdbcUsername());
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
ProcessEngines.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,6 +56,12 @@
|
||||
<artifactId>spring-boot-test</artifactId>
|
||||
<version>${mockito.spring.boot.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
@@ -85,6 +91,7 @@
|
||||
<commons.io.version>2.5</commons.io.version>
|
||||
<spring-boot.version>1.5.2.RELEASE</spring-boot.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<assertj.version>3.12.2</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -1,19 +1,21 @@
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
|
||||
https://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<bean id="toyota" class="com.baeldung.constructordi.domain.Car">
|
||||
<constructor-arg index="0" ref="engine" />
|
||||
<constructor-arg index="1" ref="transmission" />
|
||||
</bean>
|
||||
|
||||
<bean id="engine" class="com.baeldung.constructordi.domain.Engine">
|
||||
<bean id="engine"
|
||||
class="com.baeldung.constructordi.domain.Engine">
|
||||
<constructor-arg index="0" value="v4" />
|
||||
<constructor-arg index="1" value="2" />
|
||||
</bean>
|
||||
|
||||
<bean id="transmission" class="com.baeldung.constructordi.domain.Transmission">
|
||||
<bean id="transmission"
|
||||
class="com.baeldung.constructordi.domain.Transmission">
|
||||
<constructor-arg value="sliding" />
|
||||
</bean>
|
||||
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.constructordi;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
import com.baeldung.constructordi.domain.Car;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = Config.class)
|
||||
public class ConstructorDependencyInjectionIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenPrototypeInjection_WhenObjectFactory_ThenNewInstanceReturn() {
|
||||
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
|
||||
Car firstContextCar = context.getBean(Car.class);
|
||||
|
||||
ApplicationContext xmlContext = new ClassPathXmlApplicationContext("constructordi.xml");
|
||||
Car secondContextCar = xmlContext.getBean(Car.class);
|
||||
|
||||
assertThat(firstContextCar).isNotSameAs(secondContextCar);
|
||||
assertThat(firstContextCar).hasToString("Engine: v8 5 Transmission: sliding");
|
||||
assertThat(secondContextCar).hasToString("Engine: v4 2 Transmission: sliding");
|
||||
}
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package org.baeldung.config.child;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.access.intercept.RunAsImplAuthenticationProvider;
|
||||
import org.springframework.security.access.intercept.RunAsManager;
|
||||
import org.springframework.security.access.intercept.RunAsManagerImpl;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
|
||||
|
||||
|
||||
@Configuration
|
||||
@EnableGlobalMethodSecurity(securedEnabled = true)
|
||||
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
|
||||
|
||||
@Override
|
||||
protected RunAsManager runAsManager() {
|
||||
RunAsManagerImpl runAsManager = new RunAsManagerImpl();
|
||||
runAsManager.setKey("MyRunAsKey");
|
||||
return runAsManager;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.authenticationProvider(runAsAuthenticationProvider());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationProvider runAsAuthenticationProvider() {
|
||||
RunAsImplAuthenticationProvider authProvider = new RunAsImplAuthenticationProvider();
|
||||
authProvider.setKey("MyRunAsKey");
|
||||
return authProvider;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package org.baeldung.service;
|
||||
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class RunAsService {
|
||||
|
||||
@Secured({ "ROLE_RUN_AS_REPORTER" })
|
||||
public Authentication getCurrentUser() {
|
||||
Authentication authentication =
|
||||
SecurityContextHolder.getContext().getAuthentication();
|
||||
return authentication;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package org.baeldung.web.controller;
|
||||
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/runas")
|
||||
public class RunAsController {
|
||||
|
||||
@Secured({ "ROLE_USER", "RUN_AS_REPORTER" })
|
||||
@RequestMapping
|
||||
@ResponseBody
|
||||
public String tryRunAs() {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
return "Current User Authorities inside this RunAS method only " +
|
||||
auth.getAuthorities().toString();
|
||||
}
|
||||
}
|
||||
+5
@@ -10,4 +10,9 @@ public class ViewController {
|
||||
public String index() {
|
||||
return "index";
|
||||
}
|
||||
|
||||
@RequestMapping({ "/runashome" })
|
||||
public String run() {
|
||||
return "runas";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns:th="https://www.thymeleaf.org"
|
||||
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
|
||||
<body>
|
||||
Current user authorities:
|
||||
<span sec:authentication="principal.authorities">user</span>
|
||||
<br />
|
||||
<span id="temp"></span>
|
||||
<a href="#" onclick="tryRunAs()">Generate Report As Super User</a>
|
||||
|
||||
<script
|
||||
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
|
||||
<script type="text/javascript">
|
||||
|
||||
function tryRunAs(){
|
||||
var context = window.location.pathname.substring(0, window.location.pathname.indexOf("/", 2));
|
||||
$.get( context + "/runas" , function( data ) {
|
||||
$("#temp").html(data);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,32 @@
|
||||
<?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>junit-5-advanced</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>junit-5-advanced</name>
|
||||
<description>Advanced JUnit 5 Topics</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<junit-jupiter.version>5.4.2</junit-jupiter.version>
|
||||
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package com.baeldung.displayname;
|
||||
|
||||
import org.junit.jupiter.api.DisplayNameGeneration;
|
||||
import org.junit.jupiter.api.DisplayNameGenerator;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
@DisplayNameGeneration(DisplayNameGeneratorUnitTest.ReplaceCamelCase.class)
|
||||
class DisplayNameGeneratorUnitTest {
|
||||
|
||||
@Test
|
||||
void camelCaseName() {
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayNameGeneration(DisplayNameGeneratorUnitTest.IndicativeSentences.class)
|
||||
class ANumberIsFizz {
|
||||
@Test
|
||||
void ifItIsDivisibleByThree() {
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "Number {0} is fizz.")
|
||||
@ValueSource(ints = { 3, 12, 18 })
|
||||
void ifItIsOneOfTheFollowingNumbers(int number) {
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayNameGeneration(DisplayNameGeneratorUnitTest.IndicativeSentences.class)
|
||||
class ANumberIsBuzz {
|
||||
@Test
|
||||
void ifItIsDivisibleByFive() {
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "Number {0} is buzz.")
|
||||
@ValueSource(ints = { 5, 10, 20 })
|
||||
void ifItIsOneOfTheFollowingNumbers(int number) {
|
||||
}
|
||||
}
|
||||
|
||||
static class IndicativeSentences extends ReplaceCamelCase {
|
||||
@Override
|
||||
public String generateDisplayNameForNestedClass(Class<?> nestedClass) {
|
||||
return super.generateDisplayNameForNestedClass(nestedClass) + "...";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generateDisplayNameForMethod(Class<?> testClass, Method testMethod) {
|
||||
return replaceCamelCase(testClass.getSimpleName() + " " + testMethod.getName()) + ".";
|
||||
}
|
||||
}
|
||||
|
||||
static class ReplaceCamelCase extends DisplayNameGenerator.Standard {
|
||||
@Override
|
||||
public String generateDisplayNameForClass(Class<?> testClass) {
|
||||
return replaceCamelCase(super.generateDisplayNameForClass(testClass));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generateDisplayNameForNestedClass(Class<?> nestedClass) {
|
||||
return replaceCamelCase(super.generateDisplayNameForNestedClass(nestedClass));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generateDisplayNameForMethod(Class<?> testClass, Method testMethod) {
|
||||
return this.replaceCamelCase(testMethod.getName()) + DisplayNameGenerator.parameterTypesAsString(testMethod);
|
||||
}
|
||||
|
||||
String replaceCamelCase(String camelCase) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
result.append(camelCase.charAt(0));
|
||||
for (int i=1; i<camelCase.length(); i++) {
|
||||
if (Character.isUpperCase(camelCase.charAt(i))) {
|
||||
result.append(' ');
|
||||
result.append(Character.toLowerCase(camelCase.charAt(i)));
|
||||
} else {
|
||||
result.append(camelCase.charAt(i));
|
||||
}
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user