Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2019-02-24 13:39:18 +02:00
commit 8c8a1b9b0e
86 changed files with 2416 additions and 138 deletions

View File

@ -0,0 +1,3 @@
package com.baeldung
class Car implements VehicleTrait {}

View File

@ -22,7 +22,7 @@ trait UserTrait implements Human {
msg msg
} }
def whoAmI() { def self() {
return this return this
} }

View File

@ -0,0 +1,9 @@
package com.baeldung
trait VehicleTrait extends WheelTrait {
String showWheels() {
return "Num of Wheels $noOfWheels"
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung
trait WheelTrait {
int noOfWheels
}

View File

@ -0,0 +1,85 @@
package com.baeldung.map
import static org.junit.Assert.*
import org.junit.Test
class MapUnitTest {
@Test
void whenUsingEach_thenMapIsIterated() {
def map = [
'FF0000' : 'Red',
'00FF00' : 'Lime',
'0000FF' : 'Blue',
'FFFF00' : 'Yellow'
]
map.each { println "Hex Code: $it.key = Color Name: $it.value" }
}
@Test
void whenUsingEachWithEntry_thenMapIsIterated() {
def map = [
'E6E6FA' : 'Lavender',
'D8BFD8' : 'Thistle',
'DDA0DD' : 'Plum',
]
map.each { entry -> println "Hex Code: $entry.key = Color Name: $entry.value" }
}
@Test
void whenUsingEachWithKeyAndValue_thenMapIsIterated() {
def map = [
'000000' : 'Black',
'FFFFFF' : 'White',
'808080' : 'Gray'
]
map.each { key, val ->
println "Hex Code: $key = Color Name $val"
}
}
@Test
void whenUsingEachWithIndexAndEntry_thenMapIsIterated() {
def map = [
'800080' : 'Purple',
'4B0082' : 'Indigo',
'6A5ACD' : 'Slate Blue'
]
map.eachWithIndex { entry, index ->
def indent = ((index == 0 || index % 2 == 0) ? " " : "")
println "$indent Hex Code: $entry.key = Color Name: $entry.value"
}
}
@Test
void whenUsingEachWithIndexAndKeyAndValue_thenMapIsIterated() {
def map = [
'FFA07A' : 'Light Salmon',
'FF7F50' : 'Coral',
'FF6347' : 'Tomato',
'FF4500' : 'Orange Red'
]
map.eachWithIndex { key, val, index ->
def indent = ((index == 0 || index % 2 == 0) ? " " : "")
println "$indent Hex Code: $key = Color Name: $val"
}
}
@Test
void whenUsingForLoop_thenMapIsIterated() {
def map = [
'2E8B57' : 'Seagreen',
'228B22' : 'Forest Green',
'008000' : 'Green'
]
for (entry in map) {
println "Hex Code: $entry.key = Color Name: $entry.value"
}
}
}

View File

@ -57,7 +57,7 @@ class TraitsUnitTest extends Specification {
def 'Should return employee instance when using Employee.whoAmI method' () { def 'Should return employee instance when using Employee.whoAmI method' () {
when: when:
def emp = employee.whoAmI() def emp = employee.self()
then: then:
emp emp
emp instanceof Employee emp instanceof Employee

View File

@ -0,0 +1,62 @@
package com.baeldung.streamreduce.application;
import com.baeldung.streamreduce.entities.User;
import com.baeldung.streamreduce.utilities.NumberUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Application {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result1 = numbers.stream().reduce(0, (a, b) -> a + b);
System.out.println(result1);
int result2 = numbers.stream().reduce(0, Integer::sum);
System.out.println(result2);
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result3 = letters.stream().reduce("", (a, b) -> a + b);
System.out.println(result3);
String result4 = letters.stream().reduce("", String::concat);
System.out.println(result4);
String result5 = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase());
System.out.println(result5);
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
System.out.println(result6);
String result7 = letters.parallelStream().reduce("", String::concat);
System.out.println(result7);
int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
System.out.println(result8);
List<User> userList = new ArrayList<>();
for (int i = 0; i <= 1000000; i++) {
userList.add(new User("John" + i, i));
}
long t1 = System.currentTimeMillis();
int result9 = userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
long t2 = System.currentTimeMillis();
System.out.println(result9);
System.out.println("Sequential stream time: " + (t2 - t1) + "ms");
long t3 = System.currentTimeMillis();
int result10 = userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
long t4 = System.currentTimeMillis();
System.out.println(result10);
System.out.println("Parallel stream time: " + (t4 - t3) + "ms");
int result11 = NumberUtils.divideListElements(numbers, 1);
System.out.println(result11);
int result12 = NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 0);
System.out.println(result12);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.streamreduce.entities;
public class User {
private final String name;
private final int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "User{" + "name=" + name + ", age=" + age + '}';
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.streamreduce.utilities;
import java.util.List;
import java.util.function.BiFunction;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class NumberUtils {
private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName());
public static int divideListElements(List<Integer> values, Integer divider) {
return values.stream()
.reduce(0, (a, b) -> {
try {
return a / divider + b / divider;
} catch (ArithmeticException e) {
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
}
return 0;
});
}
public static int divideListElementsWithExtractedTryCatchBlock(List<Integer> values, int divider) {
return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider));
}
public static int divideListElementsWithApplyFunctionMethod(List<Integer> values, int divider) {
BiFunction<Integer, Integer, Integer> division = (a, b) -> a / b;
return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider));
}
private static int divide(int value, int factor) {
int result = 0;
try {
result = value / factor;
} catch (ArithmeticException e) {
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
}
return result;
}
private static int applyFunction(BiFunction<Integer, Integer, Integer> function, int a, int b) {
try {
return function.apply(a, b);
}
catch(Exception e) {
LOGGER.log(Level.INFO, "Exception occurred!");
}
return 0;
}
}

View File

@ -0,0 +1,126 @@
package com.baeldung.streamreduce.tests;
import com.baeldung.streamreduce.entities.User;
import com.baeldung.streamreduce.utilities.NumberUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class StreamReduceManualTest {
@Test
public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result = numbers.stream().reduce(0, (a, b) -> a + b);
assertThat(result).isEqualTo(21);
}
@Test
public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result = numbers.stream().reduce(0, Integer::sum);
assertThat(result).isEqualTo(21);
}
@Test
public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.stream().reduce("", (a, b) -> a + b);
assertThat(result).isEqualTo("abcde");
}
@Test
public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.stream().reduce("", String::concat);
assertThat(result).isEqualTo("abcde");
}
@Test
public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase());
assertThat(result).isEqualTo("ABCDE");
}
@Test
public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
assertThat(result).isEqualTo(65);
}
@Test
public void givenStringList_whenReduceWithParallelStream_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.parallelStream().reduce("", String::concat);
assertThat(result).isEqualTo("abcde");
}
@Test
public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
}
@Test
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
}
@Test
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlockAndListContainsZero_thenCorrect() {
List<Integer> numbers = Arrays.asList(0, 1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
}
@Test
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlockAndDividerIsZero_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 0)).isEqualTo(0);
}
@Test
public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
}
@Test
public void givenTwoStreams_whenCalledReduceOnParallelizedStream_thenFasterExecutionTime() {
List<User> userList = new ArrayList<>();
for (int i = 0; i <= 1000000; i++) {
userList.add(new User("John" + i, i));
}
long currentTime1 = System.currentTimeMillis();
userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
long sequentialExecutionTime = System.currentTimeMillis() -currentTime1;
long currentTime2 = System.currentTimeMillis();
userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
long parallelizedExecutionTime = System.currentTimeMillis() - currentTime2;
assertThat(parallelizedExecutionTime).isLessThan(sequentialExecutionTime);
}
}

View File

@ -27,3 +27,4 @@
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections) - [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection) - [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist) - [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal)

View File

@ -52,6 +52,17 @@
<artifactId>colt</artifactId> <artifactId>colt</artifactId>
<version>${colt.version}</version> <version>${colt.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-core.version}</version>
</dependency>
</dependencies> </dependencies>
<properties> <properties>

View File

