Merge branch 'master' into BAEL_679_reactive_streams

This commit is contained in:
Grzegorz Piwowarek
2017-03-24 21:05:36 +01:00
committed by GitHub
75 changed files with 1526 additions and 1074 deletions
+2 -1
View File
@@ -1,6 +1,6 @@
language: java
install: travis_wait 60 mvn -q clean install
install: travis_wait 60 mvn -q test
before_script:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -XX:-UseGCOverheadLimit'" > ~/.mavenrc
@@ -17,4 +17,5 @@ cache:
directories:
- .autoconf
- $HOME/.m2
Binary file not shown.
-1
View File
@@ -198,7 +198,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
@@ -0,0 +1,61 @@
package com.baeldung.arraycopy.model;
public class Address implements Cloneable {
private String country;
private String state;
private String city;
private String street;
private String zipcode;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
@Override
protected Object clone() throws CloneNotSupportedException {
super.clone();
Address address = new Address();
address.setCity(this.city);
address.setCountry(this.country);
address.setState(this.state);
address.setStreet(this.street);
address.setZipcode(this.zipcode);
return address;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.arraycopy.model;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = -2454619097207585825L;
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,163 @@
package com.baeldung.arraycopy;
import com.baeldung.arraycopy.model.Address;
import com.baeldung.arraycopy.model.Employee;
import org.apache.commons.lang3.SerializationUtils;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
public class ArrayCopyUtilTest {
private static Employee[] employees;
private static final int MAX = 2;
@BeforeClass
public static void setup(){
employees = new Employee[MAX];
Employee employee;
for(int i = 0; i < MAX; i++) {
employee = new Employee();
employee.setName("Emp"+i);
employee.setId(i);
employees[i] = employee;
}
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaSystemsArrayCopy_thenSuccessful(){
int[] array = {23, 43, 55};
int[] copiedArray = new int[3];
System.arraycopy(array, 0, copiedArray, 0, 3);
Assert.assertTrue(array.length == copiedArray.length);
Assert.assertTrue(copiedArray[0] == array[0]);
Assert.assertTrue(copiedArray[1] == array[1]);
Assert.assertTrue(copiedArray[2] == array[2]);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaSystemsArrayCopy_thenSuccessful(){
int[] array = {23, 43, 55, 12, 65, 88, 92};
int[] copiedArray = new int[3];
System.arraycopy(array, 2, copiedArray, 0, 3);
Assert.assertTrue(3 == copiedArray.length);
Assert.assertTrue(copiedArray[0] == array[2]);
Assert.assertTrue(copiedArray[1] == array[3]);
Assert.assertTrue(copiedArray[2] == array[4]);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaArraysCopyOfRange_thenSuccessful(){
int[] array = {23, 43, 55, 12, 65, 88, 92};
int[] copiedArray = Arrays.copyOfRange(array, 1, 4);
Assert.assertTrue(3 == copiedArray.length);
Assert.assertTrue(copiedArray[0] == array[1]);
Assert.assertTrue(copiedArray[1] == array[2]);
Assert.assertTrue(copiedArray[2] == array[3]);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaArraysCopyOf_thenValueChangeIsSuccessful(){
int[] array = {23, 43, 55, 12};
int newLength = array.length;
int[] copiedArray = Arrays.copyOf(array, newLength);
Assert.assertNotNull(copiedArray);
Assert.assertTrue(copiedArray.length == array.length);
Assert.assertTrue(copiedArray[0] == array[0]);
Assert.assertTrue(copiedArray[1] == array[1]);
Assert.assertTrue(copiedArray[2] == array[2]);
Assert.assertTrue(copiedArray[3] == array[3]);
array[0] = 9;
Assert.assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
Assert.assertTrue(copiedArray[1] != array[1]);
}
@Test
public void givenArrayOfNonPrimitiveType_whenCopiedViaArraysCopyOf_thenDoShallowCopy(){
Employee[] copiedArray = Arrays.copyOf(employees, employees.length);
Assert.assertNotNull(copiedArray);
Assert.assertTrue(copiedArray.length == employees.length);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element caused change in the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaArrayClone_thenValueChangeIsSuccessful(){
int[] array = {23, 43, 55, 12};
int[] copiedArray = array.clone();
Assert.assertNotNull(copiedArray);
Assert.assertTrue(copiedArray.length == array.length);
Assert.assertTrue(copiedArray[0] == array[0]);
Assert.assertTrue(copiedArray[1] == array[1]);
Assert.assertTrue(copiedArray[2] == array[2]);
Assert.assertTrue(copiedArray[3] == array[3]);
array[0] = 9;
Assert.assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
Assert.assertTrue(copiedArray[1] != array[1]);
}
@Test
public void givenArraysOfNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){
Employee[] copiedArray = employees.clone();
Assert.assertNotNull(copiedArray);
Assert.assertTrue(copiedArray.length == employees.length);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element changed the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArraysOfCloneableNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){
Address[] addresses = createAddressArray();
Address[] copiedArray = addresses.clone();
Assert.assertNotNull(copiedArray);
Assert.assertTrue(copiedArray.length == addresses.length);
addresses[0].setCity(addresses[0].getCity()+"_Changed");
Assert.assertTrue(copiedArray[0].getCity().equals(addresses[0].getCity()));
}
@Test
public void givenArraysOfSerializableNonPrimitiveType_whenCopiedViaSerializationUtils_thenDoDeepCopy(){
Employee[] copiedArray = SerializationUtils.clone(employees);
Assert.assertNotNull(copiedArray);
Assert.assertTrue(copiedArray.length == employees.length);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element didn't change in the copied array
Assert.assertFalse(copiedArray[0].getName().equals(employees[0].getName()));
}
private Address[] createAddressArray(){
Address[] addresses = new Address[1];
addresses[0] = createAddress();
return addresses;
}
private Address createAddress() {
Address address = new Address();
address.setCountry("USA");
address.setState("CA");
address.setCity("San Francisco");
address.setStreet("Street 1");
address.setZipcode("59999");
return address;
}
}
@@ -12,7 +12,7 @@ import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
public class CountdownLatchExampleTest {
public class CountdownLatchExampleIntegrationTest {
@Test
public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() throws InterruptedException {
// Given
@@ -7,7 +7,7 @@ import java.io.*;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
public class JavaProcessUnitTest {
public class JavaProcessUnitIntegrationTest {
private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
private static class StreamGobbler implements Runnable {
@@ -1,38 +1,38 @@
package org.baeldung.java.streams;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ThreadPoolInParallelStreamTest {
@Test
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException {
long firstNum = 1;
long lastNum = 1_000_000;
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList());
ForkJoinPool customThreadPool = new ForkJoinPool(4);
long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get();
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
}
@Test
public void givenList_whenCallingParallelStream_shouldBeParallelStream() {
List<Long> aList = new ArrayList<>();
Stream<Long> parallelStream = aList.parallelStream();
assertTrue(parallelStream.isParallel());
}
}
package org.baeldung.java.streams;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ThreadPoolInParallelStreamIntegrationTest {
@Test
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException {
long firstNum = 1;
long lastNum = 1_000_000;
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList());
ForkJoinPool customThreadPool = new ForkJoinPool(4);
long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get();
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
}
@Test
public void givenList_whenCallingParallelStream_shouldBeParallelStream() {
List<Long> aList = new ArrayList<>();
Stream<Long> parallelStream = aList.parallelStream();
assertTrue(parallelStream.isParallel());
}
}
@@ -0,0 +1,119 @@
package com.baeldung.jackson.streaming;
import com.fasterxml.jackson.core.*;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static junit.framework.TestCase.assertEquals;
public class JacksonStreamingAPITest {
@Test
public void givenJsonGenerator_whenAppendJsonToIt_thenGenerateJson() throws IOException {
//given
ByteArrayOutputStream stream = new ByteArrayOutputStream();
JsonFactory jfactory = new JsonFactory();
JsonGenerator jGenerator = jfactory.createGenerator(stream, JsonEncoding.UTF8);
//when
jGenerator.writeStartObject();
jGenerator.writeStringField("name", "Tom");
jGenerator.writeNumberField("age", 25);
jGenerator.writeFieldName("address");
jGenerator.writeStartArray();
jGenerator.writeString("Poland");
jGenerator.writeString("5th avenue");
jGenerator.writeEndArray();
jGenerator.writeEndObject();
jGenerator.close();
//then
String json = new String(stream.toByteArray(), "UTF-8");
assertEquals(json, "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}");
}
@Test
public void givenJson_whenReadItUsingStreamAPI_thenShouldCreateProperJsonObject() throws IOException {
//given
String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}";
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createParser(json);
String parsedName = null;
Integer parsedAge = null;
List<String> addresses = new LinkedList<>();
//when
while (jParser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = jParser.getCurrentName();
if ("name".equals(fieldname)) {
jParser.nextToken();
parsedName = jParser.getText();
}
if ("age".equals(fieldname)) {
jParser.nextToken();
parsedAge = jParser.getIntValue();
}
if ("address".equals(fieldname)) {
jParser.nextToken();
while (jParser.nextToken() != JsonToken.END_ARRAY) {
addresses.add(jParser.getText());
}
}
}
jParser.close();
//then
assertEquals(parsedName, "Tom");
assertEquals(parsedAge, (Integer) 25);
assertEquals(addresses, Arrays.asList("Poland", "5th avenue"));
}
@Test
public void givenJson_whenWantToExtractPartOfIt_thenShouldExtractOnlyNeededFieldWithoutGoingThroughWholeJSON() throws IOException {
//given
String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}";
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createParser(json);
String parsedName = null;
Integer parsedAge = null;
List<String> addresses = new LinkedList<>();
//when
while (jParser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = jParser.getCurrentName();
if ("age".equals(fieldname)) {
jParser.nextToken();
parsedAge = jParser.getIntValue();
return;
}
}
jParser.close();
//then
assertNull(parsedName);
assertEquals(parsedAge, (Integer) 25);
assertTrue(addresses.isEmpty());
}
}
-1
View File
@@ -161,7 +161,6 @@
<module>spring-rest-angular</module>
<module>spring-rest-docs</module>
<module>spring-rest</module>
<module>spring-security-basic-auth</module>
<module>spring-security-cache-control</module>
<module>spring-security-client/spring-security-jsp-authentication</module>
<module>spring-security-client/spring-security-jsp-authorize</module>
@@ -1,70 +0,0 @@
package org.baeldung.boot;
import org.baeldung.boot.components.FooService;
import org.baeldung.boot.model.Foo;
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.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.doReturn;
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = DemoApplication.class,
webEnvironment = WebEnvironment.RANDOM_PORT)
public class FooComponentTests {
@Autowired
private TestRestTemplate testRestTemplate;
@SpyBean
private FooService fooService;
@Before
public void init() throws Exception {
Foo foo = new Foo();
foo.setId(5);
foo.setName("MOCKED_FOO");
doReturn(foo).when(fooService).getFooWithId(anyInt());
// doCallRealMethod().when(fooComponent).getFooWithName(anyString());
}
@Test
public void givenInquiryingFooWithId_whenFooComponentIsMocked_thenAssertMockedResult() {
Map<String, String> pathVariables = new HashMap<>();
pathVariables.put("id", "1");
ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/{id}", Foo.class, pathVariables);
assertNotNull(fooResponse);
assertEquals(HttpStatus.OK, fooResponse.getStatusCode());
assertEquals(5, fooResponse.getBody().getId().longValue());
assertEquals("MOCKED_FOO", fooResponse.getBody().getName());
}
@Test
public void givenInquiryingFooWithName_whenFooComponentIsMocked_thenAssertMockedResult() {
Map<String, String> pathVariables = new HashMap<>();
pathVariables.put("name", "Foo_Name");
ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/?name={name}", Foo.class, pathVariables);
assertNotNull(fooResponse);
assertEquals(HttpStatus.OK, fooResponse.getStatusCode());
assertEquals(1, fooResponse.getBody().getId().longValue());
}
}
@@ -1,43 +0,0 @@
package org.baeldung.boot;
import java.util.HashMap;
import java.util.Map;
import org.baeldung.boot.DemoApplication;
import org.baeldung.boot.model.Foo;
import org.junit.Assert;
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.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes=DemoApplication.class,webEnvironment = WebEnvironment.RANDOM_PORT)
public class FooIntegrationTest {
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void givenInquiryingFooWithId_whenIdIsValid_thenHttpStatusOK(){
Map<String,String> pathVariables = new HashMap<String,String>();
pathVariables.put("id", "1");
ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/{id}", Foo.class, pathVariables);
Assert.assertNotNull(fooResponse);
Assert.assertEquals(HttpStatus.OK,fooResponse.getStatusCode());
}
@Test
public void givenInquiryingFooWithName_whenNameIsValid_thenHttpStatusOK(){
Map<String,String> pathVariables = new HashMap<String,String>();
pathVariables.put("name", "Foo_Name");
ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/?name={name}", Foo.class, pathVariables);
Assert.assertNotNull(fooResponse);
Assert.assertEquals(HttpStatus.OK,fooResponse.getStatusCode());
}
}
@@ -1,34 +0,0 @@
package org.baeldung.boot;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.baeldung.boot.model.Foo;
import org.baeldung.boot.repository.FooRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@DataJpaTest
public class FooJPATest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private FooRepository repository;
@Test
public void findFooByName() {
this.entityManager.persist(new Foo("Foo_Name_2"));
Foo foo = this.repository.findByName("Foo_Name_2");
assertNotNull(foo);
assertEquals("Foo_Name_2",foo.getName());
// Due to having Insert query for Foo with Id 1, so TestEntityManager generates new Id of 2
assertEquals(2l,foo.getId().longValue());
}
}
@@ -1,35 +0,0 @@
package org.baeldung.boot;
import static org.assertj.core.api.Assertions.assertThat;
import org.baeldung.boot.model.Foo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@JsonTest
public class FooJsonTest {
@Autowired
private JacksonTester<Foo> json;
@Test
public void testSerialize() throws Exception {
Foo foo = new Foo(3, "Foo_Name_3");
assertThat(this.json.write(foo)).isEqualToJson("expected.json");
assertThat(this.json.write(foo)).hasJsonPathStringValue("@.name");
assertThat(this.json.write(foo)).extractingJsonPathStringValue("@.name").isEqualTo("Foo_Name_3");
}
@Test
public void testDeserialize() throws Exception {
String content = "{\"id\":4,\"name\":\"Foo_Name_4\"}";
assertThat(this.json.parseObject(content).getName()).isEqualTo("Foo_Name_4");
assertThat(this.json.parseObject(content).getId()==4);
}
}
@@ -1,18 +1,18 @@
package com.baeldung.applicationcontext;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import java.util.List;
import java.util.Locale;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ClasspathXmlApplicationContextTest {
import java.util.List;
import java.util.Locale;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
public class ClasspathXmlApplicationContextIntegrationTest {
@Test
public void testBasicUsage() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpathxmlapplicationcontext-example.xml");
+12 -1
View File
@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>intro-spring-data-rest</artifactId>
<artifactId>spring-data-rest</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
@@ -56,6 +56,17 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringDataRestApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT)
public class SpringDataRelationshipsTest {
public class SpringDataRelationshipsIntegrationTest {
@Autowired
private TestRestTemplate template;
@@ -1,11 +1,8 @@
package com.baeldung.validator;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import com.baeldung.SpringDataRestApplication;
import com.baeldung.models.WebsiteUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -17,14 +14,16 @@ import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.SpringDataRestApplication;
import com.baeldung.models.WebsiteUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringDataRestApplication.class)
@WebAppConfiguration
public class SpringDataRestValidatorTest {
public class SpringDataRestValidatorIntegrationTest {
public static final String URL = "http://localhost";
private MockMvc mockMvc;
+23 -3
View File
@@ -2,8 +2,28 @@
This is a simple Spring Boot app to demonstrate sending and receiving of messages in Kafka using spring-kafka.
As Kafka topics are not created automatically by default, this application requires that a topic named 'baeldung' is created manually.
As Kafka topics are not created automatically by default, this application requires that you create the following topics manually.
`$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic baeldung`
`$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic baeldung`<br>
`$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 5 --topic partitioned`<br>
`$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic filtered`<br>
`$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic greeting`<br>
Two listeners with group Ids **foo** and **bar** are configured. When run successfully, the *Hello World!* message will be received by both the listeners and logged on console.
When the application runs successfully, following output is logged on to console (along with spring logs):
#### Message received from the 'baeldung' topic by the basic listeners with groups foo and bar
>Received Messasge in group 'foo': Hello, World!<br>
Received Messasge in group 'bar': Hello, World!
#### Message received from the 'baeldung' topic, with the partition info
>Received Messasge: Hello, World! from partition: 0
#### Message received from the 'partitioned' topic, only from specific partitions
>Received Message: Hello To Partioned Topic! from partition: 0<br>
Received Message: Hello To Partioned Topic! from partition: 3
#### Message received from the 'filtered' topic after filtering
>Recieved Message in filtered listener: Hello Baeldung!
#### Message (Serialized Java Object) received from the 'greeting' topic
>Recieved greeting message: Greetings, World!!
+9 -3
View File
@@ -12,6 +12,7 @@
<properties>
<java.version>1.8</java.version>
<spring-kafka.version>1.1.3.RELEASE</spring-kafka.version>
<jackson.version>2.6.7</jackson.version>
</properties>
<parent>
@@ -21,17 +22,22 @@
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
<build>
@@ -0,0 +1,37 @@
package com.baeldung.spring.kafka;
public class Greeting {
private String msg;
private String name;
public Greeting() {
}
public Greeting(String msg, String name) {
this.msg = msg;
this.name = name;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return msg + ", " + name + "!";
}
}
@@ -10,21 +10,61 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.annotation.TopicPartition;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
@SpringBootApplication
public class KafkaApplication {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(KafkaApplication.class, args);
MessageProducer producer = context.getBean(MessageProducer.class);
producer.sendMessage("Hello, World!");
MessageListener listener = context.getBean(MessageListener.class);
listener.latch.await(20, TimeUnit.SECONDS);
Thread.sleep(60000);
context.close();
/*
* Sending a Hello World message to topic 'baeldung'.
* Must be recieved by both listeners with group foo
* and bar with containerFactory fooKafkaListenerContainerFactory
* and barKafkaListenerContainerFactory respectively.
* It will also be recieved by the listener with
* headersKafkaListenerContainerFactory as container factory
*/
producer.sendMessage("Hello, World!");
listener.latch.await(10, TimeUnit.SECONDS);
/*
* Sending message to a topic with 5 partition,
* each message to a different partition. But as per
* listener configuration, only the messages from
* partition 0 and 3 will be consumed.
*/
for (int i = 0; i < 5; i++) {
producer.sendMessageToPartion("Hello To Partioned Topic!", i);
}
listener.partitionLatch.await(10, TimeUnit.SECONDS);
/*
* Sending message to 'filtered' topic. As per listener
* configuration, all messages with char sequence
* 'World' will be discarded.
*/
producer.sendMessageToFiltered("Hello Baeldung!");
producer.sendMessageToFiltered("Hello World!");
listener.filterLatch.await(10, TimeUnit.SECONDS);
/*
* Sending message to 'greeting' topic. This will send
* and recieved a java object with the help of
* greetingKafkaListenerContainerFactory.
*/
producer.sendGreetingMessage(new Greeting("Greetings", "World!"));
listener.greetingLatch.await(10, TimeUnit.SECONDS);
context.close();
}
@Bean
@@ -42,18 +82,47 @@ public class KafkaApplication {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Autowired
private KafkaTemplate<String, Greeting> greetingKafkaTemplate;
@Value(value = "${message.topic.name}")
private String topicName;
@Value(value = "${partitioned.topic.name}")
private String partionedTopicName;
@Value(value = "${filtered.topic.name}")
private String filteredTopicName;
@Value(value = "${greeting.topic.name}")
private String greetingTopicName;
public void sendMessage(String message) {
kafkaTemplate.send(topicName, message);
}
public void sendMessageToPartion(String message, int partition) {
kafkaTemplate.send(partionedTopicName, partition, message);
}
public void sendMessageToFiltered(String message) {
kafkaTemplate.send(filteredTopicName, message);
}
public void sendGreetingMessage(Greeting greeting) {
greetingKafkaTemplate.send(greetingTopicName, greeting);
}
}
public static class MessageListener {
private CountDownLatch latch = new CountDownLatch(2);
private CountDownLatch latch = new CountDownLatch(3);
private CountDownLatch partitionLatch = new CountDownLatch(2);
private CountDownLatch filterLatch = new CountDownLatch(2);
private CountDownLatch greetingLatch = new CountDownLatch(1);
@KafkaListener(topics = "${message.topic.name}", group = "foo", containerFactory = "fooKafkaListenerContainerFactory")
public void listenGroupFoo(String message) {
@@ -67,6 +136,30 @@ public class KafkaApplication {
latch.countDown();
}
@KafkaListener(topics = "${message.topic.name}", containerFactory = "headersKafkaListenerContainerFactory")
public void listenWithHeaders(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition) {
System.out.println("Received Messasge: " + message + " from partition: " + partition);
latch.countDown();
}
@KafkaListener(topicPartitions = @TopicPartition(topic = "${partitioned.topic.name}", partitions = { "0", "3" }))
public void listenToParition(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition) {
System.out.println("Received Message: " + message + " from partition: " + partition);
this.partitionLatch.countDown();
}
@KafkaListener(topics = "${filtered.topic.name}", containerFactory = "filterKafkaListenerContainerFactory")
public void listenWithFilter(String message) {
System.out.println("Recieved Message in filtered listener: " + message);
this.filterLatch.countDown();
}
@KafkaListener(topics = "${greeting.topic.name}", containerFactory = "greetingKafkaListenerContainerFactory")
public void greetingListener(Greeting greeting) {
System.out.println("Recieved greeting message: " + greeting);
this.greetingLatch.countDown();
}
}
}
@@ -12,6 +12,7 @@ import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.support.serializer.JsonDeserializer;
@EnableKafka
@Configuration
@@ -35,11 +36,49 @@ public class KafkaConsumerConfig {
factory.setConsumerFactory(consumerFactory("foo"));
return factory;
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> barKafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory("bar"));
return factory;
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> headersKafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory("headers"));
return factory;
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> partitionsKafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory("partitions"));
return factory;
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> filterKafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory("filter"));
factory.setRecordFilterStrategy(record -> record.value()
.contains("World"));
return factory;
}
public ConsumerFactory<String, Greeting> greetingConsumerFactory() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
props.put(ConsumerConfig.GROUP_ID_CONFIG, "greeting");
return new DefaultKafkaConsumerFactory<>(props, new StringDeserializer(), new JsonDeserializer<>(Greeting.class));
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, Greeting> greetingKafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, Greeting> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(greetingConsumerFactory());
return factory;
}
}
@@ -11,6 +11,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.support.serializer.JsonSerializer;
@Configuration
public class KafkaProducerConfig {
@@ -29,8 +30,21 @@ public class KafkaProducerConfig {
@Bean
public KafkaTemplate<String, String> kafkaTemplate() {
KafkaTemplate<String, String> template =
new KafkaTemplate<String, String>(producerFactory());
return template;
return new KafkaTemplate<String, String>(producerFactory());
}
@Bean
public ProducerFactory<String, Greeting> greetingProducerFactory() {
Map<String, Object> configProps = new HashMap<String, Object>();
configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
return new DefaultKafkaProducerFactory<String, Greeting>(configProps);
}
@Bean
public KafkaTemplate<String, Greeting> greetingKafkaTemplate() {
return new KafkaTemplate<String, Greeting>(greetingProducerFactory());
}
}
@@ -1,2 +1,5 @@
kafka.bootstrapAddress=localhost:9092
message.topic.name=baeldung
greeting.topic.name=greeting
filtered.topic.name=filtered
partitioned.topic.name=partitioned
+62
View File
@@ -0,0 +1,62 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-mybatis</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>spring-mybatis Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.1.1.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-mybatis</finalName>
</build>
</project>
@@ -0,0 +1,48 @@
package com.baeldung.spring.mybatis.application;
import java.util.Date;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baeldung.spring.mybatis.model.Student;
import com.baeldung.spring.mybatis.service.StudentService;
public class SpringMyBatisApplication {
public static void main(String[] args){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("mybatis-spring.xml");
StudentService studentService = (StudentService) ctx.getBean("studentService");
Student student = new Student();
student.setFirstName("Santosh");
student.setLastName("B S");
student.setEmailAddress("[email protected]");
student.setPassword("Test123");
student.setDateOfBirth(new Date());
student.setUserName("santoshbs1");
boolean result = studentService.insertStudent(student);
if(result){
System.out.println("Student record saved successfully");
}
else{
System.out.println("Encountered an error while saving student data");
}
final String userName = "santosh";
Student matchingStudent = studentService.getStudentByUserName(userName);
if(matchingStudent == null){
System.out.println("No matching student found for User Name - " + userName);
}
else{
System.out.println("Student Details are as follows : ");
System.out.println("First Name : " + matchingStudent.getFirstName());
System.out.println("Last Name : " + matchingStudent.getLastName());
System.out.println("EMail : " + matchingStudent.getEmailAddress());
System.out.println("DOB : " + matchingStudent.getDateOfBirth());
System.out.println("User Name : " + matchingStudent.getUserName());
}
}
}
@@ -0,0 +1,60 @@
package com.baeldung.spring.mybatis.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.baeldung.spring.mybatis.model.Student;
import com.baeldung.spring.mybatis.model.StudentLogin;
import com.baeldung.spring.mybatis.service.StudentService;
@Controller
@SessionAttributes("student")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(value = "/signup", method = RequestMethod.GET)
public String signup(Model model) {
Student student = new Student();
model.addAttribute("student", student);
return "signup";
}
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String signup(@Validated @ModelAttribute("student") Student student, BindingResult result, ModelMap model) {
if (studentService.getStudentByUserName(student.getUserName())) {
model.addAttribute("message", "User Name exists. Try another user name");
return "signup";
} else {
studentService.insertStudent(student);
model.addAttribute("message", "Saved student details");
return "redirect:login.html";
}
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model) {
StudentLogin studentLogin = new StudentLogin();
model.addAttribute("studentLogin", studentLogin);
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@ModelAttribute("studentLogin") StudentLogin studentLogin, BindingResult result, ModelMap model) {
boolean found = studentService.getStudentByLogin(studentLogin.getUserName(), studentLogin.getPassword());
if (found) {
return "success";
} else {
return "failure";
}
}
}
@@ -0,0 +1,19 @@
package com.baeldung.spring.mybatis.mappers;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import com.baeldung.spring.mybatis.model.Student;
public interface StudentMapper {
@Insert("INSERT INTO student(userName, password, firstName,lastName, dateOfBirth, emailAddress) VALUES"
+ "(#{userName},#{password}, #{firstName}, #{lastName}, #{dateOfBirth}, #{emailAddress})")
@Options(useGeneratedKeys = true, keyProperty = "id", flushCache = true, keyColumn = "id")
public void insertStudent(Student student);
@Select("SELECT USERNAME as userName, PASSWORD as password, FIRSTNAME as firstName, LASTNAME as lastName, "
+ "DATEOFBIRTH as dateOfBirth, EMAILADDRESS as emailAddress " + "FROM student WHERE userName = #{userName}")
public Student getStudentByUserName(String userName);
}

Some files were not shown because too many files have changed in this diff Show More