Spring Native Demo Application
++ This is a sample application that can be built as native executable. +
+ + + diff --git a/spring-boot-modules/spring-boot-3-native/src/test/java/com/baeldung/sample/JacksonAutoConfigurationIntegrationTest.java b/spring-boot-modules/spring-boot-3-native/src/test/java/com/baeldung/sample/JacksonAutoConfigurationIntegrationTest.java new file mode 100644 index 0000000000..83ec6b3923 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-native/src/test/java/com/baeldung/sample/JacksonAutoConfigurationIntegrationTest.java @@ -0,0 +1,23 @@ +package com.baeldung.sample; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +class JacksonAutoConfigurationIntegrationTest { + + @Autowired + ObjectMapper mapper; + + @Test + void shouldUseSnakeCasePropertyNamingStrategy() { + assertThat(mapper.getPropertyNamingStrategy()) + .isSameAs(PropertyNamingStrategies.SNAKE_CASE); + } + +} diff --git a/spring-boot-modules/spring-boot-3-native/src/test/java/com/baeldung/sample/JacksonRuntimeHintsUnitTest.java b/spring-boot-modules/spring-boot-3-native/src/test/java/com/baeldung/sample/JacksonRuntimeHintsUnitTest.java new file mode 100644 index 0000000000..eb45db9407 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-native/src/test/java/com/baeldung/sample/JacksonRuntimeHintsUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.sample; + +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import org.junit.jupiter.api.Test; +import org.springframework.aot.hint.RuntimeHints; +import org.springframework.aot.hint.predicate.RuntimeHintsPredicates; + +import static org.assertj.core.api.Assertions.assertThat; + +class JacksonRuntimeHintsUnitTest { + + @Test + void shouldRegisterSnakeCasePropertyNamingStrategy() { + // arrange + final var hints = new RuntimeHints(); + final var expectSnakeCaseHint = RuntimeHintsPredicates + .reflection() + .onField(PropertyNamingStrategies.class, "SNAKE_CASE"); + // act + new JacksonRuntimeHints.PropertyNamingStrategyRegistrar() + .registerHints(hints, getClass().getClassLoader()); + // assert + assertThat(expectSnakeCaseHint).accepts(hints); + + } + +} diff --git a/spring-boot-modules/spring-boot-3-observation/README.md b/spring-boot-modules/spring-boot-3-observation/README.md new file mode 100644 index 0000000000..edfb23ce2b --- /dev/null +++ b/spring-boot-modules/spring-boot-3-observation/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Observability with Spring Boot 3](https://www.baeldung.com/spring-boot-3-observability) diff --git a/spring-boot-modules/spring-boot-3-observation/pom.xml b/spring-boot-modules/spring-boot-3-observation/pom.xml new file mode 100644 index 0000000000..ed613ee98e --- /dev/null +++ b/spring-boot-modules/spring-boot-3-observation/pom.xml @@ -0,0 +1,66 @@ + ++ Hello, --name--. +
+ID | +Name | +Address | +Service Rendered | +
---|---|---|---|
Text ... | +Text ... | +Text ... | +Text... | +
Customer Portal
+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam + erat lectus, vehicula feugiat ultricies at, tempus sed ante. Cras + arcu erat, lobortis vitae quam et, mollis pharetra odio. Nullam sit + amet congue ipsum. Nunc dapibus odio ut ligula venenatis porta non + id dui. Duis nec tempor tellus. Suspendisse id blandit ligula, sit + amet varius mauris. Nulla eu eros pharetra, tristique dui quis, + vehicula libero. Aenean a neque sit amet tellus porttitor rutrum nec + at leo.
+ +Existing Customers
+Document last modified 2017/10/23.
+Copyright: Lorem Ipsum
+- > getAllTopics() {
+ return new ResponseEntity<>(topicService.getAlllTopics(), HttpStatus.OK);
+ }
+}
diff --git a/spring-boot-modules/spring-boot-swagger-2/src/main/java/com/baeldung/springdoc/demo/model/Topic.java b/spring-boot-modules/spring-boot-swagger-2/src/main/java/com/baeldung/springdoc/demo/model/Topic.java
new file mode 100644
index 0000000000..0e4417b64f
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger-2/src/main/java/com/baeldung/springdoc/demo/model/Topic.java
@@ -0,0 +1,26 @@
+package com.baeldung.springdoc.demo.model;
+
+public class Topic {
+
+ Integer id;
+ String name;
+
+ public Topic(Integer id, String name) {
+ super();
+ this.id = id;
+ this.name = name;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+ public void setId(Integer id) {
+ this.id = id;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/spring-boot-modules/spring-boot-swagger-2/src/main/java/com/baeldung/springdoc/demo/service/TopicService.java b/spring-boot-modules/spring-boot-swagger-2/src/main/java/com/baeldung/springdoc/demo/service/TopicService.java
new file mode 100644
index 0000000000..a468d2915b
--- /dev/null
+++ b/spring-boot-modules/spring-boot-swagger-2/src/main/java/com/baeldung/springdoc/demo/service/TopicService.java
@@ -0,0 +1,26 @@
+package com.baeldung.springdoc.demo.service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.springframework.stereotype.Service;
+
+import com.baeldung.springdoc.demo.model.Topic;
+
+@Service
+public class TopicService {
+
+ private List
- {
-}
+}
\ No newline at end of file
diff --git a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/ItemService.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemService.java
similarity index 88%
rename from spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/ItemService.java
rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemService.java
index 6a59c7d74e..fdb6f975a0 100644
--- a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/ItemService.java
+++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemService.java
@@ -13,7 +13,7 @@ public class ItemService {
@Cacheable(value = "itemCache")
public Item getItemForId(String id) {
return itemRepository.findById(id)
- .orElseThrow(RuntimeException::new);
+ .orElseThrow(RuntimeException::new);
}
-}
+}
\ No newline at end of file
diff --git a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java
similarity index 99%
rename from spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java
rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java
index 3b337def01..2be0cc6ff2 100644
--- a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java
+++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java
@@ -11,4 +11,4 @@ public class RedisCacheApplication {
public static void main(String[] args) {
SpringApplication.run(RedisCacheApplication.class, args);
}
-}
+}
\ No newline at end of file
diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/Application.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/CachingTTLApplication.java
old mode 100755
new mode 100644
similarity index 75%
rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/Application.java
rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/CachingTTLApplication.java
index b8f337bcf7..f6f1a13727
--- a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/Application.java
+++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/CachingTTLApplication.java
@@ -6,8 +6,8 @@ import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
-public class Application {
+public class CachingTTLApplication {
public static void main(String[] args) {
- SpringApplication.run(Application.class, args);
+ SpringApplication.run(CachingTTLApplication.class, args);
}
}
\ No newline at end of file
diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java
similarity index 100%
rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java
rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java
diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java
old mode 100755
new mode 100644
similarity index 79%
rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java
rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java
index f1a90eb950..f489e979ff
--- a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java
+++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java
@@ -5,7 +5,6 @@ import com.baeldung.caching.ttl.model.Hotel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@@ -27,10 +26,4 @@ public class HotelController {
public List
getAllHotels() { return hotelService.getAllHotels(); } - - @GetMapping(value = "/{id}") - @ResponseStatus(HttpStatus.OK) - public Hotel getHotelById(@PathVariable Long id) { - return hotelService.getHotelById(id); - } } \ No newline at end of file diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java similarity index 100% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java similarity index 100% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/model/City.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/City.java similarity index 86% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/model/City.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/City.java index 88902d7e05..5c9ea2098a 100644 --- a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/model/City.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/City.java @@ -17,7 +17,7 @@ public class City implements Serializable { private String name; - private double cityCentreLatitude; + private double cityCentreLattitude; private double cityCentreLongitude; public City() {} @@ -25,7 +25,7 @@ public class City implements Serializable { public City(Long id, String name, double cityCentreLatitude, double cityCentreLongitude) { this.id = id; this.name = name; - this.cityCentreLatitude = cityCentreLatitude; + this.cityCentreLattitude = cityCentreLatitude; this.cityCentreLongitude = cityCentreLongitude; } @@ -42,7 +42,7 @@ public class City implements Serializable { } public double getCityCentreLatitude() { - return cityCentreLatitude; + return cityCentreLattitude; } public double getCityCentreLongitude() { @@ -56,7 +56,7 @@ public class City implements Serializable { City city = (City) o; - if (Double.compare(city.cityCentreLatitude, cityCentreLatitude) != 0) return false; + if (Double.compare(city.cityCentreLattitude, cityCentreLattitude) != 0) return false; if (Double.compare(city.cityCentreLongitude, cityCentreLongitude) != 0) return false; if (!Objects.equals(id, city.id)) return false; return Objects.equals(name, city.name); diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/model/Hotel.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/Hotel.java old mode 100755 new mode 100644 similarity index 92% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/model/Hotel.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/Hotel.java index ffb4f298c8..4244d339e4 --- a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/model/Hotel.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/Hotel.java @@ -22,7 +22,7 @@ public class Hotel implements Serializable { private City city; private String address; - private double latitude; + private double lattitude; private double longitude; private boolean deleted = false; @@ -34,7 +34,7 @@ public class Hotel implements Serializable { Double rating, City city, String address, - double latitude, + double lattitude, double longitude, boolean deleted) { this.id = id; @@ -42,7 +42,7 @@ public class Hotel implements Serializable { this.rating = rating; this.city = city; this.address = address; - this.latitude = latitude; + this.lattitude = lattitude; this.longitude = longitude; this.deleted = deleted; } @@ -88,11 +88,11 @@ public class Hotel implements Serializable { } public double getLatitude() { - return latitude; + return lattitude; } public void setLatitude(double latitude) { - this.latitude = latitude; + this.lattitude = latitude; } public double getLongitude() { @@ -118,7 +118,7 @@ public class Hotel implements Serializable { Hotel hotel = (Hotel) o; - if (Double.compare(hotel.latitude, latitude) != 0) return false; + if (Double.compare(hotel.lattitude, lattitude) != 0) return false; if (Double.compare(hotel.longitude, longitude) != 0) return false; if (deleted != hotel.deleted) return false; if (!Objects.equals(id, hotel.id)) return false; diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java similarity index 100% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java old mode 100755 new mode 100644 similarity index 67% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java index 6ce5ca9e76..1dee17d86f --- a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java @@ -16,13 +16,4 @@ public interface HotelRepository extends JpaRepository { } return findAll(); } - - default Optional getHotelById(Long hotelId) { - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - return findById(hotelId); - } } \ No newline at end of file diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/service/HotelService.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/HotelService.java old mode 100755 new mode 100644 similarity index 50% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/service/HotelService.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/HotelService.java index c69d371456..6e2b91b6ae --- a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/service/HotelService.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/HotelService.java @@ -1,8 +1,6 @@ package com.baeldung.caching.ttl.service; import com.baeldung.caching.ttl.repository.HotelRepository; -import com.baeldung.caching.ttl.config.GuavaCachingConfig; -import com.baeldung.caching.ttl.exception.ElementNotFoundException; import com.baeldung.caching.ttl.model.Hotel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -17,12 +15,10 @@ import java.util.List; public class HotelService { private final HotelRepository hotelRepository; - private final GuavaCachingConfig hotelGuavaCachingConfig; Logger logger = LoggerFactory.getLogger(HotelService.class); - HotelService(HotelRepository hotelRepository, GuavaCachingConfig hotelGuavaCachingConfig) { + HotelService(HotelRepository hotelRepository) { this.hotelRepository = hotelRepository; - this.hotelGuavaCachingConfig = hotelGuavaCachingConfig; } @Cacheable("hotels") @@ -36,17 +32,4 @@ public class HotelService { logger.info("emptying Hotels cache"); } - - public Hotel getHotelById(Long hotelId) { - if (hotelGuavaCachingConfig.get(hotelId) != null) { - logger.info(String.format("hotel with id: %s found in cache", hotelId)); - return hotelGuavaCachingConfig.get(hotelId); - } - logger.info(String.format("hotel with id: %s is being searched in DB", hotelId)); - Hotel hotel = hotelRepository.getHotelById(hotelId) - .orElseThrow(() -> new ElementNotFoundException(String.format("Hotel with id %s not found", hotelId))); - hotelGuavaCachingConfig.add(hotelId, hotel); - return hotel; - } - } \ No newline at end of file diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java similarity index 100% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java diff --git a/spring-caching-2/redis/src/main/resources/application.properties b/spring-boot-modules/spring-caching-2/src/main/resources/application.properties similarity index 78% rename from spring-caching-2/redis/src/main/resources/application.properties rename to spring-boot-modules/spring-caching-2/src/main/resources/application.properties index 080185b620..38f3537d01 100644 --- a/spring-caching-2/redis/src/main/resources/application.properties +++ b/spring-boot-modules/spring-caching-2/src/main/resources/application.properties @@ -2,11 +2,12 @@ spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= - # Enabling H2 Console spring.h2.console.enabled=true spring.h2.console.path=/h2 - +spring.jpa.hibernate.ddl-auto=update +#setting cache TTL +caching.spring.hotelListTTL=43200 # Connection details #spring.redis.host=localhost #spring.redis.port=6379 diff --git a/spring-boot-modules/spring-caching-2/src/main/resources/data.sql b/spring-boot-modules/spring-caching-2/src/main/resources/data.sql new file mode 100644 index 0000000000..027a8b5f01 --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/resources/data.sql @@ -0,0 +1,67 @@ +DROP TABLE IF EXISTS ITEM; +create table ITEM +( + ID CHARACTER VARYING not null, + DESCRIPTION CHARACTER VARYING, + constraint ITEM_PK + primary key (ID) +); +DROP TABLE IF EXISTS HOTEL; +DROP TABLE IF EXISTS CITY; +create table CITY +( + id bigint, + name varchar, + city_centre_lattitude double, + city_centre_longitude double, + constraint city_pk + primary key (id) +); +create table hotel +( + id bigint auto_increment, + name varchar, + deleted boolean, + rating double, + city_id bigint, + address varchar, + lattitude varchar, + longitude varchar, + constraint hotel_pk + primary key (id), + constraint "hotel_CITY_null_fk" + foreign key (city_id) references CITY (id) +); + + +INSERT INTO ITEM VALUES('abc','ITEM1'); + + +INSERT INTO city(id, name, city_centre_lattitude, city_centre_longitude) +VALUES (1, 'Amsterdam', 52.368780, 4.903303); +INSERT INTO city(id, name, city_centre_lattitude, city_centre_longitude) +VALUES (2, 'Manchester', 53.481062, -2.237706); + + +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('Monaghan Hotel', false, 9.2, 1, 'Weesperbuurt en Plantage', 52.364799, 4.908971); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('The Thornton Council Hotel', false, 6.3, 1, 'Waterlooplein', 52.3681563, 4.9010029); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('McZoe Trescothiks Hotel', false, 9.8, 1, 'Oude Stad, Harlem', 52.379577, 4.633547); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('Stay Schmtay Hotel', false, 8.7, 1, 'Jan van Galenstraat', 52.3756755, 4.8668628); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('Fitting Image Hotel', false, NULL, 1, 'Staatsliedenbuurt', 52.380936, 4.8708297); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('Raymond of Amsterdam Hotel', false, NULL, 1, '22 High Avenue', 52.3773989, 4.8846443); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('201 Deansgate Hotel', false, 7.3, 2, '201 Deansgate', 53.4788305, -2.2484721); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('Fountain Street Hotel', true, 3.0, 2, '35 Fountain Street', 53.4811298, -2.2402227); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('Sunlight House', false, 4.3, 2, 'Little Quay St', 53.4785129, -2.2505943); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('St Georges House', false, 9.6, 2, '56 Peter St', 53.477822, -2.2462002); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('Marriot Bonvoy', false, 9.6, 1, 'Hans Zimmerstraat', 53.477872, -2.2462003); \ No newline at end of file diff --git a/spring-caching-2/redis/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java similarity index 98% rename from spring-caching-2/redis/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java rename to spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java index 71a9729efd..291e729fb9 100644 --- a/spring-caching-2/redis/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java @@ -45,7 +45,7 @@ class ItemServiceCachingIntegrationTest { void givenRedisCaching_whenFindItemById_thenItemReturnedFromCache() { Item anItem = new Item(AN_ID, A_DESCRIPTION); given(mockItemRepository.findById(AN_ID)) - .willReturn(Optional.of(anItem)); + .willReturn(Optional.of(anItem)); Item itemCacheMiss = itemService.getItemForId(AN_ID); Item itemCacheHit = itemService.getItemForId(AN_ID); @@ -81,4 +81,4 @@ class ItemServiceCachingIntegrationTest { } } -} +} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/ttl/HotelControllerIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/ttl/HotelControllerIntegrationTest.java new file mode 100644 index 0000000000..f36c794361 --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/ttl/HotelControllerIntegrationTest.java @@ -0,0 +1,43 @@ +package com.baeldung.caching.ttl; + +import com.baeldung.caching.ttl.repository.HotelRepository; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; + +import static org.hamcrest.Matchers.hasSize; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@AutoConfigureMockMvc +@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:data.sql") +@SlowTest +class HotelControllerIntegrationTest { + @Autowired private MockMvc mockMvc; + @Autowired private HotelRepository repository; + + @Test + @DisplayName("When all hotels requested then request is successful") + void whenAllHotelsRequested_thenRequestIsSuccessful() throws Exception { + mockMvc + .perform(get("/hotel")) + .andExpect(status().isOk()); + } + + @Test + @DisplayName("When all hotels are requested then they correct number of hotels is returned") + void whenAllHotelsRequested_thenReturnAllHotels() throws Exception { + mockMvc + .perform(get("/hotel")) + .andExpect(jsonPath("$", hasSize((int) repository.findAll().stream().count()))); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/ttl/SlowTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/ttl/SlowTest.java new file mode 100644 index 0000000000..60e8abcd14 --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/ttl/SlowTest.java @@ -0,0 +1,4 @@ +package com.baeldung.caching.ttl; + +public @interface SlowTest { +} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/test/resources/application.properties b/spring-boot-modules/spring-caching-2/src/test/resources/application.properties new file mode 100644 index 0000000000..13fc375261 --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/test/resources/application.properties @@ -0,0 +1,15 @@ +spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= + +# Enabling H2 Console +spring.h2.console.enabled=true +spring.h2.console.path=/h2 +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=false +caching.spring.hotelListTTL=43200 +# Connection details +#spring.redis.host=localhost +#spring.redis.port=6379 +server.port=8000 \ No newline at end of file diff --git a/spring-caching/README.md b/spring-boot-modules/spring-caching/README.md similarity index 100% rename from spring-caching/README.md rename to spring-boot-modules/spring-caching/README.md diff --git a/spring-caching/pom.xml b/spring-boot-modules/spring-caching/pom.xml similarity index 90% rename from spring-caching/pom.xml rename to spring-boot-modules/spring-caching/pom.xml index 34c035a8ec..fa36b3af8b 100644 --- a/spring-caching/pom.xml +++ b/spring-boot-modules/spring-caching/pom.xml @@ -8,11 +8,10 @@ spring-caching war -- com.baeldung -parent-boot-2 -0.0.1-SNAPSHOT -../parent-boot-2 ++ com.baeldung.spring-boot-modules +spring-boot-modules +1.0.0-SNAPSHOT @@ -65,7 +64,7 @@ org.projectlombok lombok -1.18.12 +${lombok.version} org.springframework.boot @@ -79,6 +78,7 @@3.5.2 +1.18.26
- >(){}))
+ .willReturn(Mono.just(List.of(
+ new Book(1,"Book_1", "Author_1", 1998),
+ new Book(2, "Book_2", "Author_2", 1999)
+ )));
+
+ BooksService booksService = booksClient.getBooksService();
+ List
Hello, NOMO_NOMO
+ +User info:
+ +Attribute | +Value | +
---|---|
Name | +user.name | +
Class | +user.class | +
Principal Class | +user.principal.class | +
isAuthenticated? | +user.authenticated | +
clientRegistrationId | +user.authorizedClientregistrationId | +
Claim: key | +value | +
Granted Authority: | +authority | +
Baeldung Example for SAML 2.0 Login/Logout with Spring Security
+You are successfully logged in as
+User Identity Attributes
+Attribute | +Value | +
---|---|
+ | + |
Normal " + greeterService.greet() + "
Secure " + greeterService.greet() + "
+
Hello World!
- - diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/normal-webapp-servlet.xml b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/normal-webapp-servlet.xml deleted file mode 100644 index 8addbe3cf3..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/normal-webapp-servlet.xml +++ /dev/null @@ -1,16 +0,0 @@ --
This is the body of the sample view
- - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/scopesExample.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/scopesExample.jsp deleted file mode 100644 index e9abcf194c..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/scopesExample.jsp +++ /dev/null @@ -1,10 +0,0 @@ - - - - -Bean Scopes Examples
-Previous Message: ${previousMessage } -
Current Message: ${currentMessage } -
- - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/web-old.xml b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/web-old.xml deleted file mode 100644 index 1344362d19..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/web-old.xml +++ /dev/null @@ -1,88 +0,0 @@ -
Hello World!
- - diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java index f378357548..7fd8f0c97f 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java @@ -1,26 +1,24 @@ package com.baeldung.controller; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.baeldung.controller.config.WebConfig; -import com.baeldung.controller.student.Student; import org.junit.Assert; 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.AnnotationConfigWebContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class) +import com.baeldung.controller.student.Student; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ControllerAnnotationIntegrationTest { private MockMvc mockMvc; diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java index 7e5cf1532e..a7e6bd6c4b 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java @@ -5,9 +5,8 @@ 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.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -15,11 +14,11 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; import com.baeldung.controller.student.Student; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; import com.fasterxml.jackson.databind.ObjectMapper; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration({ "classpath:test-mvc.xml" }) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ControllerIntegrationTest { private MockMvc mockMvc; diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/GreetingsControllerUnitTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/GreetingsControllerUnitTest.java index ee9a8da8d4..4917d68ef4 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/GreetingsControllerUnitTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/GreetingsControllerUnitTest.java @@ -1,24 +1,21 @@ package com.baeldung.controller; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.baeldung.controller.controller.GreetingsController; import org.junit.Assert; 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.AnnotationConfigWebContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { GreetingsController.class }, loader = AnnotationConfigWebContextLoader.class) +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class GreetingsControllerUnitTest { private MockMvc mockMvc; diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java index aa8148c1ef..7408ae825d 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java @@ -5,24 +5,24 @@ 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.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + /** * This is the test class for {@link com.baeldung.controller.controller.PassParametersController} class. * 09/09/2017 * * @author Ahmet Cetin */ -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration({"classpath:test-mvc.xml"}) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class PassParametersControllerIntegrationTest { private MockMvc mockMvc; @@ -39,7 +39,7 @@ public class PassParametersControllerIntegrationTest { ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/showViewPage")).andReturn().getModelAndView(); //Validate view - Assert.assertEquals(mv.getViewName(), "viewPage"); + Assert.assertEquals(mv.getViewName(), "view/viewPage"); //Validate attribute Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung"); @@ -50,7 +50,7 @@ public class PassParametersControllerIntegrationTest { ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/printViewPage")).andReturn().getModelAndView(); //Validate view - Assert.assertEquals(mv.getViewName(), "viewPage"); + Assert.assertEquals(mv.getViewName(), "view/viewPage"); //Validate attribute Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung"); @@ -61,7 +61,7 @@ public class PassParametersControllerIntegrationTest { ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/goToViewPage")).andReturn().getModelAndView(); //Validate view - Assert.assertEquals(mv.getViewName(), "viewPage"); + Assert.assertEquals(mv.getViewName(), "view/viewPage"); //Validate attribute Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung"); diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/jsonparams/JsonParamsIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/jsonparams/JsonParamsIntegrationTest.java index bceadc4896..9d414ed4ca 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/jsonparams/JsonParamsIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/jsonparams/JsonParamsIntegrationTest.java @@ -1,26 +1,25 @@ package com.baeldung.jsonparams; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.AnnotationConfigWebContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; -import com.baeldung.jsonparams.config.JsonParamsConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { JsonParamsConfig.class }, loader = AnnotationConfigWebContextLoader.class) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class JsonParamsIntegrationTest { private MockMvc mockMvc; diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerIntegrationTest.java deleted file mode 100644 index 0e2313c2ac..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerIntegrationTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.optionalpathvars; - -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.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) -public class ArticleViewerControllerIntegrationTest { - - @Autowired - private WebApplicationContext wac; - - private MockMvc mockMvc; - - @Before - public void setup() throws Exception { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); - } - - @Test - public void whenIdPathVariableIsPassed_thenResponseOK() throws Exception { - - int articleId = 5; - - this.mockMvc - .perform(MockMvcRequestBuilders.get("/article/{id}", articleId)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId)); - - } - - @Test - public void whenIdPathVariableIsNotPassed_thenResponse500() throws Exception { - - this.mockMvc - .perform(MockMvcRequestBuilders.get("/article")) - .andExpect(MockMvcResultMatchers.status().isInternalServerError()); - - } - - -} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java index 094995ba67..2685946b4c 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java @@ -4,19 +4,18 @@ 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.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ArticleViewerControllerWithOptionalParamIntegrationTest { @Autowired diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java index a4b12c7163..e7d864d9be 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java @@ -12,42 +12,38 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) +@ContextConfiguration(classes = { SpringListValidationApplication.class }) public class ArticleViewerControllerWithRequiredAttributeIntegrationTest { @Autowired private WebApplicationContext wac; - + private MockMvc mockMvc; @Before - public void setup() throws Exception { + public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test - public void givenRequiredAttributeIsFalse_whenIdPathVariableIsPassed_thenResponseOK() throws Exception { - - int articleId = 154; + public void whenIdPathVariableIsPassed_thenResponseOK() throws Exception { + int articleId = 5; this.mockMvc .perform(MockMvcRequestBuilders.get("/requiredAttribute/article/{id}", articleId)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId)); - } - + @Test - public void givenRequiredAttributeIsFalse_whenIdPathVariableIsNotPassed_thenResponseOK() throws Exception { - + public void whenIdPathVariableIsNotPassed_thenResponseOK() throws Exception { this.mockMvc .perform(MockMvcRequestBuilders.get("/requiredAttribute/article")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(Article.DEFAULT_ARTICLE.getId())); - + .andExpect(MockMvcResultMatchers.status().isOk()); + } } \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java index 044a1c8bce..2be6d1e679 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java @@ -4,19 +4,18 @@ 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.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ArticleViewerWithMapParamIntegrationTest { @Autowired diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java index 1ca926277d..e70ac5e5a6 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java @@ -4,19 +4,18 @@ 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.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ArticleViewerWithTwoSeparateMethodsIntegrationTest { @Autowired diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java index cddc6c6bd9..14ceb651d7 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java @@ -34,7 +34,7 @@ public class MovieControllerIntegrationTest { Movie movie = new Movie("Movie3"); movies.add(movie); mvc.perform(MockMvcRequestBuilders.post("/movies") - .contentType(MediaType.APPLICATION_JSON_UTF8) + .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(movies))) .andExpect(MockMvcResultMatchers.status() .isOk()); @@ -44,7 +44,7 @@ public class MovieControllerIntegrationTest { public void givenEmptyMovieList_whenAddingMovieList_thenThrowBadRequest() throws Exception { ListForm
+ + + + + diff --git a/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates-3/index.html b/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates-3/index.html new file mode 100644 index 0000000000..4928b50df0 --- /dev/null +++ b/spring-web-modules/spring-thymeleaf-5/src/main/resources/templates-3/index.html @@ -0,0 +1,29 @@ + + + ++
+
+
+
Copyright 2022
++
Result
+ + + Submit Another Dino + Baeldung Home + + + + + diff --git a/spring-web-modules/spring-web-url/README.md b/spring-web-modules/spring-web-url/README.md index 41b479337b..79a89f4386 100644 --- a/spring-web-modules/spring-web-url/README.md +++ b/spring-web-modules/spring-web-url/README.md @@ -6,3 +6,4 @@ This module contains articles about Spring MVC - [Using a Slash Character in Spring URLs](https://www.baeldung.com/spring-slash-character-in-url) - [Excluding URLs for a Filter in a Spring Web Application](https://www.baeldung.com/spring-exclude-filter) - [Handling URL Encoded Form Data in Spring REST](https://www.baeldung.com/spring-url-encoded-form-data) +- [Spring MVC – Mapping the Root URL to a Page](https://www.baeldung.com/spring-mvc-map-root-url) diff --git a/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/RootMappingApplication.java b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/RootMappingApplication.java new file mode 100644 index 0000000000..f64753fa36 --- /dev/null +++ b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/RootMappingApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.rootmapping; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +@SpringBootApplication +@EnableWebMvc +public class RootMappingApplication { + + public static void main(String[] args) { + SpringApplication.run(RootMappingApplication.class, args); + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/config/WebConfig.java b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/config/WebConfig.java new file mode 100644 index 0000000000..ba15bc992c --- /dev/null +++ b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/config/WebConfig.java @@ -0,0 +1,13 @@ +package com.baeldung.rootmapping.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("index"); + } +} diff --git a/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/controller/RootController.java b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/controller/RootController.java new file mode 100644 index 0000000000..7724e43e71 --- /dev/null +++ b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/controller/RootController.java @@ -0,0 +1,12 @@ +package com.baeldung.rootmapping.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class RootController { + @GetMapping("/") + public String index() { + return "index"; + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-web-url/src/main/resources/templates/index.html b/spring-web-modules/spring-web-url/src/main/resources/templates/index.html new file mode 100644 index 0000000000..acfb847868 --- /dev/null +++ b/spring-web-modules/spring-web-url/src/main/resources/templates/index.html @@ -0,0 +1,10 @@ + + + + +Hello World!
+ + \ No newline at end of file diff --git a/struts/README.md b/struts/README.md deleted file mode 100644 index d15b94f662..0000000000 --- a/struts/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Struts 2 - -This module contains articles about Struts 2 - -### Relevant articles - -- [A Quick Struts 2 Intro](https://www.baeldung.com/struts-2-intro) diff --git a/struts/WebContent/WEB-INF/web.xml b/struts/WebContent/WEB-INF/web.xml deleted file mode 100644 index 8f1b55943c..0000000000 --- a/struts/WebContent/WEB-INF/web.xml +++ /dev/null @@ -1,12 +0,0 @@ - -Hello Baeldung User
-You are a
Note: using {@link InstancioExtension} is optional. The extension adds support for: + *
+ * - reporting seed value if a test fails
+ * - {@link Seed} annotation for reproducing failed tests
+ * - {@link WithSettings} for injecting custom settings, if needed
+ */
+@ExtendWith(InstancioExtension.class)
+class CreateStudentUnitTest {
+
+ /**
+ * Common settings to be used by all test methods.
+ */
+ @WithSettings
+ private static final Settings settings = Settings.create()
+ .set(Keys.COLLECTION_MAX_SIZE, 3);
+
+ /**
+ * A {@link Model} is a template for creating objects.
+ * Objects created from a model can be created as is, or customized, if needed.
+ */
+ private static Model Sample error message generated by {@link InstancioExtension}:
+ *
+ *
+ * Using the reported seed value we can reproduce the test failure.
+ */
+ @Test
+ @Seed(1234)
+ @Disabled("This test fails on purpose to demonstrate failure reporting by InstancioExtension")
+ void whenGivenNoFailingGrades_thenShouldEnrollStudentInCourse() {
+ // Given
+ Course course = Instancio.create(Course.class);
+ Student student = Instancio.of(Student.class)
+ // The test can be fixed by uncommenting the line below:
+ //.generate(all(Grade.class), gen -> gen.enumOf(Grade.class).excluding(Grade.F))
+ .create();
+
+ System.out.println(student); // same data generated on each run
+
+ // When
+ boolean isEnrolled = enrollmentService.enrollStudent(student, course);
+
+ // Then
+ assertThat(isEnrolled).isTrue();
+ }
+}
diff --git a/testing-modules/instancio/src/test/java/com/baeldung/instancio/selectors/SelectorScopesUnitTest.java b/testing-modules/instancio/src/test/java/com/baeldung/instancio/selectors/SelectorScopesUnitTest.java
new file mode 100644
index 0000000000..683b510f0c
--- /dev/null
+++ b/testing-modules/instancio/src/test/java/com/baeldung/instancio/selectors/SelectorScopesUnitTest.java
@@ -0,0 +1,76 @@
+package com.baeldung.instancio.selectors;
+
+import com.baeldung.instancio.student.model.ContactInfo;
+import com.baeldung.instancio.student.model.EmergencyContact;
+import com.baeldung.instancio.student.model.Phone;
+import com.baeldung.instancio.student.model.Student;
+import org.instancio.Instancio;
+import org.instancio.Scope;
+import org.instancio.Select;
+import org.instancio.TargetSelector;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.instancio.Select.allStrings;
+import static org.instancio.Select.scope;
+
+/**
+ * Examples of various selector {@link Scope}.
+ * Scopes allow narrowing down selector targets.
+ */
+class SelectorScopesUnitTest {
+
+ /**
+ * Prefix all String fields in Phone class with "phone_".
+ */
+ @Test
+ void whenGivenClassScope_shouldSelectTargetsWithinClass() {
+ // Given
+ final String prefix = "phone_";
+ final Scope phoneClass = scope(Phone.class);
+
+ // When
+ Student student = Instancio.of(Student.class)
+ .generate(allStrings().within(phoneClass), gen -> gen.string().prefix(prefix))
+ .create();
+
+ // Then
+
+ // matches phone numbers
+ Phone emergencyContactPhone = student.getEmergencyContact().getPhone();
+ assertThat(emergencyContactPhone.getCountryCode()).startsWith(prefix);
+ assertThat(emergencyContactPhone.getNumber()).startsWith(prefix);
+ assertThat(student.getContactInfo().getPhones()).allSatisfy(phone -> {
+ assertThat(phone.getCountryCode()).startsWith(prefix);
+ assertThat(phone.getNumber()).startsWith(prefix);
+ });
+
+ // does not match other fields
+ assertThat(student.getContactInfo().getAddress().getCity()).doesNotStartWith(prefix);
+ }
+
+ /**
+ * Using scope to set student's and their emergency contact's
+ * phone number to different values.
+ */
+ @Test
+ void whenGivenFieldScope_shouldSelectTargetsWithinField() {
+ // Given
+ TargetSelector studentPhone = Select.field(Phone::getNumber).within(scope(ContactInfo.class));
+ TargetSelector emergencyPhone = Select.field(Phone::getNumber).within(scope(EmergencyContact.class));
+
+ // When
+ Student student = Instancio.of(Student.class)
+ .set(studentPhone, "student")
+ .set(emergencyPhone, "emergency")
+ .create();
+
+ // Then
+ assertThat(student.getContactInfo().getPhones())
+ .isNotEmpty()
+ .allSatisfy(phone -> assertThat(phone.getNumber()).isEqualTo("student"));
+
+ assertThat(student.getEmergencyContact().getPhone().getNumber())
+ .isEqualTo("emergency");
+ }
+}
diff --git a/testing-modules/instancio/src/test/java/com/baeldung/instancio/selectors/SelectorsUnitTest.java b/testing-modules/instancio/src/test/java/com/baeldung/instancio/selectors/SelectorsUnitTest.java
new file mode 100644
index 0000000000..fe6b9cc3f4
--- /dev/null
+++ b/testing-modules/instancio/src/test/java/com/baeldung/instancio/selectors/SelectorsUnitTest.java
@@ -0,0 +1,104 @@
+package com.baeldung.instancio.selectors;
+
+import com.baeldung.instancio.student.model.Address;
+import com.baeldung.instancio.student.model.ContactInfo;
+import com.baeldung.instancio.student.model.Phone;
+import com.baeldung.instancio.student.model.Student;
+import org.instancio.FieldSelectorBuilder;
+import org.instancio.Instancio;
+import org.instancio.Select;
+import org.instancio.Selector;
+import org.instancio.SelectorGroup;
+import org.instancio.TargetSelector;
+import org.junit.jupiter.api.Test;
+
+import java.util.Collection;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.instancio.Select.all;
+import static org.instancio.Select.field;
+import static org.instancio.Select.fields;
+import static org.instancio.Select.types;
+
+/**
+ * Examples of various types of selectors provided by the {@link Select} class.
+ */
+class SelectorsUnitTest {
+
+ @Test
+ void whenGivenFieldSelector_shouldCustomizeSelectedField() {
+ Address address = Instancio.of(Address.class)
+ .set(field(Address::getCity), "London")
+ .set(field(Address.class, "country"), "UK")
+ .create();
+
+ assertThat(address.getCity()).isEqualTo("London");
+ assertThat(address.getCountry()).isEqualTo("UK");
+ }
+
+ @Test
+ void whenGivenClassSelector_shouldCustomizeSelectedClass() {
+ // Given
+ final Selector allStrings = all(String.class);
+ final String prefix = "test_";
+
+ // When
+ Address address = Instancio.of(Address.class)
+ .generate(allStrings, gen -> gen.string().prefix(prefix))
+ .create();
+
+ // Then
+ assertThat(address.getCity()).startsWith(prefix);
+ assertThat(address.getCountry()).startsWith(prefix);
+ }
+
+ @Test
+ void whenGivenPredicateFieldSelector_shouldCustomizeMatchingFields() {
+ // Given: regie matching 'city' and 'country' fields
+ final FieldSelectorBuilder fieldsMatchingRegex = fields().matching("c.*y");
+
+ // When
+ Address address = Instancio.of(Address.class)
+ .ignore(fieldsMatchingRegex)
+ .create();
+
+ // Then
+ assertThat(address.getCity()).isNull();
+ assertThat(address.getCountry()).isNull();
+ assertThat(address.getStreet()).isNotBlank();
+ }
+
+ @Test
+ void whenGivenPredicateClassSelector_shouldCustomizeMatchingClasses() {
+ // Given
+ final TargetSelector allTypesOfCollections = types().of(Collection.class);
+ final int size = 3;
+
+ // When
+ ContactInfo contactInfo = Instancio.of(ContactInfo.class)
+ .generate(allTypesOfCollections, gen -> gen.collection().size(size))
+ .create();
+
+ // Then
+ List Float range was overridden to [0, 100].
+ * See: {@code src/test/resources/instancio.properties}
+ */
+ @Test
+ void whenInstancioPropertiesAreOnClasspath_shouldUseConfiguredProperties() {
+ Set>() {});
+
+ assertThat(list).isNotEmpty().doesNotContainNull();
+ }
+
+ @Test
+ void whenGivenTypeToken_shouldCreateMap() {
+ Map
>>>() {});
+
+ assertThat(list)
+ .isNotEmpty()
+ .allSatisfy(triplet -> {
+ assertThat(triplet.getLeft()).isInstanceOf(Integer.class);
+ assertThat(triplet.getMiddle()).isInstanceOf(LocalDate.class);
+ assertThat(triplet.getRight())
+ .isInstanceOf(Item.class)
+ .satisfies(item -> assertThat(item.getValue()).isNotBlank());
+ });
+
+ // Sample output
+ list.forEach(System.out::println);
+ }
+
+
+ /**
+ * Alternative way to create generic objects is using 'withTypeParameters'.
+ * However, this approach generates an "unchecked assignment" warning.
+ */
+ @Test
+ @SuppressWarnings("unchecked")
+ void whenGivenClassWithTypeParameters_shouldCreateGenericType() {
+ Map
+ * timestamp = 2023-01-24T13:50:12.436704221, Instancio = Test method 'enrollStudent' failed with seed: 1234
+ *
+ *