@ -0,0 +1,96 @@
package com.baeldung.list.primitive;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import gnu.trove.list.array.TIntArrayList;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Measurement(batchSize = 100000, iterations = 10)
@Warmup(batchSize = 100000, iterations = 10)
@State(Scope.Thread)
public class PrimitivesListPerformance {
private List<Integer> arrayList = new ArrayList<>();
private TIntArrayList tList = new TIntArrayList();
private cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList();
private IntArrayList fastUtilList = new IntArrayList();
private int getValue = 10;
@Benchmark
public boolean addArrayList() {
return arrayList.add(getValue);
}
@Benchmark
public boolean addTroveIntList() {
return tList.add(getValue);
}
@Benchmark
public void addColtIntList() {
coltList.add(getValue);
}
@Benchmark
public boolean addFastUtilIntList() {
return fastUtilList.add(getValue);
}
@Benchmark
public int getArrayList() {
return arrayList.get(getValue);
}
@Benchmark
public int getTroveIntList() {
return tList.get(getValue);
}
@Benchmark
public int getColtIntList() {
return coltList.get(getValue);
}
@Benchmark
public int getFastUtilIntList() {
return fastUtilList.getInt(getValue);
}
@Benchmark
public boolean containsArrayList() {
return arrayList.contains(getValue);
}
@Benchmark
public boolean containsTroveIntList() {
return tList.contains(getValue);
}
@Benchmark
public boolean containsColtIntList() {
return coltList.contains(getValue);
}
@Benchmark
public boolean containsFastUtilIntList() {
return fastUtilList.contains(getValue);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(PrimitivesListPerformance.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@ -9,10 +9,10 @@
<description>DDD series examples</description> <description>DDD series examples</description>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <artifactId>parent-boot-2</artifactId>
<artifactId>spring-boot-starter-parent</artifactId> <groupId>com.baeldung</groupId>
<version>2.0.6.RELEASE</version> <version>0.0.1-SNAPSHOT</version>
<relativePath /> <!-- lookup parent from repository --> <relativePath>../parent-boot-2</relativePath>
</parent> </parent>
<dependencies> <dependencies>
@ -86,6 +86,7 @@
<properties> <properties>
<joda-money.version>1.0.1</joda-money.version> <joda-money.version>1.0.1</joda-money.version>
<maven-surefire-plugin.version>2.22.0</maven-surefire-plugin.version> <maven-surefire-plugin.version>2.22.0</maven-surefire-plugin.version>
<spring-boot.version>2.0.6.RELEASE</spring-boot.version>
</properties> </properties>
</project> </project>

View File

@ -11,7 +11,7 @@ import org.joda.money.Money;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
class OrderTest { class OrderUnitTest {
@DisplayName("given order with two items, when calculate total cost, then sum is returned") @DisplayName("given order with two items, when calculate total cost, then sum is returned")
@Test @Test
void test0() throws Exception { void test0() throws Exception {

View File

@ -7,7 +7,7 @@ import java.math.BigDecimal;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class ViolateOrderBusinessRulesTest { public class ViolateOrderBusinessRulesUnitTest {
@DisplayName("given two non-zero order line items, when create an order with them, it's possible to set total cost to zero") @DisplayName("given two non-zero order line items, when create an order with them, it's possible to set total cost to zero")
@Test @Test
void test() throws Exception { void test() throws Exception {

View File

@ -0,0 +1,33 @@
package org.baeldung.gson.conversion;
import com.google.gson.*;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
public class JsonObjectConversionsUnitTest {
@Test
void whenUsingJsonParser_thenConvertToJsonObject() throws Exception {
// Example 1: Using JsonParser
String json = "{ \"name\": \"Baeldung\", \"java\": true }";
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
Assert.assertTrue(jsonObject.isJsonObject());
Assert.assertTrue(jsonObject.get("name").getAsString().equals("Baeldung"));
Assert.assertTrue(jsonObject.get("java").getAsBoolean() == true);
}
@Test
void whenUsingGsonInstanceFromJson_thenConvertToJsonObject() throws Exception {
// Example 2: Using fromJson
String json = "{ \"name\": \"Baeldung\", \"java\": true }";
JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class);
Assert.assertTrue(convertedObject.isJsonObject());
Assert.assertTrue(convertedObject.get("name").getAsString().equals("Baeldung"));
Assert.assertTrue(convertedObject.get("java").getAsBoolean() == true);
}
}

View File

@ -21,7 +21,7 @@ import com.stackify.Application;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class) @SpringBootTest(classes = Application.class)
@WebAppConfiguration @WebAppConfiguration
public class EmployeeControllerTest { public class EmployeeControllerUnitTest {
private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; private static final String CONTENT_TYPE = "application/json;charset=UTF-8";

View File

@ -0,0 +1,33 @@
package com.baeldung.jackson.dtos;
public class Address {
String streetNumber;
String streetName;
String city;
public String getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(String streetNumber) {
this.streetNumber = streetNumber;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.jackson.dtos;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
@JacksonXmlRootElement(localName = "person")
public final class Person {
private String firstName;
private String lastName;
private List<String> phoneNumbers = new ArrayList<>();
private List<Address> address = new ArrayList<>();
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<String> getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}

View File

@ -2,19 +2,25 @@ package com.baeldung.jackson.xml;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test; import org.junit.Test;
import com.baeldung.jackson.dtos.Address;
import com.baeldung.jackson.dtos.Person;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.annotation.JsonProperty;
public class XMLSerializeDeserializeUnitTest { public class XMLSerializeDeserializeUnitTest {
@ -52,21 +58,73 @@ public class XMLSerializeDeserializeUnitTest {
@Test @Test
public void whenJavaGotFromXmlStrWithCapitalElem_thenCorrect() throws IOException { public void whenJavaGotFromXmlStrWithCapitalElem_thenCorrect() throws IOException {
XmlMapper xmlMapper = new XmlMapper(); XmlMapper xmlMapper = new XmlMapper();
SimpleBeanForCapitalizedFields value = xmlMapper. SimpleBeanForCapitalizedFields value = xmlMapper.readValue("<SimpleBeanForCapitalizedFields><X>1</X><y>2</y></SimpleBeanForCapitalizedFields>", SimpleBeanForCapitalizedFields.class);
readValue("<SimpleBeanForCapitalizedFields><X>1</X><y>2</y></SimpleBeanForCapitalizedFields>",
SimpleBeanForCapitalizedFields.class);
assertTrue(value.getX() == 1 && value.getY() == 2); assertTrue(value.getX() == 1 && value.getY() == 2);
} }
@Test @Test
public void whenJavaSerializedToXmlFileWithCapitalizedField_thenCorrect() throws IOException { public void whenJavaSerializedToXmlFileWithCapitalizedField_thenCorrect() throws IOException {
XmlMapper xmlMapper = new XmlMapper(); XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValue(new File("target/simple_bean_capitalized.xml"), xmlMapper.writeValue(new File("target/simple_bean_capitalized.xml"), new SimpleBeanForCapitalizedFields());
new SimpleBeanForCapitalizedFields());
File file = new File("target/simple_bean_capitalized.xml"); File file = new File("target/simple_bean_capitalized.xml");
assertNotNull(file); assertNotNull(file);
} }
@Test
public void whenJavaDeserializedFromXmlFile_thenCorrect() throws IOException {
XmlMapper xmlMapper = new XmlMapper();
String xml = "<person><firstName>Rohan</firstName><lastName>Daye</lastName><phoneNumbers><phoneNumbers>9911034731</phoneNumbers><phoneNumbers>9911033478</phoneNumbers></phoneNumbers><address><address><streetNumber>1</streetNumber><streetName>Name1</streetName><city>City1</city></address><address><streetNumber>2</streetNumber><streetName>Name2</streetName><city>City2</city></address></address></person>";
Person value = xmlMapper.readValue(xml, Person.class);
assertTrue(value.getAddress()
.get(0)
.getCity()
.equalsIgnoreCase("city1")
&& value.getAddress()
.get(1)
.getCity()
.equalsIgnoreCase("city2"));
}
@Test
public void whenJavaSerializedToXmlFile_thenSuccess() throws IOException {
XmlMapper xmlMapper = new XmlMapper();
String expectedXml = "<person><firstName>Rohan</firstName><lastName>Daye</lastName><phoneNumbers><phoneNumbers>9911034731</phoneNumbers><phoneNumbers>9911033478</phoneNumbers></phoneNumbers><address><address><streetNumber>1</streetNumber><streetName>Name1</streetName><city>City1</city></address><address><streetNumber>2</streetNumber><streetName>Name2</streetName><city>City2</city></address></address></person>";
Person person = new Person();
person.setFirstName("Rohan");
person.setLastName("Daye");
List<String> ph = new ArrayList<>();
ph.add("9911034731");
ph.add("9911033478");
person.setPhoneNumbers(ph);
List<Address> addresses = new ArrayList<>();
Address address1 = new Address();
address1.setStreetNumber("1");
address1.setStreetName("Name1");
address1.setCity("City1");
Address address2 = new Address();
address2.setStreetNumber("2");
address2.setStreetName("Name2");
address2.setCity("City2");
addresses.add(address1);
addresses.add(address2);
person.setAddress(addresses);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
xmlMapper.writeValue(byteArrayOutputStream, person);
assertEquals(expectedXml, byteArrayOutputStream.toString());
}
private static String inputStreamToString(InputStream is) throws IOException { private static String inputStreamToString(InputStream is) throws IOException {
BufferedReader br; BufferedReader br;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();

View File

@ -9,8 +9,10 @@ import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.collections4.MultiMapUtils; import org.apache.commons.collections4.MultiMapUtils;
import org.apache.commons.collections4.MultiSet;
import org.apache.commons.collections4.MultiValuedMap; import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.apache.commons.collections4.multimap.HashSetValuedHashMap; import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
@ -65,25 +67,28 @@ public class MultiValuedMapUnitTest {
@Test @Test
public void givenMultiValuesMap_whenUsingKeysMethod_thenReturningAllKeys() { public void givenMultiValuesMap_whenUsingKeysMethod_thenReturningAllKeys() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple"); map.put("fruits", "apple");
map.put("fruits", "orange"); map.put("fruits", "orange");
map.put("vehicles", "car"); map.put("vehicles", "car");
map.put("vehicles", "bike"); map.put("vehicles", "bike");
assertThat(((Collection<String>) map.keys())).contains("fruits", "vehicles"); MultiSet<String> keys = map.keys();
assertThat((keys)).contains("fruits", "vehicles");
} }
@Test @Test
public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() { public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple"); map.put("fruits", "apple");
map.put("fruits", "orange"); map.put("fruits", "orange");
map.put("vehicles", "car"); map.put("vehicles", "car");
map.put("vehicles", "bike"); map.put("vehicles", "bike");
assertThat((Collection<String>) map.keySet()).contains("fruits", "vehicles"); Set<String> keys = map.keySet();
assertThat(keys).contains("fruits", "vehicles");
} }

View File

@ -73,6 +73,12 @@
<version>${commons-collections4.version}</version> <version>${commons-collections4.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<properties> <properties>
@ -86,6 +92,7 @@
<jackson-databind.version>2.9.7</jackson-databind.version> <jackson-databind.version>2.9.7</jackson-databind.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<javax.version>1.1.2</javax.version> <javax.version>1.1.2</javax.version>
<assertj-core.version>3.11.1</assertj-core.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,50 @@
package com.baeldung.jsonobject.iterate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
public class JSONObjectIterator {
private Map<String, Object> keyValuePairs;
public JSONObjectIterator() {
keyValuePairs = new HashMap<>();
}
public void handleValue(String key, Object value) {
if (value instanceof JSONArray) {
handleJSONArray(key, (JSONArray) value);
} else if (value instanceof JSONObject) {
handleJSONObject((JSONObject) value);
}
keyValuePairs.put(key, value);
}
public void handleJSONObject(JSONObject jsonObject) {
Iterator<String> jsonObjectIterator = jsonObject.keys();
jsonObjectIterator.forEachRemaining(key -> {
Object value = jsonObject.get(key);
handleValue(key, value);
});
}
public void handleJSONArray(String key, JSONArray jsonArray) {
Iterator<Object> jsonArrayIterator = jsonArray.iterator();
jsonArrayIterator.forEachRemaining(element -> {
handleValue(key, element);
});
}
public Map<String, Object> getKeyValuePairs() {
return keyValuePairs;
}
public void setKeyValuePairs(Map<String, Object> keyValuePairs) {
this.keyValuePairs = keyValuePairs;
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.jsonobject.iterate;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
public class JSONObjectIteratorUnitTest {
private JSONObjectIterator jsonObjectIterator = new JSONObjectIterator();
@Test
public void givenJSONObject_whenIterating_thenGetKeyValuePairs() {
JSONObject jsonObject = getJsonObject();
jsonObjectIterator.handleJSONObject(jsonObject);
Map<String, Object> keyValuePairs = jsonObjectIterator.getKeyValuePairs();
assertThat(keyValuePairs.get("rType")).isEqualTo("Regular");
assertThat(keyValuePairs.get("rId")).isEqualTo("1001");
assertThat(keyValuePairs.get("cType")).isEqualTo("Chocolate");
assertThat(keyValuePairs.get("cId")).isEqualTo("1002");
assertThat(keyValuePairs.get("bType")).isEqualTo("BlueBerry");
assertThat(keyValuePairs.get("bId")).isEqualTo("1003");
assertThat(keyValuePairs.get("name")).isEqualTo("Cake");
assertThat(keyValuePairs.get("cakeId")).isEqualTo("0001");
assertThat(keyValuePairs.get("type")).isEqualTo("donut");
assertThat(keyValuePairs.get("Type")).isEqualTo("Maple");
assertThat(keyValuePairs.get("tId")).isEqualTo("5001");
assertThat(keyValuePairs.get("batters")
.toString()).isEqualTo("[{\"rType\":\"Regular\",\"rId\":\"1001\"},{\"cType\":\"Chocolate\",\"cId\":\"1002\"},{\"bType\":\"BlueBerry\",\"bId\":\"1003\"}]");
assertThat(keyValuePairs.get("cakeShapes")
.toString()).isEqualTo("[\"square\",\"circle\",\"heart\"]");
assertThat(keyValuePairs.get("topping")
.toString()).isEqualTo("{\"Type\":\"Maple\",\"tId\":\"5001\"}");
}
private JSONObject getJsonObject() {
JSONObject cake = new JSONObject();
cake.put("cakeId", "0001");
cake.put("type", "donut");
cake.put("name", "Cake");
JSONArray batters = new JSONArray();
JSONObject regular = new JSONObject();
regular.put("rId", "1001");
regular.put("rType", "Regular");
batters.put(regular);
JSONObject chocolate = new JSONObject();
chocolate.put("cId", "1002");
chocolate.put("cType", "Chocolate");
batters.put(chocolate);
JSONObject blueberry = new JSONObject();
blueberry.put("bId", "1003");
blueberry.put("bType", "BlueBerry");
batters.put(blueberry);
JSONArray cakeShapes = new JSONArray();
cakeShapes.put("square");
cakeShapes.put("circle");
cakeShapes.put("heart");
cake.put("cakeShapes", cakeShapes);
cake.put("batters", batters);
JSONObject topping = new JSONObject();
topping.put("tId", "5001");
topping.put("Type", "Maple");
cake.put("topping", topping);
return cake;
}
}

View File

@ -10,10 +10,10 @@
<description>JEE JTA demo</description> <description>JEE JTA demo</description>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <artifactId>parent-boot-2</artifactId>
<artifactId>spring-boot-starter-parent</artifactId> <groupId>com.baeldung</groupId>
<version>2.0.4.RELEASE</version> <version>0.0.1-SNAPSHOT</version>
<relativePath/> <relativePath>../parent-boot-2</relativePath>
</parent> </parent>
<dependencies> <dependencies>
@ -85,5 +85,6 @@
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<hsqldb.version>2.4.1</hsqldb.version> <hsqldb.version>2.4.1</hsqldb.version>
<spring-boot.version>2.0.4.RELEASE</spring-boot.version>
</properties> </properties>
</project> </project>

View File

@ -223,6 +223,12 @@
<artifactId>serenity-spring</artifactId> <artifactId>serenity-spring</artifactId>
<version>${serenity.version}</version> <version>${serenity.version}</version>
<scope>test</scope> <scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>net.serenity-bdd</groupId> <groupId>net.serenity-bdd</groupId>
@ -318,6 +324,12 @@
<artifactId>pact-jvm-consumer-junit_2.11</artifactId> <artifactId>pact-jvm-consumer-junit_2.11</artifactId>
<version>${pact.version}</version> <version>${pact.version}</version>
<scope>test</scope> <scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.codehaus.groovy</groupId> <groupId>org.codehaus.groovy</groupId>
@ -675,6 +687,17 @@
<version>${mockftpserver.version}</version> <version>${mockftpserver.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.7.1</version>
</dependency>
<!-- Reflections -->
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>${reflections.version}</version>
</dependency>
</dependencies> </dependencies>
@ -687,10 +710,6 @@
<name>bintray</name> <name>bintray</name>
<url>http://dl.bintray.com/cuba-platform/main</url> <url>http://dl.bintray.com/cuba-platform/main</url>
</repository> </repository>
<repository>
<id>Apache Staging</id>
<url>https://repository.apache.org/content/groups/staging</url>
</repository>
<repository> <repository>
<id>nm-repo</id> <id>nm-repo</id>
<name>Numerical Method's Maven Repository</name> <name>Numerical Method's Maven Repository</name>
@ -734,7 +753,7 @@
<api>JDO</api> <api>JDO</api>
<props>${basedir}/datanucleus.properties</props> <props>${basedir}/datanucleus.properties</props>
<log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration> <log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration>
<verbose>true</verbose> <verbose>false</verbose>
<fork>false</fork> <fork>false</fork>
<!-- Solve windows line too long error --> <!-- Solve windows line too long error -->
</configuration> </configuration>
@ -897,6 +916,8 @@
<derive4j.version>1.1.0</derive4j.version> <derive4j.version>1.1.0</derive4j.version>
<mockftpserver.version>2.7.1</mockftpserver.version> <mockftpserver.version>2.7.1</mockftpserver.version>
<commons-net.version>3.6</commons-net.version> <commons-net.version>3.6</commons-net.version>
<reflections.version>0.9.11</reflections.version>
</properties> </properties>
</project> </project>

View File

@ -6,7 +6,7 @@ import org.derive4j.Make;
@Data(value = @Derive( @Data(value = @Derive(
inClass = "{ClassName}Impl", inClass = "{ClassName}Impl",
make = {Make.lazyConstructor, Make.constructors} make = {Make.lazyConstructor, Make.constructors, Make.getters}
)) ))
public interface LazyRequest { public interface LazyRequest {
interface Cases<R>{ interface Cases<R>{

View File

@ -0,0 +1,71 @@
package com.baeldung.reflections;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Set;
import java.util.regex.Pattern;
import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.scanners.MethodParameterScanner;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.scanners.Scanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
public class ReflectionsApp {
public Set<Class<? extends Scanner>> getReflectionsSubTypes() {
Reflections reflections = new Reflections("org.reflections");
Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class);
return scannersSet;
}
public Set<Class<?>> getJDKFunctinalInterfaces() {
Reflections reflections = new Reflections("java.util.function");
Set<Class<?>> typesSet = reflections.getTypesAnnotatedWith(FunctionalInterface.class);
return typesSet;
}
public Set<Method> getDateDeprecatedMethods() {
Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner());
Set<Method> deprecatedMethodsSet = reflections.getMethodsAnnotatedWith(Deprecated.class);
return deprecatedMethodsSet;
}
@SuppressWarnings("rawtypes")
public Set<Constructor> getDateDeprecatedConstructors() {
Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner());
Set<Constructor> constructorsSet = reflections.getConstructorsAnnotatedWith(Deprecated.class);
return constructorsSet;
}
public Set<Method> getMethodsWithDateParam() {
Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner());
Set<Method> methodsSet = reflections.getMethodsMatchParams(Date.class);
return methodsSet;
}
public Set<Method> getMethodsWithVoidReturn() {
Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner());
Set<Method> methodsSet = reflections.getMethodsReturn(void.class);
return methodsSet;
}
public Set<String> getPomXmlPaths() {
Reflections reflections = new Reflections(new ResourcesScanner());
Set<String> resourcesSet = reflections.getResources(Pattern.compile(".*pom\\.xml"));
return resourcesSet;
}
public Set<Class<? extends Scanner>> getReflectionsSubTypesUsingBuilder() {
Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.reflections"))
.setScanners(new SubTypesScanner()));
Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class);
return scannersSet;
}
}

View File

@ -26,7 +26,7 @@ import com.google.api.services.sheets.v4.model.ValueRange;
import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.*;
public class GoogleSheetsIntegrationTest { public class GoogleSheetsLiveTest {
private static Sheets sheetsService; private static Sheets sheetsService;

View File

@ -0,0 +1,50 @@
package com.baeldung.reflections;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Test;
public class ReflectionsUnitTest {
@Test
public void givenTypeThenGetAllSubTypes() {
ReflectionsApp reflectionsApp = new ReflectionsApp();
assertFalse(reflectionsApp.getReflectionsSubTypes()
.isEmpty());
}
@Test
public void givenTypeAndUsingBuilderThenGetAllSubTypes() {
ReflectionsApp reflectionsApp = new ReflectionsApp();
assertFalse(reflectionsApp.getReflectionsSubTypesUsingBuilder()
.isEmpty());
}
@Test
public void givenAnnotationThenGetAllAnnotatedMethods() {
ReflectionsApp reflectionsApp = new ReflectionsApp();
assertFalse(reflectionsApp.getDateDeprecatedMethods()
.isEmpty());
}
@Test
public void givenAnnotationThenGetAllAnnotatedConstructors() {
ReflectionsApp reflectionsApp = new ReflectionsApp();
assertFalse(reflectionsApp.getDateDeprecatedConstructors()
.isEmpty());
}
@Test
public void givenParamTypeThenGetAllMethods() {
ReflectionsApp reflectionsApp = new ReflectionsApp();
assertFalse(reflectionsApp.getMethodsWithDateParam()
.isEmpty());
}
@Test
public void givenReturnTypeThenGetAllMethods() {
ReflectionsApp reflectionsApp = new ReflectionsApp();
assertFalse(reflectionsApp.getMethodsWithVoidReturn()
.isEmpty());
}
}

1
maven/.gitignore vendored
View File

@ -1 +1,2 @@
/output-resources /output-resources
/.idea/

69
maven/custom-rule/pom.xml Normal file
View File

@ -0,0 +1,69 @@
<?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">
<parent>
<artifactId>maven</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>custom-rule</artifactId>
<properties>
<api.version>3.0.0-M2</api.version>
<maven.version>2.0.9</maven.version>
</properties>
<dependencies>
<!-- dependencies for maven plugin-->
<dependency>
<groupId>org.apache.maven.enforcer</groupId>
<artifactId>enforcer-api</artifactId>
<version>${api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-project</artifactId>
<version>${maven.version}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
<version>${maven.version}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-artifact</artifactId>
<version>${maven.version}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>${maven.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-container-default</artifactId>
<version>1.0-alpha-9</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-verifier-plugin</artifactId>
<version>${maven.verifier.version}</version>
<configuration>
<verificationFile>../input-resources/verifications.xml</verificationFile>
<failOnError>false</failOnError>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,43 @@
/*
* Copyright (c) 2019 PloyRef
* Created by Seun Matt <smatt382@gmail.com>
* on 19 - 2 - 2019
*/
package com.baeldung.enforcer;
import org.apache.maven.enforcer.rule.api.EnforcerRule;
import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
public class MyCustomRule implements EnforcerRule {
public void execute(EnforcerRuleHelper enforcerRuleHelper) throws EnforcerRuleException {
try {
String groupId = (String) enforcerRuleHelper.evaluate("${project.groupId}");
if (groupId == null || !groupId.startsWith("org.baeldung")) {
throw new EnforcerRuleException("Project group id does not start with org.baeldung");
}
}
catch (ExpressionEvaluationException ex ) {
throw new EnforcerRuleException( "Unable to lookup an expression " + ex.getLocalizedMessage(), ex );
}
}
public boolean isCacheable() {
return false;
}
public boolean isResultValid(EnforcerRule enforcerRule) {
return false;
}
public String getCacheId() {
return null;
}
}

View File

@ -0,0 +1,74 @@
<?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">
<parent>
<artifactId>maven</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>maven-enforcer</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M2</version>
<!--<dependencies>-->
<!--<dependency>-->
<!--<groupId>com.baeldung</groupId>-->
<!--<artifactId>custom-rule</artifactId>-->
<!--<version>1.0</version>-->
<!--</dependency>-->
<!--</dependencies>-->
<executions>
<execution>
<id>enforce</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<banDuplicatePomDependencyVersions/>
<requireMavenVersion>
<version>3.0</version>
<message>Invalid Maven version. It should, at least, be 3.0</message>
</requireMavenVersion>
<requireJavaVersion>
<version>1.8</version>
</requireJavaVersion>
<requireEnvironmentVariable>
<variableName>ui</variableName>
<level>WARN</level>
</requireEnvironmentVariable>
<requireEnvironmentVariable>
<variableName>cook</variableName>
<level>WARN</level>
</requireEnvironmentVariable>
<requireActiveProfile>
<profiles>local,base</profiles>
<message>Missing active profiles</message>
<level>WARN</level>
</requireActiveProfile>
<!--other rules -->
<!--<myCustomRule implementation="com.baeldung.enforcer.MyCustomRule"/>-->
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-verifier-plugin</artifactId>
<version>${maven.verifier.version}</version>
<configuration>
<verificationFile>../input-resources/verifications.xml</verificationFile>
<failOnError>false</failOnError>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -4,8 +4,12 @@
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>maven</artifactId> <artifactId>maven</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>maven</name> <modules>
<packaging>war</packaging> <module>custom-rule</module>
<module>maven-enforcer</module>
</modules>
<name>maven</name>
<packaging>pom</packaging>
<dependencies> <dependencies>
<dependency> <dependency>

View File

@ -11,10 +11,10 @@
<description>Demo Spring Boot applications that starts H2 in memory database</description> <description>Demo Spring Boot applications that starts H2 in memory database</description>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <artifactId>parent-boot-2</artifactId>
<artifactId>spring-boot-starter-parent</artifactId> <groupId>com.baeldung</groupId>
<version>2.0.4.RELEASE</version> <version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath>../../../parent-boot-2</relativePath>
</parent> </parent>
<dependencies> <dependencies>
@ -48,6 +48,7 @@
<java.version>1.8</java.version> <java.version>1.8</java.version>
<!-- The main class to start by executing java -jar --> <!-- The main class to start by executing java -jar -->
<start-class>com.baeldung.h2db.demo.server.SpringBootApp</start-class> <start-class>com.baeldung.h2db.demo.server.SpringBootApp</start-class>
<spring-boot.version>2.0.4.RELEASE</spring-boot.version>
</properties> </properties>
</project> </project>

View File

@ -67,10 +67,14 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
@Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
int updateUserSetStatusForNameNative(Integer status, String name); int updateUserSetStatusForNameNative(Integer status, String name);
@Query(value = "INSERT INTO Users (name, age, email, status) VALUES (:name, :age, :email, :status)", nativeQuery = true)
@Modifying
void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("status") Integer status, @Param("email") String email);
@Modifying @Modifying
@Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true) @Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true)
int updateUserSetStatusForNameNativePostgres(Integer status, String name); int updateUserSetStatusForNameNativePostgres(Integer status, String name);
@Query(value = "SELECT u FROM User u WHERE u.name IN :names") @Query(value = "SELECT u FROM User u WHERE u.name IN :names")
List<User> findUserByNameList(@Param("names") Collection<String> names); List<User> findUserByNameList(@Param("names") Collection<String> names);
} }

View File

@ -12,11 +12,7 @@ import org.springframework.data.jpa.domain.JpaSort;
import org.springframework.data.mapping.PropertyReferenceException; import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays; import java.util.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -29,10 +25,10 @@ class UserRepositoryCommon {
final String USER_EMAIL4 = "email4@example.com"; final String USER_EMAIL4 = "email4@example.com";
final Integer INACTIVE_STATUS = 0; final Integer INACTIVE_STATUS = 0;
final Integer ACTIVE_STATUS = 1; final Integer ACTIVE_STATUS = 1;
private final String USER_EMAIL5 = "email5@example.com"; final String USER_EMAIL5 = "email5@example.com";
private final String USER_EMAIL6 = "email6@example.com"; final String USER_EMAIL6 = "email6@example.com";
private final String USER_NAME_ADAM = "Adam"; final String USER_NAME_ADAM = "Adam";
private final String USER_NAME_PETER = "Peter"; final String USER_NAME_PETER = "Peter";
@Autowired @Autowired
protected UserRepository userRepository; protected UserRepository userRepository;
@ -385,6 +381,22 @@ class UserRepositoryCommon {
assertThat(usersWithNames.size()).isEqualTo(2); assertThat(usersWithNames.size()).isEqualTo(2);
} }
@Test
@Transactional
public void whenInsertedWithQuery_ThenUserIsPersisted() {
userRepository.insertUser(USER_NAME_ADAM, 1, ACTIVE_STATUS, USER_EMAIL);
userRepository.insertUser(USER_NAME_PETER, 1, ACTIVE_STATUS, USER_EMAIL2);
User userAdam = userRepository.findUserByNameLike(USER_NAME_ADAM);
User userPeter = userRepository.findUserByNameLike(USER_NAME_PETER);
assertThat(userAdam).isNotNull();
assertThat(userAdam.getEmail()).isEqualTo(USER_EMAIL);
assertThat(userPeter).isNotNull();
assertThat(userPeter.getEmail()).isEqualTo(USER_EMAIL2);
}
@After @After
public void cleanUp() { public void cleanUp() {
userRepository.deleteAll(); userRepository.deleteAll();

View File

@ -475,6 +475,7 @@
<module>kotlin-libraries</module> <module>kotlin-libraries</module>
<!-- <module>lagom</module> --> <!-- Not a maven project --> <!-- <module>lagom</module> --> <!-- Not a maven project -->
<module>libraries</module>
<module>libraries-data</module> <module>libraries-data</module>
<module>libraries-apache-commons</module> <module>libraries-apache-commons</module>
<module>libraries-security</module> <module>libraries-security</module>

View File

@ -10,11 +10,11 @@
<description>WebFluc and Spring Security OAuth </description> <description>WebFluc and Spring Security OAuth </description>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <artifactId>parent-boot-2</artifactId>
<artifactId>spring-boot-starter-parent</artifactId> <groupId>com.baeldung</groupId>
<version>2.1.0.RELEASE</version> <version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath>../parent-boot-2</relativePath>
</parent> </parent>
<dependencies> <dependencies>
<dependency> <dependency>
@ -70,6 +70,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring-boot.version>2.1.0.RELEASE</spring-boot.version>
</properties> </properties>
</project> </project>

View File

@ -89,12 +89,6 @@
<groupId>org.junit.jupiter</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId> <artifactId>junit-jupiter-api</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<!-- restdocs --> <!-- restdocs -->
<dependency> <dependency>
<groupId>org.springframework.restdocs</groupId> <groupId>org.springframework.restdocs</groupId>
@ -162,7 +156,6 @@
<commons-collections4.version>4.1</commons-collections4.version> <commons-collections4.version>4.1</commons-collections4.version>
<snippetsDirectory>${project.build.directory}/generated-snippets</snippetsDirectory> <snippetsDirectory>${project.build.directory}/generated-snippets</snippetsDirectory>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version> <maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<awaitility.version>3.1.6</awaitility.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Formatting JSON Dates in Spring ](https://www.baeldung.com/spring-boot-formatting-json-dates)

122
spring-boot-data/pom.xml Normal file
View File

@ -0,0 +1,122 @@
<?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>spring-boot-data</artifactId>
<packaging>war</packaging>
<name>spring-boot-data</name>
<description>Spring Boot Data Module</description>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<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-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-boot</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
<version>${git-commit-id-plugin.version}</version>
<executions>
<execution>
<id>get-the-git-infos</id>
<goals>
<goal>revision</goal>
</goals>
<phase>initialize</phase>
</execution>
<execution>
<id>validate-the-git-infos</id>
<goals>
<goal>validateRevision</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
<configuration>
<generateGitPropertiesFile>true</generateGitPropertiesFile>
<generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties
</generateGitPropertiesFilename>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>autoconfiguration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude>
</excludes>
<includes>
<include>**/AutoconfigurationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<start-class>com.baeldung.SpringBootDataApplication</start-class>
<git-commit-id-plugin.version>2.2.4</git-commit-id-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootDataApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDataApplication.class, args);
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class Contact {
private String name;
private String address;
private String phone;
@JsonFormat(pattern="yyyy-MM-dd")
private LocalDate birthday;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime lastUpdate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
public LocalDateTime getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(LocalDateTime lastUpdate) {
this.lastUpdate = lastUpdate;
}
public Contact() {
}
public Contact(String name, String address, String phone, LocalDate birthday, LocalDateTime lastUpdate) {
this.name = name;
this.address = address;
this.phone = phone;
this.birthday = birthday;
this.lastUpdate = lastUpdate;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.jsondateformat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ContactApp {
public static void main(String[] args) {
SpringApplication.run(ContactApp.class, args);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.time.format.DateTimeFormatter;
@Configuration
public class ContactAppConfig {
private static final String dateFormat = "yyyy-MM-dd";
private static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss";
@Bean
@ConditionalOnProperty(value = "spring.jackson.date-format", matchIfMissing = true, havingValue = "none")
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.simpleDateFormat(dateTimeFormat);
builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
}
};
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.jsondateformat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping(value = "/contacts")
public class ContactController {
@GetMapping
public List<Contact> getContacts() {
List<Contact> contacts = new ArrayList<>();
Contact contact1 = new Contact("John Doe", "123 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
Contact contact2 = new Contact("John Doe 2", "124 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
Contact contact3 = new Contact("John Doe 3", "125 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
@GetMapping("/javaUtilDate")
public List<ContactWithJavaUtilDate> getContactsWithJavaUtilDate() {
List<ContactWithJavaUtilDate> contacts = new ArrayList<>();
ContactWithJavaUtilDate contact1 = new ContactWithJavaUtilDate("John Doe", "123 Sesame Street", "123-456-789", new Date(), new Date());
ContactWithJavaUtilDate contact2 = new ContactWithJavaUtilDate("John Doe 2", "124 Sesame Street", "123-456-789", new Date(), new Date());
ContactWithJavaUtilDate contact3 = new ContactWithJavaUtilDate("John Doe 3", "125 Sesame Street", "123-456-789", new Date(), new Date());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
@GetMapping("/plain")
public List<PlainContact> getPlainContacts() {
List<PlainContact> contacts = new ArrayList<>();
PlainContact contact1 = new PlainContact("John Doe", "123 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
PlainContact contact2 = new PlainContact("John Doe 2", "124 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
PlainContact contact3 = new PlainContact("John Doe 3", "125 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
@GetMapping("/plainWithJavaUtilDate")
public List<PlainContactWithJavaUtilDate> getPlainContactsWithJavaUtilDate() {
List<PlainContactWithJavaUtilDate> contacts = new ArrayList<>();
PlainContactWithJavaUtilDate contact1 = new PlainContactWithJavaUtilDate("John Doe", "123 Sesame Street", "123-456-789", new Date(), new Date());
PlainContactWithJavaUtilDate contact2 = new PlainContactWithJavaUtilDate("John Doe 2", "124 Sesame Street", "123-456-789", new Date(), new Date());
PlainContactWithJavaUtilDate contact3 = new PlainContactWithJavaUtilDate("John Doe 3", "125 Sesame Street", "123-456-789", new Date(), new Date());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class ContactWithJavaUtilDate {
private String name;
private String address;
private String phone;
@JsonFormat(pattern="yyyy-MM-dd")
private Date birthday;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date lastUpdate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public ContactWithJavaUtilDate() {
}
public ContactWithJavaUtilDate(String name, String address, String phone, Date birthday, Date lastUpdate) {
this.name = name;
this.address = address;
this.phone = phone;
this.birthday = birthday;
this.lastUpdate = lastUpdate;
}
}

View File

@ -0,0 +1,66 @@
package com.baeldung.jsondateformat;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class PlainContact {
private String name;
private String address;
private String phone;
private LocalDate birthday;
private LocalDateTime lastUpdate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
public LocalDateTime getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(LocalDateTime lastUpdate) {
this.lastUpdate = lastUpdate;
}
public PlainContact() {
}
public PlainContact(String name, String address, String phone, LocalDate birthday, LocalDateTime lastUpdate) {
this.name = name;
this.address = address;
this.phone = phone;
this.birthday = birthday;
this.lastUpdate = lastUpdate;
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class PlainContactWithJavaUtilDate {
private String name;
private String address;
private String phone;
@JsonFormat(pattern="yyyy-MM-dd")
private Date birthday;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date lastUpdate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public PlainContactWithJavaUtilDate() {
}
public PlainContactWithJavaUtilDate(String name, String address, String phone, Date birthday, Date lastUpdate) {
this.name = name;
this.address = address;
this.phone = phone;
this.birthday = birthday;
this.lastUpdate = lastUpdate;
}
}

View File

@ -0,0 +1,2 @@
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Europe/Zagreb

View File

@ -0,0 +1,100 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
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.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = ContactApp.class)
@TestPropertySource(properties = {
"spring.jackson.date-format=yyyy-MM-dd HH:mm:ss"
})
public class ContactAppIntegrationTest {
private final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void givenJsonFormatAnnotationAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException, ParseException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + port + "/contacts", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenJsonFormatAnnotationAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + port + "/contacts/javaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + port + "/contacts/plainWithJavaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test(expected = DateTimeParseException.class)
public void givenDefaultDateFormatInAppPropertiesAndJava8DateType_whenGet_thenNotApplyFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + port + "/contacts/plain", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
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.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = ContactApp.class)
public class ContactAppWithObjectMapperCustomizerIntegrationTest {
private final ObjectMapper mapper = new ObjectMapper();
@Autowired
private TestRestTemplate restTemplate;
@LocalServerPort
private int port;
@Test
public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + this.port + "/contacts/plainWithJavaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenDefaultDateFormatInAppPropertiesAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + this.port + "/contacts/plain", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
}

View File

@ -6,3 +6,5 @@ Module for the articles that are part of the Spring REST E-book:
4. [Build a REST API with Spring and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration) 4. [Build a REST API with Spring and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration)
5. [HATEOAS for a Spring REST Service](http://www.baeldung.com/rest-api-discoverability-with-spring) 5. [HATEOAS for a Spring REST Service](http://www.baeldung.com/rest-api-discoverability-with-spring)
6. [REST API Discoverability and HATEOAS](http://www.baeldung.com/restful-web-service-discoverability) 6. [REST API Discoverability and HATEOAS](http://www.baeldung.com/restful-web-service-discoverability)
7. [Versioning a REST API](http://www.baeldung.com/rest-versioning)
8. [Http Message Converters with the Spring Framework](http://www.baeldung.com/spring-httpmessageconverter-rest)

View File

@ -25,12 +25,22 @@
<groupId>com.fasterxml.jackson.dataformat</groupId> <groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId> <artifactId>jackson-dataformat-xml</artifactId>
</dependency> </dependency>
<!-- We'll need to comment out the jackson-dataformat-xml dependency if we want to use XStream: -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>${xstream.version}</version>
</dependency>
<dependency> <dependency>
<groupId>com.h2database</groupId> <groupId>com.h2database</groupId>
<artifactId>h2</artifactId> <artifactId>h2</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> </dependency>
@ -67,5 +77,6 @@
<properties> <properties>
<start-class>com.baeldung.SpringBootRestApplication</start-class> <start-class>com.baeldung.SpringBootRestApplication</start-class>
<guava.version>27.0.1-jre</guava.version> <guava.version>27.0.1-jre</guava.version>
<xstream.version>1.4.11.1</xstream.version>
</properties> </properties>
</project> </project>

View File

@ -8,6 +8,9 @@ import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("Foo")
@Entity @Entity
public class Foo implements Serializable { public class Foo implements Serializable {

View File

@ -1,10 +1,49 @@
package com.baeldung.spring; package com.baeldung.spring;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.oxm.xstream.XStreamMarshaller;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration @Configuration
// If we want to enable xml configurations for message-converter:
// @ImportResource("classpath:WEB-INF/api-servlet.xml")
public class WebConfig implements WebMvcConfigurer { public class WebConfig implements WebMvcConfigurer {
// @Override
// public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) {
// messageConverters.add(new MappingJackson2HttpMessageConverter());
// messageConverters.add(createXmlHttpMessageConverter());
// }
//
// private HttpMessageConverter<Object> createXmlHttpMessageConverter() {
// final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
//
// final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
// xstreamMarshaller.setAutodetectAnnotations(true);
// xmlConverter.setMarshaller(xstreamMarshaller);
// xmlConverter.setUnmarshaller(xstreamMarshaller);
//
// return xmlConverter;
// }
// Another possibility is to create a bean which will be automatically added to the Spring Boot Autoconfigurations
// @Bean
// public HttpMessageConverter<Object> createXmlHttpMessageConverter() {
// final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
//
// final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
// xstreamMarshaller.setAutodetectAnnotations(true);
// xmlConverter.setMarshaller(xstreamMarshaller);
// xmlConverter.setUnmarshaller(xstreamMarshaller);
//
// return xmlConverter;
// }
} }

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- We have to exclude Spring Boot's WebMvcAutoConfiguration if we want the xml-configured message-converters to work properly -->
<!-- <mvc:annotation-driven> -->
<!-- <mvc:message-converters -->
<!-- register-defaults="true"> -->
<!-- <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"> -->
<!-- <property name="marshaller" ref="xstreamMarshaller" /> -->
<!-- <property name="unmarshaller" ref="xstreamMarshaller" /> -->
<!-- </bean> -->
<!-- <bean -->
<!-- class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /> -->
<!-- </mvc:message-converters> -->
<!-- </mvc:annotation-driven> -->
<!-- <bean id="xstreamMarshaller" -->
<!-- class="org.springframework.oxm.xstream.XStreamMarshaller"> -->
<!-- <property name="autodetectAnnotations" value="true" /> -->
<!-- </bean> -->
<!-- -->
<!-- Also, we can JUST add a HttpMessageConverter Bean to the existing Spring Boot Autoconfiguration: -->
<!-- <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"> -->
<!-- <property name="marshaller" ref="xstreamMarshaller" /> -->
<!-- <property name="unmarshaller" ref="xstreamMarshaller" /> -->
<!-- </bean> -->
<!-- <bean id="xstreamMarshaller" -->
<!-- class="org.springframework.oxm.xstream.XStreamMarshaller"> -->
<!-- <property name="autodetectAnnotations" value="true" /> -->
<!-- </bean> -->
</beans>

View File

@ -0,0 +1,184 @@
{
"info": {
"_postman_id": "9989b5be-13ba-4d22-8e43-d05dbf628e58",
"name": "foo API test",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "add a foo",
"event": [
{
"listen": "test",
"script": {
"id": "a01534dc-6fc7-4c54-ba1d-6bcf311e5836",
"exec": [
"pm.test(\"success status\", () => pm.response.to.be.success );",
"",
"pm.test(\"name is correct\", () => ",
" pm.expect(pm.response.json().name).to.equal(\"Transformers\"));",
"",
"pm.test(\"id was assigned\", () => ",
" pm.expect(pm.response.json().id).to.be.not.null );",
"",
"pm.variables.set(\"id\", pm.response.json().id);"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"name": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"name\": \"Transformers\"\n}"
},
"url": {
"raw": "http://localhost:8082/spring-boot-rest/auth/foos",
"protocol": "http",
"host": [
"localhost"
],
"port": "8082",
"path": [
"spring-boot-rest",
"auth",
"foos"
]
}
},
"response": []
},
{
"name": "get a foo",
"event": [
{
"listen": "test",
"script": {
"id": "03de440c-b483-4ab8-a11a-d0c99b349963",
"exec": [
"pm.test(\"success status\", () => pm.response.to.be.success );",
"",
"pm.test(\"name is correct\", () => ",
" pm.expect(pm.response.json().name).to.equal(\"Transformers\"));",
"",
"pm.test(\"id is correct\", () => ",
" pm.expect(pm.response.json().id).to.equal(pm.variables.get(\"id\")) );"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"url": {
"raw": "http://localhost:8082/spring-boot-rest/auth/foos/{{id}}",
"protocol": "http",
"host": [
"localhost"
],
"port": "8082",
"path": [
"spring-boot-rest",
"auth",
"foos",
"{{id}}"
]
}
},
"response": []
},
{
"name": "delete a foo",
"event": [
{
"listen": "test",
"script": {
"id": "74c1bb0f-c06c-48b1-a545-459233541b14",
"exec": [
"pm.test(\"success status\", () => pm.response.to.be.success );"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "DELETE",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"url": {
"raw": "http://localhost:8082/spring-boot-rest/auth/foos/{{id}}",
"protocol": "http",
"host": [
"localhost"
],
"port": "8082",
"path": [
"spring-boot-rest",
"auth",
"foos",
"{{id}}"
]
}
},
"response": []
},
{
"name": "verify delete",
"event": [
{
"listen": "test",
"script": {
"id": "03de440c-b483-4ab8-a11a-d0c99b349963",
"exec": [
"pm.test(\"status is 500\", () => pm.response.to.have.status(500) );",
"",
"pm.test(\"no value present\", () => ",
" pm.expect(pm.response.json().cause).to.equal(\"No value present\"));"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"url": {
"raw": "http://localhost:8082/spring-boot-rest/auth/foos/{{id}}",
"protocol": "http",
"host": [
"localhost"
],
"port": "8082",
"path": [
"spring-boot-rest",
"auth",
"foos",
"{{id}}"
]
}
},
"response": []
}
]
}

View File

@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SpringBootSecurityTagLibsApplication.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SpringBootSecurityTagLibsApplication.class)
public class HomeControllerUnitTest { public class HomeControllerIntegrationTest {
@Autowired @Autowired
private TestRestTemplate restTemplate; private TestRestTemplate restTemplate;

View File

@ -72,6 +72,3 @@ chaos.monkey.watcher.service=true
chaos.monkey.watcher.repository=false chaos.monkey.watcher.repository=false
#Component watcher active #Component watcher active
chaos.monkey.watcher.component=false chaos.monkey.watcher.component=false
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Europe/Zagreb

View File

@ -11,19 +11,12 @@
<packaging>jar</packaging> <packaging>jar</packaging>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <artifactId>parent-boot-2</artifactId>
<artifactId>spring-boot-starter-parent</artifactId> <groupId>com.baeldung</groupId>
<version>2.0.4.RELEASE</version> <version>0.0.1-SNAPSHOT</version>
<relativePath/> <relativePath>../../parent-boot-2</relativePath>
</parent> </parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud-function.version>1.0.1.RELEASE</spring-cloud-function.version>
<aws-lambda-events.version>2.0.2</aws-lambda-events.version>
</properties>
<dependencies> <dependencies>
<dependency> <dependency>
@ -89,4 +82,13 @@
</plugins> </plugins>
</build> </build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud-function.version>1.0.1.RELEASE</spring-cloud-function.version>
<aws-lambda-events.version>2.0.2</aws-lambda-events.version>
<spring-boot.version>2.0.4.RELEASE</spring-boot.version>
</properties>
</project> </project>

View File

@ -12,7 +12,7 @@ import static org.assertj.core.api.Java6Assertions.assertThat;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CloudFunctionApplicationTests { public class CloudFunctionApplicationUnitTest {
@LocalServerPort @LocalServerPort
private int port; private int port;

View File

@ -7,10 +7,10 @@
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <artifactId>parent-boot-1</artifactId>
<artifactId>spring-boot-starter-parent</artifactId> <groupId>com.baeldung</groupId>
<version>1.5.17.RELEASE</version> <version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath>../../../parent-boot-1</relativePath>
</parent> </parent>
<dependencies> <dependencies>
@ -44,6 +44,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring-boot.version>1.5.17.RELEASE</spring-boot.version>
</properties> </properties>
</project> </project>

View File

@ -7,10 +7,10 @@
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <artifactId>parent-boot-1</artifactId>
<artifactId>spring-boot-starter-parent</artifactId> <groupId>com.baeldung</groupId>
<version>1.5.17.RELEASE</version> <version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath>../../../parent-boot-1</relativePath>
</parent> </parent>
<dependencies> <dependencies>
@ -44,6 +44,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring-boot.version>1.5.17.RELEASE</spring-boot.version>
</properties> </properties>
</project> </project>

View File

@ -10,11 +10,11 @@
<description>Demo project for Spring Boot</description> <description>Demo project for Spring Boot</description>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <artifactId>parent-boot-2</artifactId>
<artifactId>spring-boot-starter-parent</artifactId> <groupId>com.baeldung</groupId>
<version>2.0.6.RELEASE</version> <version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath>../../parent-boot-2</relativePath>
</parent> </parent>
<dependencies> <dependencies>
<dependency> <dependency>
@ -72,6 +72,7 @@
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring-cloud.version>Finchley.SR1</spring-cloud.version> <spring-cloud.version>Finchley.SR1</spring-cloud.version>
<spring-boot.version>2.0.6.RELEASE</spring-boot.version>
</properties> </properties>
</project> </project>

View File

@ -26,7 +26,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@AutoConfigureTestDatabase @AutoConfigureTestDatabase
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class GreetingControllerTest { public class GreetingControllerUnitTest {
private static final String SIMPLE_GREETING = "/greeting/simple"; private static final String SIMPLE_GREETING = "/greeting/simple";
private static final String ADVANCED_GREETING = "/greeting/advanced"; private static final String ADVANCED_GREETING = "/greeting/advanced";

View File

@ -0,0 +1,31 @@
package com.baeldung.spring.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.*;
@Controller
@RequestMapping("/public/api/1")
@Validated
public class RequestAndPathVariableValidationController {
@GetMapping("/name-for-day")
public String getNameOfDayByNumberRequestParam(@RequestParam @Min(1) @Max(7) Integer dayOfWeek) {
return dayOfWeek + "";
}
@GetMapping("/name-for-day/{dayOfWeek}")
public String getNameOfDayByPathVariable(@PathVariable("dayOfWeek") @Min(1) @Max(7) Integer dayOfWeek) {
return dayOfWeek + "";
}
@GetMapping("/valid-name")
public void validStringRequestParam(@RequestParam @NotBlank @Size(max = 10) @Pattern(regexp = "^[A-Z][a-zA-Z0-9]+$") String name) {
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.spring.controller;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.spring.ClientWebConfig;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ClientWebConfig.class)
@WebAppConfiguration
public class RequestAndPathVariableValidationControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void getNameOfDayByNumberRequestParam_whenGetWithProperRequestParam_thenReturn200() throws Exception {
mockMvc.perform(get("/public/api/1/name-for-day").param("dayOfWeek", Integer.toString(5)))
.andExpect(status().isOk());
}
@Test
public void getNameOfDayByNumberRequestParam_whenGetWithRequestParamOutOfRange_thenReturn400() throws Exception {
mockMvc.perform(get("/public/api/1/name-for-day").param("dayOfWeek", Integer.toString(15)))
.andExpect(status().isBadRequest());
}
@Test
public void getNameOfDayByPathVariable_whenGetWithProperRequestParam_thenReturn200() throws Exception {
mockMvc.perform(get("/public/api/1/name-for-day/{dayOfWeek}", Integer.toString(5))).andExpect(status().isOk());
}
@Test
public void getNameOfDayByPathVariable_whenGetWithRequestParamOutOfRange_thenReturn400() throws Exception {
mockMvc.perform(get("/public/api/1/name-for-day/{dayOfWeek}", Integer.toString(15)))
.andExpect(status().isBadRequest());
}
@Test
public void validStringRequestParam_whenGetWithProperRequestParam_thenReturn200() throws Exception {
mockMvc.perform(get("/public/api/1/valid-name").param("name", "John")).andExpect(status().isOk());
}
@Test
public void validStringRequestParam_whenGetWithTooLongRequestParam_thenReturn400() throws Exception {
mockMvc.perform(get("/public/api/1/valid-name").param("name", "asdfghjklqw"))
.andExpect(status().isBadRequest());
}
@Test
public void validStringRequestParam_whenGetWithLowerCaseRequestParam_thenReturn400() throws Exception {
mockMvc.perform(get("/public/api/1/valid-name").param("name", "john")).andExpect(status().isBadRequest());
}
}

View File

@ -5,7 +5,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles: ### Relevant Articles:
- [Spring @RequestMapping](http://www.baeldung.com/spring-requestmapping) - [Spring @RequestMapping](http://www.baeldung.com/spring-requestmapping)
- [Http Message Converters with the Spring Framework](http://www.baeldung.com/spring-httpmessageconverter-rest)
- [Returning Custom Status Codes from Spring Controllers](http://www.baeldung.com/spring-mvc-controller-custom-http-status-code) - [Returning Custom Status Codes from Spring Controllers](http://www.baeldung.com/spring-mvc-controller-custom-http-status-code)
- [A Guide to OkHttp](http://www.baeldung.com/guide-to-okhttp) - [A Guide to OkHttp](http://www.baeldung.com/guide-to-okhttp)
- [Binary Data Formats in a Spring REST API](http://www.baeldung.com/spring-rest-api-with-binary-data-formats) - [Binary Data Formats in a Spring REST API](http://www.baeldung.com/spring-rest-api-with-binary-data-formats)

View File

@ -52,10 +52,6 @@
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId> <artifactId>spring-webmvc</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
<dependency> <dependency>
<groupId>commons-fileupload</groupId> <groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId> <artifactId>commons-fileupload</artifactId>
@ -86,12 +82,6 @@
<artifactId>jackson-dataformat-xml</artifactId> <artifactId>jackson-dataformat-xml</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>${xstream.version}</version>
</dependency>
<!-- util --> <!-- util -->
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
@ -281,7 +271,6 @@
<protobuf-java-format.version>1.4</protobuf-java-format.version> <protobuf-java-format.version>1.4</protobuf-java-format.version>
<protobuf-java.version>3.1.0</protobuf-java.version> <protobuf-java.version>3.1.0</protobuf-java.version>
<commons-lang3.version>3.5</commons-lang3.version> <commons-lang3.version>3.5</commons-lang3.version>
<xstream.version>1.4.9</xstream.version>
<!-- util --> <!-- util -->
<guava.version>20.0</guava.version> <guava.version>20.0</guava.version>

View File

@ -8,8 +8,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.oxm.xstream.XStreamMarshaller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@ -34,21 +32,11 @@ public class WebConfig implements WebMvcConfigurer {
messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
// messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); // messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
// messageConverters.add(createXmlHttpMessageConverter());
// messageConverters.add(new MappingJackson2HttpMessageConverter()); // messageConverters.add(new MappingJackson2HttpMessageConverter());
// messageConverters.add(new ProtobufHttpMessageConverter()); // messageConverters.add(new ProtobufHttpMessageConverter());
} }
private HttpMessageConverter<Object> createXmlHttpMessageConverter() {
final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
xmlConverter.setMarshaller(xstreamMarshaller);
xmlConverter.setUnmarshaller(xstreamMarshaller);
return xmlConverter;
}
*/ */
} }

View File

@ -1,8 +1,5 @@
package com.baeldung.sampleapp.web.dto; package com.baeldung.sampleapp.web.dto;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("Foo")
public class Foo { public class Foo {
private long id; private long id;
private String name; private String name;

View File

@ -10,21 +10,11 @@
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" > <mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" >
<mvc:message-converters register-defaults="true"> <mvc:message-converters register-defaults="true">
<!--
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="xstreamMarshaller" />
<property name="unmarshaller" ref="xstreamMarshaller" />
</bean>
-->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<!-- <bean class="org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter"/> --> <!-- <bean class="org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter"/> -->
</mvc:message-converters> </mvc:message-converters>
</mvc:annotation-driven> </mvc:annotation-driven>
<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller" />
<!-- -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" />
<bean class="org.springframework.web.servlet.view.XmlViewResolver"> <bean class="org.springframework.web.servlet.view.XmlViewResolver">

View File

@ -1,2 +1,3 @@
### Relevant Articles: ### Relevant Articles:
- [Spring Security Login Page with Angular](https://www.baeldung.com/spring-security-login-angular) - [Spring Security Login Page with Angular](https://www.baeldung.com/spring-security-login-angular)
- [Fixing 401s with CORS Preflights and Spring Security](https://www.baeldung.com/spring-security-cors-preflight)

View File

@ -8,6 +8,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles: ### Relevant Articles:
- [Test a REST API with Java](http://www.baeldung.com/integration-testing-a-rest-api) - [Test a REST API with Java](http://www.baeldung.com/integration-testing-a-rest-api)
- [Introduction to WireMock](http://www.baeldung.com/introduction-to-wiremock) - [Introduction to WireMock](http://www.baeldung.com/introduction-to-wiremock)
- [Using WireMock Scenarios](http://www.baeldung.com/using-wiremock-scenarios)
- [REST API Testing with Cucumber](http://www.baeldung.com/cucumber-rest-api-testing) - [REST API Testing with Cucumber](http://www.baeldung.com/cucumber-rest-api-testing)
- [Testing a REST API with JBehave](http://www.baeldung.com/jbehave-rest-testing) - [Testing a REST API with JBehave](http://www.baeldung.com/jbehave-rest-testing)
- [REST API Testing with Karate](http://www.baeldung.com/karate-rest-api-testing) - [REST API Testing with Karate](http://www.baeldung.com/karate-rest-api-testing)

View File

@ -159,7 +159,7 @@
<!-- testing --> <!-- testing -->
<rest-assured.version>2.9.0</rest-assured.version> <rest-assured.version>2.9.0</rest-assured.version>
<cucumber.version>1.2.5</cucumber.version> <cucumber.version>1.2.5</cucumber.version>
<wiremock.version>2.4.1</wiremock.version> <wiremock.version>2.21.0</wiremock.version>
<karate.version>0.6.1</karate.version> <karate.version>0.6.1</karate.version>
<httpcore.version>4.4.5</httpcore.version> <httpcore.version>4.4.5</httpcore.version>

View File

@ -0,0 +1,75 @@
package com.baeldung.rest.wiremock.scenario;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.junit.Assert.assertEquals;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Rule;
import org.junit.Test;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
public class WireMockScenarioExampleIntegrationTest {
private static final String THIRD_STATE = "third";
private static final String SECOND_STATE = "second";
private static final String TIP_01 = "finally block is not called when System.exit() is called in the try block";
private static final String TIP_02 = "keep your code clean";
private static final String TIP_03 = "use composition rather than inheritance";
private static final String TEXT_PLAIN = "text/plain";
static int port = 9999;
@Rule
public WireMockRule wireMockRule = new WireMockRule(port);
@Test
public void changeStateOnEachCallTest() throws IOException {
createWireMockStub(Scenario.STARTED, SECOND_STATE, TIP_01);
createWireMockStub(SECOND_STATE, THIRD_STATE, TIP_02);
createWireMockStub(THIRD_STATE, Scenario.STARTED, TIP_03);
assertEquals(TIP_01, nextTip());
assertEquals(TIP_02, nextTip());
assertEquals(TIP_03, nextTip());
assertEquals(TIP_01, nextTip());
}
private void createWireMockStub(String currentState, String nextState, String responseBody) {
stubFor(get(urlEqualTo("/java-tip"))
.inScenario("java tips")
.whenScenarioStateIs(currentState)
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", TEXT_PLAIN)
.withBody(responseBody))
.willSetStateTo(nextState)
);
}
private String nextTip() throws ClientProtocolException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet(String.format("http://localhost:%s/java-tip", port));
HttpResponse httpResponse = httpClient.execute(request);
return firstLineOfResponse(httpResponse);
}
private static String firstLineOfResponse(HttpResponse httpResponse) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()))) {
return reader.readLine();
}
}
}

View File

@ -54,6 +54,18 @@
<artifactId>spring-data-jpa</artifactId> <artifactId>spring-data-jpa</artifactId>
<version>LATEST</version> <version>LATEST</version>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -70,6 +82,8 @@
<properties> <properties>
<!-- testing --> <!-- testing -->
<hamcrest.version>2.0.0.0</hamcrest.version> <hamcrest.version>2.0.0.0</hamcrest.version>
<awaitility.version>3.1.6</awaitility.version>
<junit.jupiter.version>5.4.0</junit.jupiter.version>
</properties> </properties>
</project> </project>