Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-12669
This commit is contained in:
commit
1fd56a8c18
|
@ -66,3 +66,10 @@ jmeter/src/main/resources/*-JMeter.csv
|
|||
**/nb-configuration.xml
|
||||
core-scala/.cache-main
|
||||
core-scala/.cache-tests
|
||||
|
||||
|
||||
persistence-modules/hibernate5/transaction.log
|
||||
apache-avro/src/main/java/com/baeldung/avro/model/
|
||||
jta/transaction-logs/
|
||||
software-security/sql-injection-samples/derby.log
|
||||
spring-soap/src/main/java/com/baeldung/springsoap/gen/
|
|
@ -0,0 +1,3 @@
|
|||
package com.baeldung
|
||||
|
||||
class Car implements VehicleTrait {}
|
|
@ -22,7 +22,7 @@ trait UserTrait implements Human {
|
|||
msg
|
||||
}
|
||||
|
||||
def whoAmI() {
|
||||
def self() {
|
||||
return this
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung
|
||||
|
||||
trait VehicleTrait extends WheelTrait {
|
||||
|
||||
String showWheels() {
|
||||
return "Num of Wheels $noOfWheels"
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung
|
||||
|
||||
trait WheelTrait {
|
||||
|
||||
int noOfWheels
|
||||
|
||||
}
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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
|
||||
|
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.multireleaseapp;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class App {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(App.class);
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String dateToCheck = args[0];
|
||||
boolean isLeapYear = DateHelper.checkIfLeapYear(dateToCheck);
|
||||
logger.info("Date given " + dateToCheck + " is leap year: " + isLeapYear);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.multireleaseapp;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class DateHelper {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DateHelper.class);
|
||||
|
||||
public static boolean checkIfLeapYear(String dateStr) throws Exception {
|
||||
logger.info("Checking for leap year using Java 1 calendar API");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(dateStr));
|
||||
int year = cal.get(Calendar.YEAR);
|
||||
return (new GregorianCalendar()).isLeapYear(year);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.multireleaseapp;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class DateHelper {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DateHelper.class);
|
||||
|
||||
public static boolean checkIfLeapYear(String dateStr) throws Exception {
|
||||
logger.info("Checking for leap year using Java 9 Date Api");
|
||||
return LocalDate.parse(dateStr)
|
||||
.isLeapYear();
|
||||
}
|
||||
|
||||
}
|
|
@ -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)
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -5,6 +5,7 @@ import static org.junit.Assert.assertTrue;
|
|||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
@ -17,7 +18,6 @@ import org.slf4j.LoggerFactory;
|
|||
public class WriteCsvFileExampleUnitTest {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(WriteCsvFileExampleUnitTest.class);
|
||||
|
||||
private static final String CSV_FILE_NAME = "src/test/resources/exampleOutput.csv";
|
||||
private WriteCsvFileExample csvExample;
|
||||
|
||||
@Before
|
||||
|
@ -65,12 +65,12 @@ public class WriteCsvFileExampleUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void givenDataArray_whenConvertToCSV_thenOutputCreated() {
|
||||
public void givenDataArray_whenConvertToCSV_thenOutputCreated() throws IOException {
|
||||
List<String[]> dataLines = new ArrayList<String[]>();
|
||||
dataLines.add(new String[] { "John", "Doe", "38", "Comment Data\nAnother line of comment data" });
|
||||
dataLines.add(new String[] { "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" });
|
||||
|
||||
File csvOutputFile = new File(CSV_FILE_NAME);
|
||||
File csvOutputFile = File.createTempFile("exampleOutput", ".csv");
|
||||
try (PrintWriter pw = new PrintWriter(csvOutputFile)) {
|
||||
dataLines.stream()
|
||||
.map(csvExample::convertToCSV)
|
||||
|
@ -80,5 +80,6 @@ public class WriteCsvFileExampleUnitTest {
|
|||
}
|
||||
|
||||
assertTrue(csvOutputFile.exists());
|
||||
csvOutputFile.deleteOnExit();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,2 +0,0 @@
|
|||
John,Doe,38,Comment Data Another line of comment data
|
||||
Jane,"Doe, Jr.",19,"She said ""I'm being quoted"""
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -2,19 +2,25 @@ 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;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
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.dataformat.xml.XmlMapper;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public class XMLSerializeDeserializeUnitTest {
|
||||
|
||||
|
@ -49,24 +55,76 @@ public class XMLSerializeDeserializeUnitTest {
|
|||
assertTrue(value.getX() == 1 && value.getY() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
@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);
|
||||
}
|
||||
|
||||
@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 {
|
||||
BufferedReader br;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
@ -103,10 +161,10 @@ class SimpleBean {
|
|||
|
||||
}
|
||||
|
||||
class SimpleBeanForCapitalizedFields {
|
||||
@JsonProperty("X")
|
||||
private int x = 1;
|
||||
private int y = 2;
|
||||
class SimpleBeanForCapitalizedFields {
|
||||
@JsonProperty("X")
|
||||
private int x = 1;
|
||||
private int y = 2;
|
||||
|
||||
public int getX() {
|
||||
return x;
|
||||
|
|
|
@ -9,8 +9,10 @@ import java.util.Arrays;
|
|||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.collections4.MultiMapUtils;
|
||||
import org.apache.commons.collections4.MultiSet;
|
||||
import org.apache.commons.collections4.MultiValuedMap;
|
||||
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
|
||||
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
|
||||
|
@ -65,25 +67,28 @@ public class MultiValuedMapUnitTest {
|
|||
@Test
|
||||
public void givenMultiValuesMap_whenUsingKeysMethod_thenReturningAllKeys() {
|
||||
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
|
||||
|
||||
map.put("fruits", "apple");
|
||||
map.put("fruits", "orange");
|
||||
map.put("vehicles", "car");
|
||||
map.put("vehicles", "bike");
|
||||
|
||||
assertThat(((Collection<String>) map.keys())).contains("fruits", "vehicles");
|
||||
MultiSet<String> keys = map.keys();
|
||||
|
||||
assertThat((keys)).contains("fruits", "vehicles");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() {
|
||||
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
|
||||
|
||||
map.put("fruits", "apple");
|
||||
map.put("fruits", "orange");
|
||||
map.put("vehicles", "car");
|
||||
map.put("vehicles", "bike");
|
||||
|
||||
assertThat((Collection<String>) map.keySet()).contains("fruits", "vehicles");
|
||||
Set<String> keys = map.keySet();
|
||||
|
||||
assertThat(keys).contains("fruits", "vehicles");
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
1813
libraries/pom.xml
1813
libraries/pom.xml
File diff suppressed because it is too large
Load Diff
|
@ -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>{
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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 +1,2 @@
|
|||
/output-resources
|
||||
/output-resources
|
||||
/.idea/
|
||||
|
|
|
@ -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>
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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>
|
|
@ -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>
|
||||
|
|
|
@ -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)
|
||||
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
|
||||
@Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true)
|
||||
int updateUserSetStatusForNameNativePostgres(Integer status, String name);
|
||||
|
||||
@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);
|
||||
}
|
||||
|
|
|
@ -12,11 +12,7 @@ import org.springframework.data.jpa.domain.JpaSort;
|
|||
import org.springframework.data.mapping.PropertyReferenceException;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.*;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
@ -29,10 +25,10 @@ class UserRepositoryCommon {
|
|||
final String USER_EMAIL4 = "email4@example.com";
|
||||
final Integer INACTIVE_STATUS = 0;
|
||||
final Integer ACTIVE_STATUS = 1;
|
||||
private final String USER_EMAIL5 = "email5@example.com";
|
||||
private final String USER_EMAIL6 = "email6@example.com";
|
||||
private final String USER_NAME_ADAM = "Adam";
|
||||
private final String USER_NAME_PETER = "Peter";
|
||||
final String USER_EMAIL5 = "email5@example.com";
|
||||
final String USER_EMAIL6 = "email6@example.com";
|
||||
final String USER_NAME_ADAM = "Adam";
|
||||
final String USER_NAME_PETER = "Peter";
|
||||
|
||||
@Autowired
|
||||
protected UserRepository userRepository;
|
||||
|
@ -384,6 +380,22 @@ class UserRepositoryCommon {
|
|||
|
||||
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
|
||||
public void cleanUp() {
|
||||
|
|
2
pom.xml
2
pom.xml
|
@ -1594,7 +1594,7 @@
|
|||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<gib.referenceBranch>refs/heads/master</gib.referenceBranch>
|
||||
<gib.referenceBranch>refs/remotes/origin/master</gib.referenceBranch>
|
||||
<gib.skipTestsForNotImpactedModules>true</gib.skipTestsForNotImpactedModules>
|
||||
<gib.failOnMissingGitDir>false</gib.failOnMissingGitDir>
|
||||
<gib.failOnError>false</gib.failOnError>
|
||||
|
|
|
@ -16,6 +16,8 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
|
@ -42,6 +44,17 @@
|
|||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-jpamodelgen</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -57,4 +70,4 @@
|
|||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
|
@ -0,0 +1,34 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.examples.security.sql;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* @author Philippe
|
||||
*
|
||||
*/
|
||||
@Entity
|
||||
@Table(name="Accounts")
|
||||
@Data
|
||||
public class Account {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy=GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String customerId;
|
||||
private String accNumber;
|
||||
private String branchId;
|
||||
private BigDecimal balance;
|
||||
|
||||
}
|
|
@ -7,14 +7,24 @@ import java.sql.Connection;
|
|||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.AbstractMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.Query;
|
||||
import javax.persistence.TypedQuery;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Order;
|
||||
import javax.persistence.criteria.Root;
|
||||
import javax.persistence.metamodel.SingularAttribute;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
@ -27,9 +37,11 @@ import org.springframework.stereotype.Component;
|
|||
public class AccountDAO {
|
||||
|
||||
private final DataSource dataSource;
|
||||
private final EntityManager em;
|
||||
|
||||
public AccountDAO(DataSource dataSource) {
|
||||
public AccountDAO(DataSource dataSource, EntityManager em) {
|
||||
this.dataSource = dataSource;
|
||||
this.em = em;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -63,6 +75,26 @@ public class AccountDAO {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all accounts owned by a given customer,given his/her external id - JPA version
|
||||
*
|
||||
* @param customerId
|
||||
* @return
|
||||
*/
|
||||
public List<AccountDTO> unsafeJpaFindAccountsByCustomerId(String customerId) {
|
||||
String jql = "from Account where customerId = '" + customerId + "'";
|
||||
TypedQuery<Account> q = em.createQuery(jql, Account.class);
|
||||
return q.getResultList()
|
||||
.stream()
|
||||
.map(a -> AccountDTO.builder()
|
||||
.accNumber(a.getAccNumber())
|
||||
.balance(a.getBalance())
|
||||
.branchId(a.getAccNumber())
|
||||
.customerId(a.getCustomerId())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all accounts owned by a given customer,given his/her external id
|
||||
*
|
||||
|
@ -71,7 +103,7 @@ public class AccountDAO {
|
|||
*/
|
||||
public List<AccountDTO> safeFindAccountsByCustomerId(String customerId) {
|
||||
|
||||
String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ?";
|
||||
String sql = "select customer_id, branch_id,acc_number,balance from Accounts where customer_id = ?";
|
||||
|
||||
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) {
|
||||
p.setString(1, customerId);
|
||||
|
@ -93,23 +125,73 @@ public class AccountDAO {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all accounts owned by a given customer,given his/her external id - JPA version
|
||||
*
|
||||
* @param customerId
|
||||
* @return
|
||||
*/
|
||||
public List<AccountDTO> safeJpaFindAccountsByCustomerId(String customerId) {
|
||||
|
||||
String jql = "from Account where customerId = :customerId";
|
||||
TypedQuery<Account> q = em.createQuery(jql, Account.class)
|
||||
.setParameter("customerId", customerId);
|
||||
|
||||
return q.getResultList()
|
||||
.stream()
|
||||
.map(a -> AccountDTO.builder()
|
||||
.accNumber(a.getAccNumber())
|
||||
.balance(a.getBalance())
|
||||
.branchId(a.getAccNumber())
|
||||
.customerId(a.getCustomerId())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all accounts owned by a given customer,given his/her external id - JPA version
|
||||
*
|
||||
* @param customerId
|
||||
* @return
|
||||
*/
|
||||
public List<AccountDTO> safeJpaCriteriaFindAccountsByCustomerId(String customerId) {
|
||||
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Account> cq = cb.createQuery(Account.class);
|
||||
Root<Account> root = cq.from(Account.class);
|
||||
cq.select(root)
|
||||
.where(cb.equal(root.get(Account_.customerId), customerId));
|
||||
|
||||
TypedQuery<Account> q = em.createQuery(cq);
|
||||
|
||||
return q.getResultList()
|
||||
.stream()
|
||||
.map(a -> AccountDTO.builder()
|
||||
.accNumber(a.getAccNumber())
|
||||
.balance(a.getBalance())
|
||||
.branchId(a.getAccNumber())
|
||||
.customerId(a.getCustomerId())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private static final Set<String> VALID_COLUMNS_FOR_ORDER_BY = Stream.of("acc_number", "branch_id", "balance")
|
||||
.collect(Collectors.toCollection(HashSet::new));
|
||||
|
||||
|
||||
/**
|
||||
* Return all accounts owned by a given customer,given his/her external id
|
||||
*
|
||||
* @param customerId
|
||||
* @return
|
||||
*/
|
||||
public List<AccountDTO> safeFindAccountsByCustomerId(String customerId, String orderBy) {
|
||||
public List<AccountDTO> safeFindAccountsByCustomerId(String customerId, String orderBy) {
|
||||
|
||||
String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ? ";
|
||||
|
||||
if (VALID_COLUMNS_FOR_ORDER_BY.contains(orderBy)) {
|
||||
sql = sql + " order by " + orderBy;
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
throw new IllegalArgumentException("Nice try!");
|
||||
}
|
||||
|
||||
|
@ -135,35 +217,82 @@ public class AccountDAO {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
private static final Map<String,SingularAttribute<Account,?>> VALID_JPA_COLUMNS_FOR_ORDER_BY = Stream.of(
|
||||
new AbstractMap.SimpleEntry<>(Account_.ACC_NUMBER, Account_.accNumber),
|
||||
new AbstractMap.SimpleEntry<>(Account_.BRANCH_ID, Account_.branchId),
|
||||
new AbstractMap.SimpleEntry<>(Account_.BALANCE, Account_.balance)
|
||||
)
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
|
||||
/**
|
||||
* Return all accounts owned by a given customer,given his/her external id
|
||||
*
|
||||
* @param customerId
|
||||
* @return
|
||||
*/
|
||||
public List<AccountDTO> safeJpaFindAccountsByCustomerId(String customerId, String orderBy) {
|
||||
|
||||
SingularAttribute<Account,?> orderByAttribute = VALID_JPA_COLUMNS_FOR_ORDER_BY.get(orderBy);
|
||||
if ( orderByAttribute == null) {
|
||||
throw new IllegalArgumentException("Nice try!");
|
||||
}
|
||||
|
||||
CriteriaBuilder cb = em.getCriteriaBuilder();
|
||||
CriteriaQuery<Account> cq = cb.createQuery(Account.class);
|
||||
Root<Account> root = cq.from(Account.class);
|
||||
cq.select(root)
|
||||
.where(cb.equal(root.get(Account_.customerId), customerId))
|
||||
.orderBy(cb.asc(root.get(orderByAttribute)));
|
||||
|
||||
TypedQuery<Account> q = em.createQuery(cq);
|
||||
|
||||
return q.getResultList()
|
||||
.stream()
|
||||
.map(a -> AccountDTO.builder()
|
||||
.accNumber(a.getAccNumber())
|
||||
.balance(a.getBalance())
|
||||
.branchId(a.getAccNumber())
|
||||
.customerId(a.getCustomerId())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid placeholder usage example
|
||||
*
|
||||
* @param tableName
|
||||
* @return
|
||||
*/
|
||||
public List<AccountDTO> wrongCountRecordsByTableName(String tableName) {
|
||||
public Long wrongCountRecordsByTableName(String tableName) {
|
||||
|
||||
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement("select count(*) from ?")) {
|
||||
|
||||
try (Connection c = dataSource.getConnection();
|
||||
PreparedStatement p = c.prepareStatement("select count(*) from ?")) {
|
||||
|
||||
p.setString(1, tableName);
|
||||
ResultSet rs = p.executeQuery();
|
||||
List<AccountDTO> accounts = new ArrayList<>();
|
||||
while (rs.next()) {
|
||||
AccountDTO acc = AccountDTO.builder()
|
||||
.customerId(rs.getString("customerId"))
|
||||
.branchId(rs.getString("branch_id"))
|
||||
.accNumber(rs.getString("acc_number"))
|
||||
.balance(rs.getBigDecimal("balance"))
|
||||
.build();
|
||||
rs.next();
|
||||
return rs.getLong(1);
|
||||
|
||||
accounts.add(acc);
|
||||
}
|
||||
|
||||
return accounts;
|
||||
} catch (SQLException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid placeholder usage example - JPA
|
||||
*
|
||||
* @param tableName
|
||||
* @return
|
||||
*/
|
||||
public Long wrongJpaCountRecordsByTableName(String tableName) {
|
||||
|
||||
String jql = "select count(*) from :tableName";
|
||||
TypedQuery<Long> q = em.createQuery(jql, Long.class)
|
||||
.setParameter("tableName", tableName);
|
||||
|
||||
return q.getSingleResult();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
|
|
@ -1,19 +0,0 @@
|
|||
<databaseChangeLog
|
||||
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
|
||||
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
|
||||
|
||||
<changeSet id="create-tables" author="baeldung">
|
||||
<createTable tableName="Accounts" >
|
||||
<column name="id" autoIncrement="true" type="BIGINT" remarks="Internal account PK" >
|
||||
<constraints primaryKey="true"/>
|
||||
</column>
|
||||
<column name="customer_id" type="java.sql.Types.VARCHAR(32)" remarks="External Customer Id"></column>
|
||||
<column name="acc_number" type="java.sql.Types.VARCHAR(128)" remarks="External Account Number"></column>
|
||||
<column name="branch_id" type="java.sql.Types.VARCHAR(32)"></column>
|
||||
<column name="balance" type="CURRENCY"></column>
|
||||
|
||||
</createTable>
|
||||
</changeSet>
|
||||
</databaseChangeLog>
|
|
@ -1,8 +0,0 @@
|
|||
<databaseChangeLog
|
||||
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
|
||||
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
|
||||
|
||||
<include file="changelog/create-tables.xml" relativeToChangelogFile="true"/>
|
||||
</databaseChangeLog>
|
|
@ -40,6 +40,15 @@ public class SqlInjectionSamplesApplicationUnitTest {
|
|||
assertThat(accounts).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAVulnerableJpaMethod_whenHackedCustomerId_thenReturnAllAccounts() {
|
||||
|
||||
List<AccountDTO> accounts = target.unsafeJpaFindAccountsByCustomerId("C1' or '1'='1");
|
||||
assertThat(accounts).isNotNull();
|
||||
assertThat(accounts).isNotEmpty();
|
||||
assertThat(accounts).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASafeMethod_whenHackedCustomerId_thenReturnNoAccounts() {
|
||||
|
||||
|
@ -48,13 +57,36 @@ public class SqlInjectionSamplesApplicationUnitTest {
|
|||
assertThat(accounts).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASafeJpaMethod_whenHackedCustomerId_thenReturnNoAccounts() {
|
||||
|
||||
List<AccountDTO> accounts = target.safeJpaFindAccountsByCustomerId("C1' or '1'='1");
|
||||
assertThat(accounts).isNotNull();
|
||||
assertThat(accounts).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenASafeJpaCriteriaMethod_whenHackedCustomerId_thenReturnNoAccounts() {
|
||||
|
||||
List<AccountDTO> accounts = target.safeJpaCriteriaFindAccountsByCustomerId("C1' or '1'='1");
|
||||
assertThat(accounts).isNotNull();
|
||||
assertThat(accounts).isEmpty();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenASafeMethod_whenInvalidOrderBy_thenThroweException() {
|
||||
target.safeFindAccountsByCustomerId("C1", "INVALID");
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
@Test(expected = Exception.class)
|
||||
public void givenWrongPlaceholderUsageMethod_whenNormalCall_thenThrowsException() {
|
||||
target.wrongCountRecordsByTableName("Accounts");
|
||||
}
|
||||
|
||||
@Test(expected = Exception.class)
|
||||
public void givenWrongJpaPlaceholderUsageMethod_whenNormalCall_thenThrowsException() {
|
||||
target.wrongJpaCountRecordsByTableName("Accounts");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -2,5 +2,17 @@
|
|||
# Test profile configuration
|
||||
#
|
||||
spring:
|
||||
liquibase:
|
||||
change-log: db/changelog/db.changelog-master.xml
|
||||
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: none
|
||||
|
||||
datasource:
|
||||
initialization-mode: always
|
||||
initialization-mode: embedded
|
||||
|
||||
logging:
|
||||
level:
|
||||
sql: DEBUG
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
create table Accounts (
|
||||
id BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
|
||||
customer_id varchar(16) not null,
|
||||
acc_number varchar(16) not null,
|
||||
branch_id decimal(8,0),
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -3,15 +3,14 @@
|
|||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.spring-boot-crud</groupId>
|
||||
<artifactId>spring-boot-crud</artifactId>
|
||||
<version>0.1.0</version>
|
||||
<name>spring-boot-crud</name>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.6.RELEASE</version>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -41,11 +40,7 @@
|
|||
<artifactId>h2</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>spring-boot-crud</finalName>
|
||||
|
@ -62,4 +57,10 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [Formatting JSON Dates in Spring ](https://www.baeldung.com/spring-boot-formatting-json-dates)
|
|
@ -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>
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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)));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
|
||||
spring.jackson.time-zone=Europe/Zagreb
|
|
@ -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"));
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -6,10 +6,10 @@
|
|||
<!-- this needs to use the boot parent directly in order to not inherit logback dependencies -->
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.1.1.RELEASE</version>
|
||||
</parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.1.1.RELEASE</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
|
|
|
@ -6,10 +6,10 @@
|
|||
<!-- this needs to use the boot parent directly in order to not inherit logback dependencies -->
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.1.1.RELEASE</version>
|
||||
</parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.1.1.RELEASE</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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 {
|
||||
|
||||
|
|
|
@ -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;
|
||||
// }
|
||||
|
||||
}
|
|
@ -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>
|
||||
|
||||
|
|
@ -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": []
|
||||
}
|
||||
]
|
||||
}
|
|
@ -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;
|
|
@ -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
|
||||
|
|
|
@ -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) {
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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">
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -8,13 +8,15 @@
|
|||
<version>1.0.0</version>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.1.2.RELEASE</version>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
<spring-boot.version>2.1.2.RELEASE</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -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>
|
Loading…
Reference in New Issue