Merge branch 'master' into task/BAEL-10856
This commit is contained in:
commit
7d9db8d27e
|
@ -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
|
||||
|
||||
}
|
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,16 +1,9 @@
|
|||
package com.baeldung.jackson.dtos;
|
||||
|
||||
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
|
||||
|
||||
public class Address {
|
||||
|
||||
@JacksonXmlProperty(localName = "street_number")
|
||||
String streetNumber;
|
||||
|
||||
@JacksonXmlProperty(localName = "street_name")
|
||||
String streetName;
|
||||
|
||||
@JacksonXmlProperty(localName = "city")
|
||||
String city;
|
||||
|
||||
public String getStreetNumber() {
|
||||
|
|
|
@ -3,16 +3,13 @@ package com.baeldung.jackson.dtos;
|
|||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
|
||||
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
|
||||
|
||||
@JacksonXmlRootElement(localName = "person")
|
||||
public final class Person {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
@JacksonXmlElementWrapper(useWrapping = false)
|
||||
private List<String> phoneNumbers = new ArrayList<>();
|
||||
@JacksonXmlElementWrapper(localName = "addresses")
|
||||
private List<Address> address = new ArrayList<>();
|
||||
|
||||
public List<Address> getAddress() {
|
||||
|
@ -38,6 +35,7 @@ public final class Person {
|
|||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public List<String> getPhoneNumbers() {
|
||||
return phoneNumbers;
|
||||
}
|
||||
|
@ -46,6 +44,4 @@ public final class Person {
|
|||
this.phoneNumbers = phoneNumbers;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -2,8 +2,10 @@ package com.baeldung.jackson.xml;
|
|||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
|
@ -56,17 +58,14 @@ public class XMLSerializeDeserializeUnitTest {
|
|||
@Test
|
||||
public void whenJavaGotFromXmlStrWithCapitalElem_thenCorrect() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
SimpleBeanForCapitalizedFields value = xmlMapper.
|
||||
readValue("<SimpleBeanForCapitalizedFields><X>1</X><y>2</y></SimpleBeanForCapitalizedFields>",
|
||||
SimpleBeanForCapitalizedFields.class);
|
||||
SimpleBeanForCapitalizedFields value = xmlMapper.readValue("<SimpleBeanForCapitalizedFields><X>1</X><y>2</y></SimpleBeanForCapitalizedFields>", SimpleBeanForCapitalizedFields.class);
|
||||
assertTrue(value.getX() == 1 && value.getY() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJavaSerializedToXmlFileWithCapitalizedField_thenCorrect() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
xmlMapper.writeValue(new File("target/simple_bean_capitalized.xml"),
|
||||
new SimpleBeanForCapitalizedFields());
|
||||
xmlMapper.writeValue(new File("target/simple_bean_capitalized.xml"), new SimpleBeanForCapitalizedFields());
|
||||
File file = new File("target/simple_bean_capitalized.xml");
|
||||
assertNotNull(file);
|
||||
}
|
||||
|
@ -74,7 +73,9 @@ public class XMLSerializeDeserializeUnitTest {
|
|||
@Test
|
||||
public void whenJavaDeserializedFromXmlFile_thenCorrect() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
Person value = xmlMapper.readValue(new File("src/test/resources/person.xml"), Person.class);
|
||||
|
||||
String xml = "<person><firstName>Rohan</firstName><lastName>Daye</lastName><phoneNumbers><phoneNumbers>9911034731</phoneNumbers><phoneNumbers>9911033478</phoneNumbers></phoneNumbers><address><address><streetNumber>1</streetNumber><streetName>Name1</streetName><city>City1</city></address><address><streetNumber>2</streetNumber><streetName>Name2</streetName><city>City2</city></address></address></person>";
|
||||
Person value = xmlMapper.readValue(xml, Person.class);
|
||||
|
||||
assertTrue(value.getAddress()
|
||||
.get(0)
|
||||
|
@ -90,33 +91,38 @@ public class XMLSerializeDeserializeUnitTest {
|
|||
public void whenJavaSerializedToXmlFile_thenSuccess() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
|
||||
String expectedXml = "<person><firstName>Rohan</firstName><lastName>Daye</lastName><phoneNumbers><phoneNumbers>9911034731</phoneNumbers><phoneNumbers>9911033478</phoneNumbers></phoneNumbers><address><address><streetNumber>1</streetNumber><streetName>Name1</streetName><city>City1</city></address><address><streetNumber>2</streetNumber><streetName>Name2</streetName><city>City2</city></address></address></person>";
|
||||
|
||||
Person person = new Person();
|
||||
|
||||
person.setFirstName("Rohan");
|
||||
person.setLastName("Daye");
|
||||
|
||||
List<String> ph = new ArrayList<>();
|
||||
ph.add("9911778981");
|
||||
ph.add("9991111111");
|
||||
ph.add("9911034731");
|
||||
ph.add("9911033478");
|
||||
person.setPhoneNumbers(ph);
|
||||
|
||||
List<Address> addresses = new ArrayList<>();
|
||||
|
||||
Address address1 = new Address();
|
||||
address1.setStreetNumber("1");
|
||||
address1.setStreetName("streetname1");
|
||||
address1.setCity("city1");
|
||||
address1.setStreetName("Name1");
|
||||
address1.setCity("City1");
|
||||
|
||||
Address address2 = new Address();
|
||||
address2.setStreetNumber("2");
|
||||
address2.setStreetName("streetname2");
|
||||
address2.setCity("city2");
|
||||
address2.setStreetName("Name2");
|
||||
address2.setCity("City2");
|
||||
|
||||
addresses.add(address1);
|
||||
addresses.add(address2);
|
||||
|
||||
person.setAddress(addresses);
|
||||
|
||||
xmlMapper.writeValue(new File("src/test/resources/PersonGenerated.xml"), person);
|
||||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
xmlMapper.writeValue(byteArrayOutputStream, person);
|
||||
assertEquals(expectedXml, byteArrayOutputStream.toString());
|
||||
}
|
||||
|
||||
private static String inputStreamToString(InputStream is) throws IOException {
|
||||
|
|
|
@ -1,18 +0,0 @@
|
|||
<person>
|
||||
<firstName></firstName>
|
||||
<lastName></lastName>
|
||||
<phoneNumbers>9911778981</phoneNumbers>
|
||||
<phoneNumbers>9991111111</phoneNumbers>
|
||||
<addresses>
|
||||
<address>
|
||||
<street_number>1</street_number>
|
||||
<street_name>streetname1</street_name>
|
||||
<city>city1</city>
|
||||
</address>
|
||||
<address>
|
||||
<street_number>2</street_number>
|
||||
<street_name>streetname2</street_name>
|
||||
<city>city2</city>
|
||||
</address>
|
||||
</addresses>
|
||||
</person>
|
|
@ -1,19 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<person>
|
||||
<firstName>Rohan</firstName>
|
||||
<lastName>Daye</lastName>
|
||||
<phoneNumbers>9911034731</phoneNumbers>
|
||||
<phoneNumbers>9911033478</phoneNumbers>
|
||||
<addresses>
|
||||
<address>
|
||||
<street_number>1</street_number>
|
||||
<street_name>Name1</street_name>
|
||||
<city>City1</city>
|
||||
</address>
|
||||
<address>
|
||||
<street_number>2</street_number>
|
||||
<street_name>Name2</street_name>
|
||||
<city>City2</city>
|
||||
</address>
|
||||
</addresses>
|
||||
</person>
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -692,6 +692,13 @@
|
|||
<artifactId>asciidoctor-maven-plugin</artifactId>
|
||||
<version>1.5.7.1</version>
|
||||
</dependency>
|
||||
<!-- Reflections -->
|
||||
<dependency>
|
||||
<groupId>org.reflections</groupId>
|
||||
<artifactId>reflections</artifactId>
|
||||
<version>${reflections.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
|
@ -909,6 +916,8 @@
|
|||
<derive4j.version>1.1.0</derive4j.version>
|
||||
<mockftpserver.version>2.7.1</mockftpserver.version>
|
||||
<commons-net.version>3.6</commons-net.version>
|
||||
<reflections.version>0.9.11</reflections.version>
|
||||
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -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
|
||||
/.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>
|
||||
<modules>
|
||||
<module>custom-rule</module>
|
||||
<module>maven-enforcer</module>
|
||||
</modules>
|
||||
<name>maven</name>
|
||||
<packaging>war</packaging>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [Formatting JSON Dates in Spring ](https://www.baeldung.com/spring-boot-formatting-json-dates)
|
|
@ -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,6 +25,16 @@
|
|||
<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>
|
||||
|
@ -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;
|
|
@ -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;
|
||||
|
||||
|
@ -34,21 +32,11 @@ public class WebConfig implements WebMvcConfigurer {
|
|||
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)
|
||||
|
|
|
@ -30,7 +30,7 @@ public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
|
|||
.authorizedGrantTypes("authorization_code")
|
||||
.scopes("user_info")
|
||||
.autoApprove(true)
|
||||
.redirectUris("http://localhost:8082/ui/login","http://localhost:8083/ui2/login","http://localhost:8082/login")
|
||||
.redirectUris("http://localhost:8082/ui/login","http://localhost:8083/ui2/login","http://localhost:8082/login","http://www.example.com/")
|
||||
// .accessTokenValiditySeconds(3600)
|
||||
; // 1 hour
|
||||
}
|
||||
|
|
|
@ -22,7 +22,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
|||
.authenticated()
|
||||
.and()
|
||||
.formLogin()
|
||||
.permitAll();
|
||||
.permitAll()
|
||||
.and().csrf().disable();
|
||||
} // @formatter:on
|
||||
|
||||
@Override
|
||||
|
|
|
@ -0,0 +1,51 @@
|
|||
package org.baeldung;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.response.Response;
|
||||
|
||||
public class UserInfoEndpointLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenAccessToken_whenAccessUserInfoEndpoint_thenSuccess() {
|
||||
String accessToken = obtainAccessTokenUsingAuthorizationCodeFlow("john","123");
|
||||
Response response = RestAssured.given().header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken).get("http://localhost:8081/auth/user/me");
|
||||
|
||||
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
|
||||
assertEquals("john", response.jsonPath().get("name"));
|
||||
}
|
||||
|
||||
private String obtainAccessTokenUsingAuthorizationCodeFlow(String username, String password) {
|
||||
final String authServerUri = "http://localhost:8081/auth";
|
||||
final String redirectUrl = "http://www.example.com/";
|
||||
final String authorizeUrl = authServerUri + "/oauth/authorize?response_type=code&client_id=SampleClientId&redirect_uri=" + redirectUrl;
|
||||
final String tokenUrl = authServerUri + "/oauth/token";
|
||||
|
||||
// user login
|
||||
Response response = RestAssured.given().formParams("username", username, "password", password).post(authServerUri + "/login");
|
||||
final String cookieValue = response.getCookie("JSESSIONID");
|
||||
|
||||
// get authorization code
|
||||
RestAssured.given().cookie("JSESSIONID", cookieValue).get(authorizeUrl);
|
||||
response = RestAssured.given().cookie("JSESSIONID", cookieValue).post(authorizeUrl);
|
||||
assertEquals(HttpStatus.FOUND.value(), response.getStatusCode());
|
||||
final String location = response.getHeader(HttpHeaders.LOCATION);
|
||||
final String code = location.substring(location.indexOf("code=") + 5);
|
||||
|
||||
// get access token
|
||||
Map<String, String> params = new HashMap<String, String>();
|
||||
params.put("grant_type", "authorization_code");
|
||||
params.put("code", code);
|
||||
params.put("client_id", "SampleClientId");
|
||||
params.put("redirect_uri", redirectUrl);
|
||||
response = RestAssured.given().auth().basic("SampleClientId", "secret").formParams(params).post(tokenUrl);
|
||||
return response.jsonPath().getString("access_token");
|
||||
}
|
||||
}
|
|
@ -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