Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Sushant 2019-02-23 21:09:59 +05:30
commit 9c8a5053be
66 changed files with 2817 additions and 1028 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
}
def whoAmI() {
def self() {
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' () {
when:
def emp = employee.whoAmI()
def emp = employee.self()
then:
emp
emp instanceof Employee

View File

@ -27,3 +27,4 @@
- [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)
- [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>
<version>${colt.version}</version>
</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>
<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

@ -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

@ -1,16 +1,9 @@
package com.baeldung.jackson.dtos;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
public class Address {
@JacksonXmlProperty(localName = "street_number")
String streetNumber;
@JacksonXmlProperty(localName = "street_name")
String streetName;
@JacksonXmlProperty(localName = "city")
String city;
public String getStreetNumber() {

View File

@ -3,16 +3,13 @@ package com.baeldung.jackson.dtos;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
@JacksonXmlRootElement(localName = "person")
public final class Person {
private String firstName;
private String lastName;
@JacksonXmlElementWrapper(useWrapping = false)
private List<String> phoneNumbers = new ArrayList<>();
@JacksonXmlElementWrapper(localName = "addresses")
private List<Address> address = new ArrayList<>();
public List<Address> getAddress() {
@ -38,6 +35,7 @@ public final class Person {
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<String> getPhoneNumbers() {
return phoneNumbers;
}
@ -46,6 +44,4 @@ public final class Person {
this.phoneNumbers = phoneNumbers;
}
}

View File

@ -2,8 +2,10 @@ package com.baeldung.jackson.xml;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@ -56,17 +58,14 @@ public class XMLSerializeDeserializeUnitTest {
@Test
public void whenJavaGotFromXmlStrWithCapitalElem_thenCorrect() throws IOException {
XmlMapper xmlMapper = new XmlMapper();
SimpleBeanForCapitalizedFields value = xmlMapper.
readValue("<SimpleBeanForCapitalizedFields><X>1</X><y>2</y></SimpleBeanForCapitalizedFields>",
SimpleBeanForCapitalizedFields.class);
SimpleBeanForCapitalizedFields value = xmlMapper.readValue("<SimpleBeanForCapitalizedFields><X>1</X><y>2</y></SimpleBeanForCapitalizedFields>", SimpleBeanForCapitalizedFields.class);
assertTrue(value.getX() == 1 && value.getY() == 2);
}
@Test
public void whenJavaSerializedToXmlFileWithCapitalizedField_thenCorrect() throws IOException {
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValue(new File("target/simple_bean_capitalized.xml"),
new SimpleBeanForCapitalizedFields());
xmlMapper.writeValue(new File("target/simple_bean_capitalized.xml"), new SimpleBeanForCapitalizedFields());
File file = new File("target/simple_bean_capitalized.xml");
assertNotNull(file);
}
@ -74,7 +73,9 @@ public class XMLSerializeDeserializeUnitTest {
@Test
public void whenJavaDeserializedFromXmlFile_thenCorrect() throws IOException {
XmlMapper xmlMapper = new XmlMapper();
Person value = xmlMapper.readValue(new File("src/test/resources/person.xml"), Person.class);
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)
@ -90,33 +91,38 @@ public class XMLSerializeDeserializeUnitTest {
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("9911778981");
ph.add("9991111111");
ph.add("9911034731");
ph.add("9911033478");
person.setPhoneNumbers(ph);
List<Address> addresses = new ArrayList<>();
Address address1 = new Address();
address1.setStreetNumber("1");
address1.setStreetName("streetname1");
address1.setCity("city1");
address1.setStreetName("Name1");
address1.setCity("City1");
Address address2 = new Address();
address2.setStreetNumber("2");
address2.setStreetName("streetname2");
address2.setCity("city2");
address2.setStreetName("Name2");
address2.setCity("City2");
addresses.add(address1);
addresses.add(address2);
person.setAddress(addresses);
xmlMapper.writeValue(new File("src/test/resources/PersonGenerated.xml"), person);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
xmlMapper.writeValue(byteArrayOutputStream, person);
assertEquals(expectedXml, byteArrayOutputStream.toString());
}
private static String inputStreamToString(InputStream is) throws IOException {

View File

@ -1,18 +0,0 @@
<person>
<firstName></firstName>
<lastName></lastName>
<phoneNumbers>9911778981</phoneNumbers>
<phoneNumbers>9991111111</phoneNumbers>
<addresses>
<address>
<street_number>1</street_number>
<street_name>streetname1</street_name>
<city>city1</city>
</address>
<address>
<street_number>2</street_number>
<street_name>streetname2</street_name>
<city>city2</city>
</address>
</addresses>
</person>

View File

@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<person>
<firstName>Rohan</firstName>
<lastName>Daye</lastName>
<phoneNumbers>9911034731</phoneNumbers>
<phoneNumbers>9911033478</phoneNumbers>
<addresses>
<address>
<street_number>1</street_number>
<street_name>Name1</street_name>
<city>City1</city>
</address>
<address>
<street_number>2</street_number>
<street_name>Name2</street_name>
<city>City2</city>
</address>
</addresses>
</person>

View File

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

File diff suppressed because it is too large Load Diff

View File

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

@ -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());
}
}

3
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>
<artifactId>maven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>maven</name>
<packaging>war</packaging>
<modules>
<module>custom-rule</module>
<module>maven-enforcer</module>
</modules>
<name>maven</name>
<packaging>pom</packaging>
<dependencies>
<dependency>

View File

@ -89,12 +89,6 @@
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<!-- restdocs -->
<dependency>
<groupId>org.springframework.restdocs</groupId>
@ -162,7 +156,6 @@
<commons-collections4.version>4.1</commons-collections4.version>
<snippetsDirectory>${project.build.directory}/generated-snippets</snippetsDirectory>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<awaitility.version>3.1.6</awaitility.version>
</properties>
</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,4 @@ 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)
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)
7. [Http Message Converters with the Spring Framework](http://www.baeldung.com/spring-httpmessageconverter-rest)

View File

@ -25,16 +25,26 @@
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</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>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependency>
<!-- util -->
<dependency>
@ -67,5 +77,6 @@
<properties>
<start-class>com.baeldung.SpringBootRestApplication</start-class>
<guava.version>27.0.1-jre</guava.version>
<xstream.version>1.4.11.1</xstream.version>
</properties>
</project>

View File

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

View File

@ -1,10 +1,49 @@
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.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;
@Configuration
// If we want to enable xml configurations for message-converter:
// @ImportResource("classpath:WEB-INF/api-servlet.xml")
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)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SpringBootSecurityTagLibsApplication.class)
public class HomeControllerUnitTest {
public class HomeControllerIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;

View File

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

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:
- [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)
- [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)

View File

@ -52,10 +52,6 @@
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
@ -86,12 +82,6 @@
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>${xstream.version}</version>
</dependency>
<!-- util -->
<dependency>
<groupId>com.google.guava</groupId>
@ -281,7 +271,6 @@
<protobuf-java-format.version>1.4</protobuf-java-format.version>
<protobuf-java.version>3.1.0</protobuf-java.version>
<commons-lang3.version>3.5</commons-lang3.version>
<xstream.version>1.4.9</xstream.version>
<!-- util -->
<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.json.Jackson2ObjectMapperBuilder;
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.WebMvcConfigurer;
@ -33,22 +31,12 @@ public class WebConfig implements WebMvcConfigurer {
.dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm"));
messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
// messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
// messageConverters.add(createXmlHttpMessageConverter());
// messageConverters.add(new MappingJackson2HttpMessageConverter());
// 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;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("Foo")
public class Foo {
private long id;
private String name;

View File

@ -10,21 +10,11 @@
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" >
<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.protobuf.ProtobufHttpMessageConverter"/> -->
</mvc:message-converters>
</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.XmlViewResolver">

View File

@ -1,2 +1,3 @@
### Relevant Articles:
- [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:
- [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)
- [Using WireMock Scenarios](http://www.baeldung.com/using-wiremock-scenarios)
- [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)
- [REST API Testing with Karate](http://www.baeldung.com/karate-rest-api-testing)

View File

@ -159,7 +159,7 @@
<!-- testing -->
<rest-assured.version>2.9.0</rest-assured.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>
<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>
<version>LATEST</version>
</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>
<build>
@ -70,6 +82,8 @@
<properties>
<!-- testing -->
<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>
</project>