From 369f73e7b38a214ed4337604b732d0879dfa7c4e Mon Sep 17 00:00:00 2001 From: "m.raheem" Date: Sun, 15 Sep 2019 00:32:01 +0200 Subject: [PATCH 01/38] enum deserialization --- .../com/baeldung/jackson/entities/City.java | 22 ++++++++++ .../com/baeldung/jackson/enums/Distance.java | 38 +++++++++++++--- .../JacksonEnumSerializationUnitTest.java | 43 ++++++++++++++++++- 3 files changed, 95 insertions(+), 8 deletions(-) create mode 100644 jackson/src/main/java/com/baeldung/jackson/entities/City.java diff --git a/jackson/src/main/java/com/baeldung/jackson/entities/City.java b/jackson/src/main/java/com/baeldung/jackson/entities/City.java new file mode 100644 index 0000000000..d4c5d715de --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/entities/City.java @@ -0,0 +1,22 @@ +package com.baeldung.jackson.entities; + +import com.baeldung.jackson.enums.Distance; + +public class City { + + private Distance distance; + + public Distance getDistance() { + return distance; + } + + public void setDistance(Distance distance) { + this.distance = distance; + } + + @Override + public String toString() { + return "City [distance=" + distance + "]"; + } + +} diff --git a/jackson/src/main/java/com/baeldung/jackson/enums/Distance.java b/jackson/src/main/java/com/baeldung/jackson/enums/Distance.java index 8026eedc44..fdda32d16c 100644 --- a/jackson/src/main/java/com/baeldung/jackson/enums/Distance.java +++ b/jackson/src/main/java/com/baeldung/jackson/enums/Distance.java @@ -1,20 +1,29 @@ package com.baeldung.jackson.enums; import com.baeldung.jackson.serialization.DistanceSerializer; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * Use @JsonFormat to handle representation of Enum as JSON (available since Jackson 2.1.2) * Use @JsonSerialize to configure a custom Jackson serializer */ -// @JsonFormat(shape = JsonFormat.Shape.OBJECT) -@JsonSerialize(using = DistanceSerializer.class) +@JsonFormat(shape = JsonFormat.Shape.OBJECT) +//@JsonSerialize(using = DistanceSerializer.class) public enum Distance { - KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); + @JsonProperty("distance-in-km") + KILOMETER("km", 1000), + @JsonProperty("distance-in-miles") + MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), + MILLIMETER("mm", 0.001); private String unit; private final double meters; - + private Distance(String unit, double meters) { this.unit = unit; this.meters = meters; @@ -23,11 +32,11 @@ public enum Distance { /** * Use @JsonValue to control marshalling output for an enum */ - // @JsonValue +// @JsonValue public double getMeters() { return meters; } - + public String getUnit() { return unit; } @@ -35,7 +44,7 @@ public enum Distance { public void setUnit(String unit) { this.unit = unit; } - + /** * Usage example: Distance.MILE.convertFromMeters(1205.5); */ @@ -51,4 +60,19 @@ public enum Distance { return distanceInMeters * meters; } +// @JsonCreator + public static Distance forValues(@JsonProperty("unit") String unit, @JsonProperty("meters") double meters) { + + for (Distance distance : Distance.values()) { + if (distance.unit.equals(unit) + && Double.compare(distance.meters, meters) == 0) { + + return distance; + } + } + + return null; + + } + } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationUnitTest.java index 45c0ba1382..3108773a00 100644 --- a/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationUnitTest.java @@ -1,13 +1,17 @@ package com.baeldung.jackson.enums; import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; - +import org.junit.Ignore; import org.junit.Test; +import com.baeldung.jackson.entities.City; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonEnumSerializationUnitTest { @@ -19,4 +23,41 @@ public class JacksonEnumSerializationUnitTest { assertThat(dtoAsString, containsString("1609.34")); } + @Test + @Ignore + public final void givenEnum_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + String json = "{\"distance\":\"KILOMETER\"}"; + City city = new ObjectMapper().readValue(json, City.class); + + assertEquals(Distance.KILOMETER, city.getDistance()); + } + + @Test + @Ignore + public final void givenEnumWithJsonValue_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + String json = "{\"JacksonDeserializationUnitTestdistance\": \"0.0254\"}"; + + City city = new ObjectMapper().readValue(json, City.class); + assertEquals(Distance.INCH, city.getDistance()); + } + + @Test + public final void givenEnumWithGsonProperty_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + String json = "{\"distance\": \"distance-in-km\"}"; + + City city = new ObjectMapper().readValue(json, City.class); + assertEquals(Distance.KILOMETER, city.getDistance()); + + } + + @Test + @Ignore + public final void givenEnumWithGsonCreator_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + String json = "{\"distance\": {\"unit\":\"miles\",\"meters\":1609.34}}"; + + City city = new ObjectMapper().readValue(json, City.class); + assertEquals(Distance.MILE, city.getDistance()); + System.out.println(city); + } + } From 9a456ba4f1d1c62819d8712fd35fd751e606f4ec Mon Sep 17 00:00:00 2001 From: Kamlesh Kumar Date: Sat, 28 Sep 2019 10:39:34 +0530 Subject: [PATCH 02/38] BAEL-1363 Fallback for Zuul Routes --- spring-cloud/pom.xml | 7 +- .../spring-cloud-zuul-fallback/README.md | 2 + .../api-gateway/pom.xml | 43 ++++++++++++ .../apigateway/ApiGatewayApplication.java | 15 ++++ .../fallback/GatewayClientResponse.java | 69 +++++++++++++++++++ .../fallback/GatewayServiceFallback.java | 29 ++++++++ .../fallback/WeatherServiceFallback.java | 29 ++++++++ .../src/main/resources/application.yml | 22 ++++++ .../ApiGatewayApplicationIntegrationTest.java | 16 +++++ .../GatewayServiceFallbackUnitTest.java | 46 +++++++++++++ .../WeatherServiceFallbackUnitTest.java | 46 +++++++++++++ .../spring-cloud-zuul-fallback/pom.xml | 28 ++++++++ .../weather-service/pom.xml | 39 +++++++++++ .../weatherservice/WeatherController.java | 16 +++++ .../WeatherServiceApplication.java | 13 ++++ .../src/main/resources/application.yml | 5 ++ .../WeatherControllerIntegrationTest.java | 31 +++++++++ ...therServiceApplicationIntegrationTest.java | 16 +++++ 18 files changed, 469 insertions(+), 3 deletions(-) create mode 100644 spring-cloud/spring-cloud-zuul-fallback/README.md create mode 100644 spring-cloud/spring-cloud-zuul-fallback/api-gateway/pom.xml create mode 100644 spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/ApiGatewayApplication.java create mode 100644 spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayClientResponse.java create mode 100644 spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayServiceFallback.java create mode 100644 spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/WeatherServiceFallback.java create mode 100644 spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/resources/application.yml create mode 100644 spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/ApiGatewayApplicationIntegrationTest.java create mode 100644 spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayServiceFallbackUnitTest.java create mode 100644 spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/fallback/WeatherServiceFallbackUnitTest.java create mode 100644 spring-cloud/spring-cloud-zuul-fallback/pom.xml create mode 100644 spring-cloud/spring-cloud-zuul-fallback/weather-service/pom.xml create mode 100644 spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/java/com/baeldung/spring/cloud/weatherservice/WeatherController.java create mode 100644 spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/java/com/baeldung/spring/cloud/weatherservice/WeatherServiceApplication.java create mode 100644 spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/resources/application.yml create mode 100644 spring-cloud/spring-cloud-zuul-fallback/weather-service/src/test/java/com/baeldung/spring/cloud/weatherservice/WeatherControllerIntegrationTest.java create mode 100644 spring-cloud/spring-cloud-zuul-fallback/weather-service/src/test/java/com/baeldung/spring/cloud/weatherservice/WeatherServiceApplicationIntegrationTest.java diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index baf86a4386..7138efc128 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -25,7 +25,7 @@ spring-cloud-zookeeper spring-cloud-gateway spring-cloud-stream - spring-cloud-stream-starters/twitterhdfs + spring-cloud-stream-starters/twitterhdfs spring-cloud-connectors-heroku spring-cloud-aws spring-cloud-consul @@ -35,9 +35,10 @@ spring-cloud-archaius spring-cloud-functions spring-cloud-vault - - spring-cloud-task + + spring-cloud-task spring-cloud-zuul + spring-cloud-zuul-fallback diff --git a/spring-cloud/spring-cloud-zuul-fallback/README.md b/spring-cloud/spring-cloud-zuul-fallback/README.md new file mode 100644 index 0000000000..2f13c1923b --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Fallback for Zuul Route](TODO) diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/pom.xml b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/pom.xml new file mode 100644 index 0000000000..ee0f607d8a --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + api-gateway + api-gateway + API Gateway using Zuul + jar + + + com.baeldung.spring.cloud + spring-cloud-zuul-fallback + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-netflix-zuul + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-starter-parent + ${spring-cloud-dependencies.version} + pom + import + + + + diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/ApiGatewayApplication.java b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/ApiGatewayApplication.java new file mode 100644 index 0000000000..78f489f2bb --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/ApiGatewayApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.apigateway; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.zuul.EnableZuulProxy; + +@SpringBootApplication +@EnableZuulProxy +public class ApiGatewayApplication { + + public static void main(String[] args) { + SpringApplication.run(ApiGatewayApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayClientResponse.java b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayClientResponse.java new file mode 100644 index 0000000000..ce0c7819f1 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayClientResponse.java @@ -0,0 +1,69 @@ +package com.baeldung.spring.cloud.apigateway.fallback; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.client.ClientHttpResponse; + +public class GatewayClientResponse implements ClientHttpResponse { + + private HttpStatus status; + private String message; + + public GatewayClientResponse(HttpStatus status, String message) { + this.status = status; + this.message = message; + } + + @Override + public HttpStatus getStatusCode() throws IOException { + return status; + } + + @Override + public int getRawStatusCode() throws IOException { + return status.value(); + } + + @Override + public String getStatusText() throws IOException { + return status.getReasonPhrase(); + } + + @Override + public void close() { + } + + @Override + public InputStream getBody() throws IOException { + return new ByteArrayInputStream(message.getBytes()); + } + + @Override + public HttpHeaders getHeaders() { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + return headers; + } + + public HttpStatus getStatus() { + return status; + } + + public void setStatus(HttpStatus status) { + this.status = status; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayServiceFallback.java b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayServiceFallback.java new file mode 100644 index 0000000000..73f72492c9 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayServiceFallback.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.cloud.apigateway.fallback; + +import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.stereotype.Component; + +import com.netflix.hystrix.exception.HystrixTimeoutException; + +@Component +class GatewayServiceFallback implements FallbackProvider { + + private static final String DEFAULT_MESSAGE = "Service not available."; + + @Override + public String getRoute() { + return "*"; // or return null; + } + + @Override + public ClientHttpResponse fallbackResponse(String route, Throwable cause) { + if (cause instanceof HystrixTimeoutException) { + return new GatewayClientResponse(HttpStatus.GATEWAY_TIMEOUT, DEFAULT_MESSAGE); + } else { + return new GatewayClientResponse(HttpStatus.INTERNAL_SERVER_ERROR, DEFAULT_MESSAGE); + } + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/WeatherServiceFallback.java b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/WeatherServiceFallback.java new file mode 100644 index 0000000000..28fb6fb6e5 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/WeatherServiceFallback.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.cloud.apigateway.fallback; + +import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.stereotype.Component; + +import com.netflix.hystrix.exception.HystrixTimeoutException; + +@Component +class WeatherServiceFallback implements FallbackProvider { + + private static final String DEFAULT_MESSAGE = "Weather information is not available."; + + @Override + public String getRoute() { + return "weather-service"; + } + + @Override + public ClientHttpResponse fallbackResponse(String route, Throwable cause) { + if (cause instanceof HystrixTimeoutException) { + return new GatewayClientResponse(HttpStatus.GATEWAY_TIMEOUT, DEFAULT_MESSAGE); + } else { + return new GatewayClientResponse(HttpStatus.INTERNAL_SERVER_ERROR, DEFAULT_MESSAGE); + } + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/resources/application.yml b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/resources/application.yml new file mode 100644 index 0000000000..9a7d3314a3 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/resources/application.yml @@ -0,0 +1,22 @@ +spring: + application: + name: api-gateway +server: + port: 8008 + +zuul: + igoredServices: '*' + routes: + weather-service: + path: /weather/** + serviceId: weather-service + strip-prefix: false + +ribbon: + eureka: + enabled: false + +weather-service: + ribbon: + listOfServers: localhost:7070 + diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/ApiGatewayApplicationIntegrationTest.java b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/ApiGatewayApplicationIntegrationTest.java new file mode 100644 index 0000000000..4052edc1f3 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/ApiGatewayApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.apigateway; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApiGatewayApplicationIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayServiceFallbackUnitTest.java b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayServiceFallbackUnitTest.java new file mode 100644 index 0000000000..db2f703084 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayServiceFallbackUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.cloud.apigateway.fallback; + +import static org.junit.Assert.assertEquals; + +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.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.test.context.junit4.SpringRunner; + +import com.netflix.hystrix.exception.HystrixTimeoutException; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class GatewayServiceFallbackUnitTest { + + private static final String ROUTE = "*"; + + @Autowired + private GatewayServiceFallback fallback; + + @Test + public void testWhenGetRouteThenReturnWeatherServiceRoute() { + assertEquals(ROUTE, fallback.getRoute()); + + } + + @Test + public void testFallbackResponse_whenHystrixException_thenGatewayTimeout() throws Exception { + HystrixTimeoutException exception = new HystrixTimeoutException(); + ClientHttpResponse response = fallback.fallbackResponse(ROUTE, exception); + + assertEquals(HttpStatus.GATEWAY_TIMEOUT, response.getStatusCode()); + } + + @Test + public void testFallbackResponse_whenNonHystrixException_thenInternalServerError() throws Exception { + RuntimeException exception = new RuntimeException("Test exception"); + ClientHttpResponse response = fallback.fallbackResponse(ROUTE, exception); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/fallback/WeatherServiceFallbackUnitTest.java b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/fallback/WeatherServiceFallbackUnitTest.java new file mode 100644 index 0000000000..ccd59531b5 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/fallback/WeatherServiceFallbackUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.cloud.apigateway.fallback; + +import static org.junit.Assert.assertEquals; + +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.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.test.context.junit4.SpringRunner; + +import com.netflix.hystrix.exception.HystrixTimeoutException; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class WeatherServiceFallbackUnitTest { + + private static final String ROUTE = "weather-service"; + + @Autowired + private WeatherServiceFallback fallback; + + @Test + public void testWhenGetRouteThenReturnWeatherServiceRoute() { + assertEquals(ROUTE, fallback.getRoute()); + + } + + @Test + public void testFallbackResponse_whenHystrixException_thenGatewayTimeout() throws Exception { + HystrixTimeoutException exception = new HystrixTimeoutException(); + ClientHttpResponse response = fallback.fallbackResponse(ROUTE, exception); + + assertEquals(HttpStatus.GATEWAY_TIMEOUT, response.getStatusCode()); + } + + @Test + public void testFallbackResponse_whenNonHystrixException_thenInternalServerError() throws Exception { + RuntimeException exception = new RuntimeException("Test exception"); + ClientHttpResponse response = fallback.fallbackResponse(ROUTE, exception); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/pom.xml b/spring-cloud/spring-cloud-zuul-fallback/pom.xml new file mode 100644 index 0000000000..5bdd1d49ca --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + spring-cloud-zuul-fallback + pom + spring-cloud-zuul-fallback + Spring Cloud Zuul Fallback + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + .. + + + + api-gateway + weather-service + + + + 1.8 + Finchley.SR2 + 3.1.1 + + diff --git a/spring-cloud/spring-cloud-zuul-fallback/weather-service/pom.xml b/spring-cloud/spring-cloud-zuul-fallback/weather-service/pom.xml new file mode 100644 index 0000000000..611f1dcd4f --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/weather-service/pom.xml @@ -0,0 +1,39 @@ + + 4.0.0 + weather-service + Weather Service + Weather Service for Zuul Fallback Test + + + com.baeldung.spring.cloud + spring-cloud-zuul-fallback + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-starter-parent + ${spring-cloud-dependencies.version} + pom + import + + + + diff --git a/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/java/com/baeldung/spring/cloud/weatherservice/WeatherController.java b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/java/com/baeldung/spring/cloud/weatherservice/WeatherController.java new file mode 100644 index 0000000000..3cf451dcf7 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/java/com/baeldung/spring/cloud/weatherservice/WeatherController.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.weatherservice; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/weather") +public class WeatherController { + + @GetMapping("/today") + public String getMessage() { + return "It's a bright sunny day today!"; + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/java/com/baeldung/spring/cloud/weatherservice/WeatherServiceApplication.java b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/java/com/baeldung/spring/cloud/weatherservice/WeatherServiceApplication.java new file mode 100644 index 0000000000..3a6d85e8d1 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/java/com/baeldung/spring/cloud/weatherservice/WeatherServiceApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.weatherservice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class WeatherServiceApplication { + + public static void main(String[] args) { + SpringApplication.run(WeatherServiceApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/resources/application.yml b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/resources/application.yml new file mode 100644 index 0000000000..30ceeee438 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/resources/application.yml @@ -0,0 +1,5 @@ +spring: + application: + name: weather-service +server: + port: 7070 diff --git a/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/test/java/com/baeldung/spring/cloud/weatherservice/WeatherControllerIntegrationTest.java b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/test/java/com/baeldung/spring/cloud/weatherservice/WeatherControllerIntegrationTest.java new file mode 100644 index 0000000000..3ffd2b0e7a --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/test/java/com/baeldung/spring/cloud/weatherservice/WeatherControllerIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.spring.cloud.weatherservice; + +import static org.hamcrest.Matchers.containsString; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +@RunWith(SpringRunner.class) +@WebMvcTest(WeatherController.class) +public class WeatherControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenWeatherControllerInvoked_thenReturnWeatherInformation() throws Exception { + this.mockMvc.perform(get("/weather/today")) + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("bright sunny day"))); + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/test/java/com/baeldung/spring/cloud/weatherservice/WeatherServiceApplicationIntegrationTest.java b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/test/java/com/baeldung/spring/cloud/weatherservice/WeatherServiceApplicationIntegrationTest.java new file mode 100644 index 0000000000..fec7ec1560 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/test/java/com/baeldung/spring/cloud/weatherservice/WeatherServiceApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.weatherservice; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class WeatherServiceApplicationIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} From 779ae2f7a3134f2cc7d26761e790bad295956408 Mon Sep 17 00:00:00 2001 From: maryarm Date: Fri, 4 Oct 2019 15:44:46 +0330 Subject: [PATCH 03/38] #BAEL-3228: Unit tests for Transaction Propagation and Isolation in Spring @Transactional --- .../FooTransactionalUnitTest.java | 250 ++++++++++++++++++ .../PersistenceTransactionalTestConfig.java | 148 +++++++++++ 2 files changed, 398 insertions(+) create mode 100644 persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java create mode 100644 persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java new file mode 100644 index 0000000000..6f2a499bc5 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java @@ -0,0 +1,250 @@ +package com.baeldung.persistence.service.transactional; + +import com.baeldung.persistence.model.Foo; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import org.junit.After; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.stereotype.Service; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.transaction.IllegalTransactionStateException; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionTemplate; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceTransactionalTestConfig.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext +public class FooTransactionalUnitTest { + + static abstract class BasicFooDao { + @PersistenceContext private EntityManager entityManager; + + public Foo findOne(final long id) { + return entityManager.find(Foo.class, id); + } + + public Foo create(final Foo entity) { + entityManager.persist(entity); + return entity; + } + } + + @Repository + static class RequiredTransactionalFooDao extends BasicFooDao { + @Override + @Transactional(propagation = Propagation.REQUIRED) + public Foo create(Foo entity) { + return super.create(entity); + } + } + + @Repository + static class RequiresNewTransactionalFooDao extends BasicFooDao { + @Override + @Transactional(propagation = Propagation.REQUIRES_NEW) + public Foo create(Foo entity) { + return super.create(entity); + } + } + + @Repository + static class SupportTransactionalFooDao extends BasicFooDao { + @Override + @Transactional(propagation = Propagation.SUPPORTS) + public Foo create(Foo entity) { + return super.create(entity); + } + } + + @Repository + static class MandatoryTransactionalFooDao extends BasicFooDao { + @Override + @Transactional(propagation = Propagation.MANDATORY) + public Foo create(Foo entity) { + return super.create(entity); + } + } + + @Repository + static class SupportTransactionalFooService { + @Transactional(propagation = Propagation.SUPPORTS) + public Foo identity(Foo entity) { + return entity; + } + } + + @Service + static class MandatoryTransactionalFooService { + @Transactional(propagation = Propagation.MANDATORY) + public Foo identity(Foo entity) { + return entity; + } + } + + @Service + static class NotSupportedTransactionalFooService { + @Transactional(propagation = Propagation.NOT_SUPPORTED) + public Foo identity(Foo entity) { + return entity; + } + } + + @Service + static class NeverTransactionalFooService { + @Transactional(propagation = Propagation.NEVER) + public Foo identity(Foo entity) { + return entity; + } + } + + @Autowired private TransactionTemplate transactionTemplate; + + @Autowired private RequiredTransactionalFooDao requiredTransactionalFooDao; + + @Autowired private RequiresNewTransactionalFooDao requiresNewTransactionalFooDao; + + @Autowired private SupportTransactionalFooDao supportTransactionalFooDao; + + @Autowired private MandatoryTransactionalFooDao mandatoryTransactionalFooDao; + + @Autowired private MandatoryTransactionalFooService mandatoryTransactionalFooService; + + @Autowired private NeverTransactionalFooService neverTransactionalFooService; + + @Autowired private NotSupportedTransactionalFooService notSupportedTransactionalFooService; + + @Autowired private SupportTransactionalFooService supportTransactionalFooService; + + @After + public void tearDown(){ + PersistenceTransactionalTestConfig.clearSpy(); + } + + @Test + public void givenRequiredWithNoActiveTransaction_whenCallCreate_thenExpect1NewAnd0Suspend() { + requiredTransactionalFooDao.create(new Foo("baeldung")); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(1, transactionSpy.getCreate()); + } + + + + @Test + public void givenRequiresNewWithNoActiveTransaction_whenCallCreate_thenExpect1NewAnd0Suspend() { + requiresNewTransactionalFooDao.create(new Foo("baeldung")); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(1, transactionSpy.getCreate()); + } + + @Test + public void givenSupportWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() { + supportTransactionalFooService.identity(new Foo("baeldung")); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(0, transactionSpy.getCreate()); + } + + @Test(expected = IllegalTransactionStateException.class) + public void givenMandatoryWithNoActiveTransaction_whenCallService_thenExpectIllegalTransactionStateExceptionWith0NewAnd0Suspend() { + mandatoryTransactionalFooService.identity(new Foo("baeldung")); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(0, transactionSpy.getCreate()); + } + + @Test + public void givenNotSupportWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() { + notSupportedTransactionalFooService.identity(new Foo("baeldung")); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(0, transactionSpy.getCreate()); + } + + @Test + public void givenNeverWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() { + neverTransactionalFooService.identity(new Foo("baeldung")); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(0, transactionSpy.getCreate()); + } + + @Test + public void givenRequiredWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() { + transactionTemplate.execute(status -> { + Foo foo = new Foo("baeldung"); + return requiredTransactionalFooDao.create(foo); + }); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(1, transactionSpy.getCreate()); + } + + @Test + public void givenRequiresNewWithActiveTransaction_whenCallCreate_thenExpect1NewAnd1Suspend() { + transactionTemplate.execute(status -> { + Foo foo = new Foo("baeldung"); + return requiresNewTransactionalFooDao.create(foo); + }); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(1, transactionSpy.getSuspend()); + Assert.assertEquals(2, transactionSpy.getCreate()); + } + + @Test + public void givenSupportWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() { + transactionTemplate.execute(status -> { + Foo foo = new Foo("baeldung"); + return supportTransactionalFooDao.create(foo); + }); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(1, transactionSpy.getCreate()); + } + + @Test + public void givenMandatoryWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() { + + transactionTemplate.execute(status -> { + Foo foo = new Foo("baeldung"); + return mandatoryTransactionalFooDao.create(foo); + }); + + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(1, transactionSpy.getCreate()); + } + + @Test + public void givenNotSupportWithActiveTransaction_whenCallCreate_thenExpect0NewAnd1Suspend() { + transactionTemplate.execute(status -> { + Foo foo = new Foo("baeldung"); + return notSupportedTransactionalFooService.identity(foo); + }); + + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(1, transactionSpy.getSuspend()); + Assert.assertEquals(1, transactionSpy.getCreate()); + } + + @Test(expected = IllegalTransactionStateException.class) + public void givenNeverWithActiveTransaction_whenCallCreate_thenExpectIllegalTransactionStateExceptionWith0NewAnd0Suspend() { + transactionTemplate.execute(status -> { + Foo foo = new Foo("baeldung"); + return neverTransactionalFooService.identity(foo); + }); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(1, transactionSpy.getCreate()); + } + +} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java new file mode 100644 index 0000000000..fde1857ca2 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java @@ -0,0 +1,148 @@ +package com.baeldung.persistence.service.transactional; + +import com.google.common.base.Preconditions; +import java.util.Properties; +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationAdapter; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-h2.properties" }) +@ComponentScan({ "com.baeldung.persistence","com.baeldung.jpa.dao" }) +@EnableJpaRepositories(basePackages = "com.baeldung.jpa.dao") +public class PersistenceTransactionalTestConfig { + + public static class TransactionSynchronizationAdapterSpy extends TransactionSynchronizationAdapter { + private int create, suspend; + + public int getSuspend() { + return suspend; + } + + public int getCreate() { + return create; + } + + public void create() { + create++; + } + + @Override + public void suspend() { + suspend++; + super.suspend(); + } + } + + + public static class JpaTransactionManagerSpy extends JpaTransactionManager { + @Override + protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition) { + super.prepareSynchronization(status, definition); + if (status.isNewTransaction()) { + if ( adapterSpyThreadLocal.get() == null ){ + TransactionSynchronizationAdapterSpy spy = new TransactionSynchronizationAdapterSpy(); + TransactionSynchronizationManager.registerSynchronization(spy); + adapterSpyThreadLocal.set(spy); + } + adapterSpyThreadLocal.get().create(); + } + } + } + + private static ThreadLocal adapterSpyThreadLocal = new ThreadLocal<>(); + + @Autowired + private Environment env; + + public PersistenceTransactionalTestConfig() { + super(); + } + + public static TransactionSynchronizationAdapterSpy getSpy(){ + if ( adapterSpyThreadLocal.get() == null ) + return new TransactionSynchronizationAdapterSpy(); + return adapterSpyThreadLocal.get(); + } + + public static void clearSpy(){ + adapterSpyThreadLocal.set(null); + } + + // beans + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + + + @Bean + public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { + final JpaTransactionManagerSpy transactionManager = new JpaTransactionManagerSpy(); + transactionManager.setEntityManagerFactory(emf); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false"); + return hibernateProperties; + } + + + @Bean + public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager){ + TransactionTemplate template = new TransactionTemplate(transactionManager); + template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + return template; + } + + +} \ No newline at end of file From da1dd4dd12fe4cbfafd39cfac5f53fbc0c45270e Mon Sep 17 00:00:00 2001 From: Lukasz Rys <> Date: Sun, 6 Oct 2019 21:27:50 +0200 Subject: [PATCH 04/38] BAEL-3322: Jimx --- testing-modules/mocks/pom.xml | 117 ++++++++++-------- .../com/baeldung/jimf/FileManipulation.java | 19 +++ .../com/baeldung/jimf/FileRepository.java | 43 +++++++ .../jimf/FileManipulationUnitTest.java | 46 +++++++ .../baeldung/jimf/FileRepositoryUnitTest.java | 74 +++++++++++ .../com/baeldung/jimf/FileTestProvider.java | 16 +++ .../src/test/resources/fileRepositoryRead.txt | 1 + 7 files changed, 261 insertions(+), 55 deletions(-) create mode 100644 testing-modules/mocks/src/main/java/com/baeldung/jimf/FileManipulation.java create mode 100644 testing-modules/mocks/src/main/java/com/baeldung/jimf/FileRepository.java create mode 100644 testing-modules/mocks/src/test/java/com/baeldung/jimf/FileManipulationUnitTest.java create mode 100644 testing-modules/mocks/src/test/java/com/baeldung/jimf/FileRepositoryUnitTest.java create mode 100644 testing-modules/mocks/src/test/java/com/baeldung/jimf/FileTestProvider.java create mode 100644 testing-modules/mocks/src/test/resources/fileRepositoryRead.txt diff --git a/testing-modules/mocks/pom.xml b/testing-modules/mocks/pom.xml index bf75cfc3a2..cbda386af8 100644 --- a/testing-modules/mocks/pom.xml +++ b/testing-modules/mocks/pom.xml @@ -1,55 +1,62 @@ - - 4.0.0 - mocks - mocks - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ - - - - - com.github.javafaker - javafaker - ${javafaker.version} - - - org.jmockit - jmockit - ${jmockit.version} - test - - - org.jukito - jukito - ${jukito.version} - test - - - org.mockito - mockito-core - ${mockito.version} - test - - - - org.easymock - easymock - ${easymock.version} - test - - - - - 0.15 - 1.5 -2.21.0 - 3.5.1 - 1.41 - - - + + 4.0.0 + mocks + mocks + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + com.github.javafaker + javafaker + ${javafaker.version} + + + org.jmockit + jmockit + ${jmockit.version} + test + + + org.jukito + jukito + ${jukito.version} + test + + + org.mockito + mockito-core + ${mockito.version} + test + + + + org.easymock + easymock + ${easymock.version} + test + + + + com.google.jimfs + jimfs + ${jimf.version} + + + + + 0.15 + 1.5 + 2.21.0 + 3.5.1 + 1.41 + 1.1 + + + diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jimf/FileManipulation.java b/testing-modules/mocks/src/main/java/com/baeldung/jimf/FileManipulation.java new file mode 100644 index 0000000000..039e4593fd --- /dev/null +++ b/testing-modules/mocks/src/main/java/com/baeldung/jimf/FileManipulation.java @@ -0,0 +1,19 @@ +package com.baeldung.jimf; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +public class FileManipulation { + + void move(final Path origin, final Path destination) { + try { + Files.createDirectories(destination); + Files.move(origin, destination, StandardCopyOption.REPLACE_EXISTING); + } catch (final IOException ex) { + throw new UncheckedIOException(ex); + } + } +} diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jimf/FileRepository.java b/testing-modules/mocks/src/main/java/com/baeldung/jimf/FileRepository.java new file mode 100644 index 0000000000..d17cff1bd2 --- /dev/null +++ b/testing-modules/mocks/src/main/java/com/baeldung/jimf/FileRepository.java @@ -0,0 +1,43 @@ +package com.baeldung.jimf; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class FileRepository { + + void create(final Path path, final String fileName) { + final Path filePath = path.resolve(fileName); + try { + Files.createFile(filePath); + } catch (final IOException ex) { + throw new UncheckedIOException(ex); + } + } + + String read(final Path path) { + try { + return new String(Files.readAllBytes(path)); + } catch (final IOException ex) { + throw new UncheckedIOException(ex); + } + } + + String update(final Path path, final String newContent) { + try { + Files.write(path, newContent.getBytes()); + return newContent; + } catch (final IOException ex) { + throw new UncheckedIOException(ex); + } + } + + void delete (final Path path){ + try { + Files.deleteIfExists(path); + } catch (final IOException ex) { + throw new UncheckedIOException(ex); + } + } +} diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileManipulationUnitTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileManipulationUnitTest.java new file mode 100644 index 0000000000..3978ec6ff7 --- /dev/null +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileManipulationUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.jimf; + +import com.google.common.jimfs.Configuration; +import com.google.common.jimfs.Jimfs; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.FileSystem; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; + +class FileManipulationUnitTest implements FileTestProvider { + + private static Stream provideFileSystem() { + return Stream.of( + Arguments.of(Jimfs.newFileSystem(Configuration.unix())), + Arguments.of(Jimfs.newFileSystem(Configuration.windows())), + Arguments.of(Jimfs.newFileSystem(Configuration.osX()))); + } + + private final FileManipulation fileManipulation = new FileManipulation(); + + @ParameterizedTest + @DisplayName("Should create a file on a file system") + @MethodSource("provideFileSystem") + void shouldCreateFile(final FileSystem fileSystem) throws Exception { + final Path origin = fileSystem.getPath(RESOURCE_FILE_NAME); + Files.copy(getResourceFilePath(), origin); + final Path destination = fileSystem.getPath("newDirectory", RESOURCE_FILE_NAME); + + fileManipulation.move(origin, destination); + + assertFalse(Files.exists(origin)); + assertTrue(Files.exists(destination)); + } +} \ No newline at end of file diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileRepositoryUnitTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileRepositoryUnitTest.java new file mode 100644 index 0000000000..3cfb49e14f --- /dev/null +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileRepositoryUnitTest.java @@ -0,0 +1,74 @@ +package com.baeldung.jimf; + +import com.google.common.jimfs.Configuration; +import com.google.common.jimfs.Jimfs; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.nio.file.FileSystem; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; + +class FileRepositoryUnitTest implements FileTestProvider { + + private final FileRepository fileRepository = new FileRepository(); + + private static Stream provideFileSystem() { + return Stream.of(Arguments.of(Jimfs.newFileSystem(Configuration.unix())), Arguments.of(Jimfs.newFileSystem(Configuration.windows())), Arguments.of(Jimfs.newFileSystem(Configuration.osX()))); + } + + @ParameterizedTest + @DisplayName("Should create a file on a file system") + @MethodSource("provideFileSystem") + void shouldCreateFile(final FileSystem fileSystem) throws Exception { + final String fileName = "test.txt"; + final Path pathToStore = fileSystem.getPath(""); + + fileRepository.create(pathToStore, fileName); + + assertTrue(Files.exists(pathToStore.resolve(fileName))); + } + + @ParameterizedTest + @DisplayName("Should read the content of the file") + @MethodSource("provideFileSystem") + void shouldReadFileContent_thenReturnIt(final FileSystem fileSystem) throws Exception { + final Path pathToStore = fileSystem.getPath(RESOURCE_FILE_NAME); + Files.copy(getResourceFilePath(), pathToStore); + + final String content = fileRepository.read(pathToStore); + + assertEquals(FILE_CONTENT, content); + } + + @ParameterizedTest + @DisplayName("Should update content of the file") + @MethodSource("provideFileSystem") + void shouldUpdateContentOfTheFile(final FileSystem fileSystem) throws Exception { + final Path pathToStore = fileSystem.getPath(RESOURCE_FILE_NAME); + Files.copy(getResourceFilePath(), pathToStore); + final String newContent = "NEW_CONTENT"; + + final String content = fileRepository.update(pathToStore, newContent); + + assertEquals(newContent, content); + assertEquals(newContent, fileRepository.read(pathToStore)); + } + + @ParameterizedTest + @DisplayName("Should update delete file") + @MethodSource("provideFileSystem") + void shouldDeleteFile(final FileSystem fileSystem) throws Exception { + final Path pathToStore = fileSystem.getPath(RESOURCE_FILE_NAME); + Files.copy(getResourceFilePath(), pathToStore); + + fileRepository.delete(pathToStore); + + assertFalse(Files.exists(pathToStore)); + } +} \ No newline at end of file diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileTestProvider.java b/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileTestProvider.java new file mode 100644 index 0000000000..9144a0b65f --- /dev/null +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileTestProvider.java @@ -0,0 +1,16 @@ +package com.baeldung.jimf; + +import java.nio.file.Path; +import java.nio.file.Paths; + +public interface FileTestProvider { + String FILE_CONTENT = "BAELDUNG"; + String RESOURCE_FILE_NAME = "fileRepositoryRead.txt"; + + default Path getResourceFilePath() { + final String resourceFilePath = getClass() + .getResource("/" + RESOURCE_FILE_NAME) + .getPath(); + return Paths.get(resourceFilePath); + } +} diff --git a/testing-modules/mocks/src/test/resources/fileRepositoryRead.txt b/testing-modules/mocks/src/test/resources/fileRepositoryRead.txt new file mode 100644 index 0000000000..7c2239aab9 --- /dev/null +++ b/testing-modules/mocks/src/test/resources/fileRepositoryRead.txt @@ -0,0 +1 @@ +BAELDUNG \ No newline at end of file From 33a3ee7592b723f8a160fccce8c8c4ecdb40613e Mon Sep 17 00:00:00 2001 From: Lukasz Rys <> Date: Sun, 6 Oct 2019 23:30:48 +0200 Subject: [PATCH 05/38] BAEL-3322: Prettify --- .../baeldung/jimf/FileRepositoryUnitTest.java | 26 +++++++++---------- .../com/baeldung/jimf/FileTestProvider.java | 2 +- .../src/test/resources/fileRepositoryRead.txt | 2 +- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileRepositoryUnitTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileRepositoryUnitTest.java index 3cfb49e14f..0564b2a52b 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileRepositoryUnitTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileRepositoryUnitTest.java @@ -26,7 +26,7 @@ class FileRepositoryUnitTest implements FileTestProvider { @DisplayName("Should create a file on a file system") @MethodSource("provideFileSystem") void shouldCreateFile(final FileSystem fileSystem) throws Exception { - final String fileName = "test.txt"; + final String fileName = "newFile.txt"; final Path pathToStore = fileSystem.getPath(""); fileRepository.create(pathToStore, fileName); @@ -38,10 +38,10 @@ class FileRepositoryUnitTest implements FileTestProvider { @DisplayName("Should read the content of the file") @MethodSource("provideFileSystem") void shouldReadFileContent_thenReturnIt(final FileSystem fileSystem) throws Exception { - final Path pathToStore = fileSystem.getPath(RESOURCE_FILE_NAME); - Files.copy(getResourceFilePath(), pathToStore); + final Path resourceFilePath = fileSystem.getPath(RESOURCE_FILE_NAME); + Files.copy(getResourceFilePath(), resourceFilePath); - final String content = fileRepository.read(pathToStore); + final String content = fileRepository.read(resourceFilePath); assertEquals(FILE_CONTENT, content); } @@ -50,25 +50,25 @@ class FileRepositoryUnitTest implements FileTestProvider { @DisplayName("Should update content of the file") @MethodSource("provideFileSystem") void shouldUpdateContentOfTheFile(final FileSystem fileSystem) throws Exception { - final Path pathToStore = fileSystem.getPath(RESOURCE_FILE_NAME); - Files.copy(getResourceFilePath(), pathToStore); - final String newContent = "NEW_CONTENT"; + final Path resourceFilePath = fileSystem.getPath(RESOURCE_FILE_NAME); + Files.copy(getResourceFilePath(), resourceFilePath); + final String newContent = "I'm updating you."; - final String content = fileRepository.update(pathToStore, newContent); + final String content = fileRepository.update(resourceFilePath, newContent); assertEquals(newContent, content); - assertEquals(newContent, fileRepository.read(pathToStore)); + assertEquals(newContent, fileRepository.read(resourceFilePath)); } @ParameterizedTest @DisplayName("Should update delete file") @MethodSource("provideFileSystem") void shouldDeleteFile(final FileSystem fileSystem) throws Exception { - final Path pathToStore = fileSystem.getPath(RESOURCE_FILE_NAME); - Files.copy(getResourceFilePath(), pathToStore); + final Path resourceFilePath = fileSystem.getPath(RESOURCE_FILE_NAME); + Files.copy(getResourceFilePath(), resourceFilePath); - fileRepository.delete(pathToStore); + fileRepository.delete(resourceFilePath); - assertFalse(Files.exists(pathToStore)); + assertFalse(Files.exists(resourceFilePath)); } } \ No newline at end of file diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileTestProvider.java b/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileTestProvider.java index 9144a0b65f..5893e5b925 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileTestProvider.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileTestProvider.java @@ -4,7 +4,7 @@ import java.nio.file.Path; import java.nio.file.Paths; public interface FileTestProvider { - String FILE_CONTENT = "BAELDUNG"; + String FILE_CONTENT = "I'm the file content."; String RESOURCE_FILE_NAME = "fileRepositoryRead.txt"; default Path getResourceFilePath() { diff --git a/testing-modules/mocks/src/test/resources/fileRepositoryRead.txt b/testing-modules/mocks/src/test/resources/fileRepositoryRead.txt index 7c2239aab9..b63f63cdd6 100644 --- a/testing-modules/mocks/src/test/resources/fileRepositoryRead.txt +++ b/testing-modules/mocks/src/test/resources/fileRepositoryRead.txt @@ -1 +1 @@ -BAELDUNG \ No newline at end of file +I'm the file content. \ No newline at end of file From f9fe917f66b0f481b34417f03feeb61e550e1698 Mon Sep 17 00:00:00 2001 From: Lukasz Rys <> Date: Sun, 6 Oct 2019 23:42:05 +0200 Subject: [PATCH 06/38] BAEL-3322: Fix package name --- .../com/baeldung/{jimf => jimfs}/FileManipulation.java | 2 +- .../java/com/baeldung/{jimf => jimfs}/FileRepository.java | 2 +- .../baeldung/{jimf => jimfs}/FileManipulationUnitTest.java | 7 +------ .../baeldung/{jimf => jimfs}/FileRepositoryUnitTest.java | 2 +- .../com/baeldung/{jimf => jimfs}/FileTestProvider.java | 2 +- 5 files changed, 5 insertions(+), 10 deletions(-) rename testing-modules/mocks/src/main/java/com/baeldung/{jimf => jimfs}/FileManipulation.java (94%) rename testing-modules/mocks/src/main/java/com/baeldung/{jimf => jimfs}/FileRepository.java (97%) rename testing-modules/mocks/src/test/java/com/baeldung/{jimf => jimfs}/FileManipulationUnitTest.java (87%) rename testing-modules/mocks/src/test/java/com/baeldung/{jimf => jimfs}/FileRepositoryUnitTest.java (99%) rename testing-modules/mocks/src/test/java/com/baeldung/{jimf => jimfs}/FileTestProvider.java (93%) diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jimf/FileManipulation.java b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileManipulation.java similarity index 94% rename from testing-modules/mocks/src/main/java/com/baeldung/jimf/FileManipulation.java rename to testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileManipulation.java index 039e4593fd..ae163b094f 100644 --- a/testing-modules/mocks/src/main/java/com/baeldung/jimf/FileManipulation.java +++ b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileManipulation.java @@ -1,4 +1,4 @@ -package com.baeldung.jimf; +package com.baeldung.jimfs; import java.io.IOException; import java.io.UncheckedIOException; diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jimf/FileRepository.java b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileRepository.java similarity index 97% rename from testing-modules/mocks/src/main/java/com/baeldung/jimf/FileRepository.java rename to testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileRepository.java index d17cff1bd2..7db4941bd3 100644 --- a/testing-modules/mocks/src/main/java/com/baeldung/jimf/FileRepository.java +++ b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.jimf; +package com.baeldung.jimfs; import java.io.IOException; import java.io.UncheckedIOException; diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileManipulationUnitTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileManipulationUnitTest.java similarity index 87% rename from testing-modules/mocks/src/test/java/com/baeldung/jimf/FileManipulationUnitTest.java rename to testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileManipulationUnitTest.java index 3978ec6ff7..63aaf5e571 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileManipulationUnitTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileManipulationUnitTest.java @@ -1,20 +1,15 @@ -package com.baeldung.jimf; +package com.baeldung.jimfs; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.io.IOException; -import java.io.UncheckedIOException; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.attribute.FileTime; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileRepositoryUnitTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java similarity index 99% rename from testing-modules/mocks/src/test/java/com/baeldung/jimf/FileRepositoryUnitTest.java rename to testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java index 0564b2a52b..4d592abf70 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileRepositoryUnitTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jimf; +package com.baeldung.jimfs; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileTestProvider.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileTestProvider.java similarity index 93% rename from testing-modules/mocks/src/test/java/com/baeldung/jimf/FileTestProvider.java rename to testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileTestProvider.java index 5893e5b925..51b584ee8c 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jimf/FileTestProvider.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileTestProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.jimf; +package com.baeldung.jimfs; import java.nio.file.Path; import java.nio.file.Paths; From 44fb860b403a7d38cfe81d12679cce1c7fe0dde8 Mon Sep 17 00:00:00 2001 From: "m.raheem" Date: Mon, 7 Oct 2019 13:52:10 +0200 Subject: [PATCH 07/38] resetting Distance class --- .../com/baeldung/jackson/enums/Distance.java | 38 ++++--------------- 1 file changed, 7 insertions(+), 31 deletions(-) diff --git a/jackson/src/main/java/com/baeldung/jackson/enums/Distance.java b/jackson/src/main/java/com/baeldung/jackson/enums/Distance.java index fdda32d16c..8026eedc44 100644 --- a/jackson/src/main/java/com/baeldung/jackson/enums/Distance.java +++ b/jackson/src/main/java/com/baeldung/jackson/enums/Distance.java @@ -1,29 +1,20 @@ package com.baeldung.jackson.enums; import com.baeldung.jackson.serialization.DistanceSerializer; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * Use @JsonFormat to handle representation of Enum as JSON (available since Jackson 2.1.2) * Use @JsonSerialize to configure a custom Jackson serializer */ -@JsonFormat(shape = JsonFormat.Shape.OBJECT) -//@JsonSerialize(using = DistanceSerializer.class) +// @JsonFormat(shape = JsonFormat.Shape.OBJECT) +@JsonSerialize(using = DistanceSerializer.class) public enum Distance { - @JsonProperty("distance-in-km") - KILOMETER("km", 1000), - @JsonProperty("distance-in-miles") - MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), - MILLIMETER("mm", 0.001); + KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); private String unit; private final double meters; - + private Distance(String unit, double meters) { this.unit = unit; this.meters = meters; @@ -32,11 +23,11 @@ public enum Distance { /** * Use @JsonValue to control marshalling output for an enum */ -// @JsonValue + // @JsonValue public double getMeters() { return meters; } - + public String getUnit() { return unit; } @@ -44,7 +35,7 @@ public enum Distance { public void setUnit(String unit) { this.unit = unit; } - + /** * Usage example: Distance.MILE.convertFromMeters(1205.5); */ @@ -60,19 +51,4 @@ public enum Distance { return distanceInMeters * meters; } -// @JsonCreator - public static Distance forValues(@JsonProperty("unit") String unit, @JsonProperty("meters") double meters) { - - for (Distance distance : Distance.values()) { - if (distance.unit.equals(unit) - && Double.compare(distance.meters, meters) == 0) { - - return distance; - } - } - - return null; - - } - } \ No newline at end of file From 06cec4c83a0a076d82e7143b7409d1c55236aa2b Mon Sep 17 00:00:00 2001 From: "m.raheem" Date: Mon, 7 Oct 2019 16:07:17 +0200 Subject: [PATCH 08/38] multiple Distance enum versions --- .../com/baeldung/jackson/entities/City.java | 196 ++++++++++++++++-- .../JacksonEnumDeserializationUnitTest.java | 45 ++++ .../JacksonEnumSerializationUnitTest.java | 44 ---- 3 files changed, 229 insertions(+), 56 deletions(-) create mode 100644 jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumDeserializationUnitTest.java diff --git a/jackson/src/main/java/com/baeldung/jackson/entities/City.java b/jackson/src/main/java/com/baeldung/jackson/entities/City.java index d4c5d715de..9f338acc28 100644 --- a/jackson/src/main/java/com/baeldung/jackson/entities/City.java +++ b/jackson/src/main/java/com/baeldung/jackson/entities/City.java @@ -1,22 +1,194 @@ package com.baeldung.jackson.entities; -import com.baeldung.jackson.enums.Distance; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; public class City { - - private Distance distance; - public Distance getDistance() { - return distance; + public static class CityWithDefaultEnum { + + private Distance distance; + + public Distance getDistance() { + return distance; + } + + public void setDistance(Distance distance) { + this.distance = distance; + } + + public enum Distance { + + KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); + + private String unit; + private final double meters; + + private Distance(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + public double getMeters() { + return meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + } + } + + public static class CityWithJsonCreatorEnum { + + private Distance distance; + + public Distance getDistance() { + return distance; + } + + public void setDistance(Distance distance) { + this.distance = distance; + } + + public enum Distance { + + KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); + + private String unit; + private final double meters; + + private Distance(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + public double getMeters() { + return meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + @JsonCreator + public static Distance forValues(@JsonProperty("unit") String unit, @JsonProperty("meters") double meters) { + + for (Distance distance : Distance.values()) { + if (distance.unit.equals(unit) && Double.compare(distance.meters, meters) == 0) { + + return distance; + } + } + + return null; + + } + } } - public void setDistance(Distance distance) { - this.distance = distance; + public static class CityWithJsonPropertyEnum { + + private Distance distance; + + public Distance getDistance() { + return distance; + } + + public void setDistance(Distance distance) { + this.distance = distance; + } + + public enum Distance { + + @JsonProperty("distance-in-km") + KILOMETER("km", 1000), + + @JsonProperty("distance-in-miles") + MILE("miles", 1609.34), + + @JsonProperty("distance-in-meters") + METER("meters", 1), + + @JsonProperty("distance-in-inches") + INCH("inches", 0.0254), + + @JsonProperty("distance-in-cm") + CENTIMETER("cm", 0.01), + + @JsonProperty("distance-in-mm") + MILLIMETER("mm", 0.001); + + private String unit; + private final double meters; + + private Distance(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + public double getMeters() { + return meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + } + } + + public static class CityWithJsonValueEnum { + + private Distance distance; + + public Distance getDistance() { + return distance; + } + + public void setDistance(Distance distance) { + this.distance = distance; + } + + public enum Distance { + + KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); + + private String unit; + private final double meters; + + private Distance(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + @JsonValue + public double getMeters() { + return meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + } } - @Override - public String toString() { - return "City [distance=" + distance + "]"; - } - } diff --git a/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumDeserializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumDeserializationUnitTest.java new file mode 100644 index 0000000000..d823bca445 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumDeserializationUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.jackson.enums; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.IOException; +import org.junit.Test; +import com.baeldung.jackson.entities.City; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JacksonEnumDeserializationUnitTest { + + @Test + public final void givenEnum_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + String json = "{\"distance\":\"KILOMETER\"}"; + City.CityWithDefaultEnum city = new ObjectMapper().readValue(json, City.CityWithDefaultEnum.class); + + assertEquals(City.CityWithDefaultEnum.Distance.KILOMETER, city.getDistance()); + } + + @Test + public final void givenEnumWithJsonValue_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + String json = "{\"distance\": \"0.0254\"}"; + + City.CityWithJsonValueEnum city = new ObjectMapper().readValue(json, City.CityWithJsonValueEnum.class); + assertEquals(City.CityWithJsonValueEnum.Distance.INCH, city.getDistance()); + } + + @Test + public final void givenEnumWithJsonProperty_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + String json = "{\"distance\": \"distance-in-km\"}"; + + City.CityWithJsonPropertyEnum city = new ObjectMapper().readValue(json, City.CityWithJsonPropertyEnum.class); + assertEquals(City.CityWithJsonPropertyEnum.Distance.KILOMETER, city.getDistance()); + + } + + @Test + public final void givenEnumWithJsonCreator_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + String json = "{\"distance\": {\"unit\":\"miles\",\"meters\":1609.34}}"; + + City.CityWithJsonCreatorEnum city = new ObjectMapper().readValue(json, City.CityWithJsonCreatorEnum.class); + assertEquals(City.CityWithJsonCreatorEnum.Distance.MILE, city.getDistance()); + } + +} diff --git a/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationUnitTest.java index 3108773a00..d4fb2401ed 100644 --- a/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationUnitTest.java @@ -1,17 +1,10 @@ package com.baeldung.jackson.enums; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; - import java.io.IOException; -import org.junit.Ignore; import org.junit.Test; - -import com.baeldung.jackson.entities.City; import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonEnumSerializationUnitTest { @@ -22,42 +15,5 @@ public class JacksonEnumSerializationUnitTest { assertThat(dtoAsString, containsString("1609.34")); } - - @Test - @Ignore - public final void givenEnum_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { - String json = "{\"distance\":\"KILOMETER\"}"; - City city = new ObjectMapper().readValue(json, City.class); - - assertEquals(Distance.KILOMETER, city.getDistance()); - } - - @Test - @Ignore - public final void givenEnumWithJsonValue_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { - String json = "{\"JacksonDeserializationUnitTestdistance\": \"0.0254\"}"; - - City city = new ObjectMapper().readValue(json, City.class); - assertEquals(Distance.INCH, city.getDistance()); - } - - @Test - public final void givenEnumWithGsonProperty_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { - String json = "{\"distance\": \"distance-in-km\"}"; - - City city = new ObjectMapper().readValue(json, City.class); - assertEquals(Distance.KILOMETER, city.getDistance()); - - } - - @Test - @Ignore - public final void givenEnumWithGsonCreator_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { - String json = "{\"distance\": {\"unit\":\"miles\",\"meters\":1609.34}}"; - - City city = new ObjectMapper().readValue(json, City.class); - assertEquals(Distance.MILE, city.getDistance()); - System.out.println(city); - } } From a2e57b357786430143c1057da765494688a69d1b Mon Sep 17 00:00:00 2001 From: "m.raheem" Date: Mon, 7 Oct 2019 22:46:32 +0200 Subject: [PATCH 09/38] custom deserializer --- .../enums/CustomEnumDeserializer.java | 44 +++++++++++++++++++ .../com/baeldung/jackson/entities/City.java | 41 +++++++++++++++++ .../JacksonEnumDeserializationUnitTest.java | 7 +++ 3 files changed, 92 insertions(+) create mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/enums/CustomEnumDeserializer.java diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/CustomEnumDeserializer.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/CustomEnumDeserializer.java new file mode 100644 index 0000000000..3b99490e0b --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/CustomEnumDeserializer.java @@ -0,0 +1,44 @@ +package com.baeldung.jackson.deserialization.enums; + +import java.io.IOException; +import com.baeldung.jackson.entities.City; +import com.baeldung.jackson.entities.City.CityWithCustomDeserializationEnum.Distance; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; + +public class CustomEnumDeserializer extends StdDeserializer { + + private static final long serialVersionUID = -1166032307856492833L; + + public CustomEnumDeserializer() { + this(null); + } + + public CustomEnumDeserializer(Class vc) { + super(vc); + } + + @Override + public City.CityWithCustomDeserializationEnum.Distance deserialize(final JsonParser jsonParser, final DeserializationContext ctxt) throws IOException, JsonProcessingException { + + final JsonNode node = jsonParser.getCodec().readTree(jsonParser); + + String unit = node.get("unit").asText(); + double meters = node.get("meters").asDouble(); + + for (Distance distance : Distance.values()) { + + if (distance.getUnit().equals(unit) && + Double.compare(distance.getMeters(), meters) == 0) { + + return distance; + } + } + + return null; + } + +} diff --git a/jackson/src/main/java/com/baeldung/jackson/entities/City.java b/jackson/src/main/java/com/baeldung/jackson/entities/City.java index 9f338acc28..42911dc798 100644 --- a/jackson/src/main/java/com/baeldung/jackson/entities/City.java +++ b/jackson/src/main/java/com/baeldung/jackson/entities/City.java @@ -1,8 +1,10 @@ package com.baeldung.jackson.entities; +import com.baeldung.jackson.deserialization.enums.CustomEnumDeserializer; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; public class City { @@ -191,4 +193,43 @@ public class City { } } + public static class CityWithCustomDeserializationEnum { + + private Distance distance; + + public Distance getDistance() { + return distance; + } + + public void setDistance(Distance distance) { + this.distance = distance; + } + + @JsonDeserialize(using = CustomEnumDeserializer.class) + public enum Distance { + + KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); + + private String unit; + private final double meters; + + private Distance(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + public double getMeters() { + return meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + } + } + } diff --git a/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumDeserializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumDeserializationUnitTest.java index d823bca445..b4d63c181e 100644 --- a/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumDeserializationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumDeserializationUnitTest.java @@ -42,4 +42,11 @@ public class JacksonEnumDeserializationUnitTest { assertEquals(City.CityWithJsonCreatorEnum.Distance.MILE, city.getDistance()); } + @Test + public final void givenEnumWithCustomDeserializer_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + String json = "{\"distance\": {\"unit\":\"miles\",\"meters\":1609.34}}"; + + City.CityWithCustomDeserializationEnum city = new ObjectMapper().readValue(json, City.CityWithCustomDeserializationEnum.class); + assertEquals(City.CityWithCustomDeserializationEnum.Distance.MILE, city.getDistance()); + } } From f4497314297a6d1a1d4b5480f2d8ec7441365312 Mon Sep 17 00:00:00 2001 From: Vivek Balasubramaniam Date: Sat, 12 Oct 2019 08:56:35 +0530 Subject: [PATCH 10/38] BAEL-3091: The Prototype Pattern in Java --- .../java/com/baeldung/prototype/Position.java | 51 ++++++++++++++++++ .../java/com/baeldung/prototype/Tree.java | 54 +++++++++++++++++++ .../com/baeldung/prototype/TreeCloneable.java | 7 +++ .../prototype/TreePrototypeUnitTest.java | 24 +++++++++ 4 files changed, 136 insertions(+) create mode 100644 patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Position.java create mode 100644 patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java create mode 100644 patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/TreeCloneable.java create mode 100644 patterns/design-patterns-creational/src/test/java/com/baeldung/prototype/TreePrototypeUnitTest.java diff --git a/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Position.java b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Position.java new file mode 100644 index 0000000000..dd7694feb6 --- /dev/null +++ b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Position.java @@ -0,0 +1,51 @@ +package com.baeldung.prototype; + +public final class Position { + + private final int x; + private final int y; + + public Position(int x, int y) { + this.x = x; + this.y = y; + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + x; + result = prime * result + y; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Position other = (Position) obj; + if (x != other.x) + return false; + if (y != other.y) + return false; + return true; + } + + @Override + public String toString() { + return "Position [x=" + x + ", y=" + y + "]"; + } + +} diff --git a/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java new file mode 100644 index 0000000000..242ed2176e --- /dev/null +++ b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java @@ -0,0 +1,54 @@ +package com.baeldung.prototype; + +public class Tree implements TreeCloneable { + + private double mass; + private double height; + private Position position; + + public Tree(double mass, double height) { + this.mass = mass; + this.height = height; + } + + public void setMass(double mass) { + this.mass = mass; + } + + public void setHeight(double height) { + this.height = height; + } + + public void setPosition(Position position) { + this.position = position; + } + + public double getMass() { + return mass; + } + + public double getHeight() { + return height; + } + + public Position getPosition() { + return position; + } + + @Override + public TreeCloneable createA_Clone() { + TreeCloneable tree = null; + try { + tree = (TreeCloneable) super.clone(); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + } + return tree; + } + + @Override + public String toString() { + return "SomeTree [mass=" + mass + ", height=" + height + ", position=" + position + "]"; + } + +} diff --git a/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/TreeCloneable.java b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/TreeCloneable.java new file mode 100644 index 0000000000..e554058624 --- /dev/null +++ b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/TreeCloneable.java @@ -0,0 +1,7 @@ +package com.baeldung.prototype; + +public interface TreeCloneable extends Cloneable { + + public TreeCloneable createA_Clone(); + +} diff --git a/patterns/design-patterns-creational/src/test/java/com/baeldung/prototype/TreePrototypeUnitTest.java b/patterns/design-patterns-creational/src/test/java/com/baeldung/prototype/TreePrototypeUnitTest.java new file mode 100644 index 0000000000..7f260c52bf --- /dev/null +++ b/patterns/design-patterns-creational/src/test/java/com/baeldung/prototype/TreePrototypeUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.prototype; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class TreePrototypeUnitTest { + + @Test + public void givenATreePrototypeWhenClonedThenCreateA_Clone() { + double mass = 10.0; + double height = 3.7; + Position position = new Position(3, 7); + Position otherPosition = new Position(4, 8); + + Tree tree = new Tree(mass, height); + tree.setPosition(position); + Tree anotherTree = (Tree) tree.createA_Clone(); + anotherTree.setPosition(otherPosition); + + assertEquals(position, tree.getPosition()); + assertEquals(otherPosition, anotherTree.getPosition()); + } +} From 5fa271fe024d6bbcb96f8308038abd1fd8ab7287 Mon Sep 17 00:00:00 2001 From: vatsalgosar Date: Sat, 12 Oct 2019 15:51:21 +0530 Subject: [PATCH 11/38] BAEL-3209 - Adding elements in Java Array vs ArrayList --- .../array/operations/ArrayOperations.java | 30 +++++++++++ .../operations/ArrayListOperations.java | 23 +++++++++ .../operations/ArrayOperationsUnitTest.java | 32 ++++++++++++ .../ArrayListOperationsUnitTest.java | 50 +++++++++++++++++++ 4 files changed, 135 insertions(+) create mode 100644 core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/operations/ArrayOperations.java create mode 100644 core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java create mode 100644 core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java create mode 100644 core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/operations/ArrayOperations.java b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/operations/ArrayOperations.java new file mode 100644 index 0000000000..8d9c4d6730 --- /dev/null +++ b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/operations/ArrayOperations.java @@ -0,0 +1,30 @@ +package com.baeldung.array.operations; + +public class ArrayOperations { + + public static Integer[] addElementUsingPureJava(Integer[] srcArray, int elementToAdd) { + Integer[] destArray = new Integer[srcArray.length + 1]; + + for (int i = 0; i < srcArray.length; i++) { + destArray[i] = srcArray[i]; + } + + destArray[destArray.length - 1] = elementToAdd; + return destArray; + } + + public static int[] insertAnElementAtAGivenIndex(final int[] srcArray, int index, int newElement) { + int[] destArray = new int[srcArray.length + 1]; + int j = 0; + for (int i = 0; i < destArray.length - 1; i++) { + + if (i == index) { + destArray[i] = newElement; + } else { + destArray[i] = srcArray[j]; + j++; + } + } + return destArray; + } +} diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java new file mode 100644 index 0000000000..b2aed553da --- /dev/null +++ b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java @@ -0,0 +1,23 @@ +package com.baeldung.arraylist.operations; + +import java.util.ArrayList; + +public class ArrayListOperations { + + public static Integer getAnIntegerElement(ArrayList anArrayList, int index) { + return anArrayList.get(index); + } + + public static void modifyAnIntegerElement(ArrayList anArrayList, int index, Integer newElement) { + anArrayList.set(index, newElement); + } + + public static void appendAnIntegerElement(ArrayList anArrayList, Integer newElement) { + anArrayList.add(newElement); + } + + public static void insertAnIntegerElementAtIndex(ArrayList anArrayList, int index, Integer newElement) { + anArrayList.add(index, newElement); + } + +} diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java new file mode 100644 index 0000000000..5ed27f2dbb --- /dev/null +++ b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.array.operations; + +import org.junit.jupiter.api.Test; +import static org.junit.Assert.assertArrayEquals; +import static org.assertj.core.api.Assertions.assertThat; + +public class ArrayOperationsUnitTest { + + @Test + public void givenSourceArrayAndElement_whenAddElementUsingPureJavaIsInvoked_thenNewElementMustBeAdded() { + Integer[] sourceArray = { 1, 2, 3, 4 }; + int elementToAdd = 5; + + Integer[] destArray = ArrayOperations.addElementUsingPureJava(sourceArray, elementToAdd); + + Integer[] expectedArray = { 1, 2, 3, 4, 5 }; + assertArrayEquals(expectedArray, destArray); + } + + @Test + public void whenInsertAnElementAtAGivenIndexCalled_thenShiftTheFollowingElementsAndInsertTheElementInArray() { + int[] expectedArray = { 1, 4, 2, 3, 0 }; + int[] anArray = new int[4]; + anArray[0] = 1; + anArray[1] = 2; + anArray[2] = 3; + int[] outputArray = ArrayOperations.insertAnElementAtAGivenIndex(anArray, 1, 4); + + assertThat(outputArray).containsExactly(expectedArray); + } + +} diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java new file mode 100644 index 0000000000..1ec7645d8f --- /dev/null +++ b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.arraylist.operations; + +import java.util.ArrayList; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; + +public class ArrayListOperationsUnitTest { + + private ArrayList anArrayList; + + @BeforeEach + public void setupDefaults() { + anArrayList = new ArrayList<>(); + anArrayList.add(2); + anArrayList.add(3); + anArrayList.add(4); + } + + @Test + public void whenGetAnIntegerElementCalled_thenReturnTheIntegerElement() { + Integer output = ArrayListOperations.getAnIntegerElement(anArrayList, 1); + + assertThat(output).isEqualTo(3); + } + + @Test + public void whenModifyAnIntegerElementCalled_thenModifyTheIntegerElement() { + ArrayListOperations.modifyAnIntegerElement(anArrayList, 2, 5); + Integer output = ArrayListOperations.getAnIntegerElement(anArrayList, 2); + + assertThat(output).isEqualTo(5); + } + + @Test + public void whenAppendAnIntegerElementCalled_thenTheIntegerElementIsAppendedToArrayList() { + ArrayListOperations.appendAnIntegerElement(anArrayList, 6); + Integer output = ArrayListOperations.getAnIntegerElement(anArrayList, anArrayList.size() - 1); + + assertThat(output).isEqualTo(6); + } + + @Test + public void whenInsertAnIntegerAtIndexCalled_thenTheIntegerElementIsInseredToArrayList() { + ArrayListOperations.insertAnIntegerElementAtIndex(anArrayList, 1, 10); + Integer output = ArrayListOperations.getAnIntegerElement(anArrayList, 1); + + assertThat(output).isEqualTo(10); + } +} \ No newline at end of file From 51e9e905411bb00697b2ac834d9a68e153fddd0d Mon Sep 17 00:00:00 2001 From: "m.raheem" Date: Sat, 12 Oct 2019 19:57:05 +0200 Subject: [PATCH 12/38] creating package per deserialization method --- .../jackson/deserialization/enums/City.java | 15 ++ .../deserialization/enums/Distance.java | 27 ++ .../enums/customdeserializer/City.java | 15 ++ .../CustomEnumDeserializer.java | 8 +- .../enums/customdeserializer/Distance.java | 29 +++ .../enums/jsoncreator/City.java | 15 ++ .../enums/jsoncreator/Distance.java | 44 ++++ .../enums/jsonproperty/City.java | 15 ++ .../enums/jsonproperty/Distance.java | 47 ++++ .../deserialization/enums/jsonvalue/City.java | 15 ++ .../enums/jsonvalue/Distance.java | 31 +++ .../com/baeldung/jackson/entities/City.java | 235 ------------------ .../DefaultJacksonEnumDeserialization.java | 19 ++ .../JacksonEnumCustomDeserialization.java | 18 ++ ...onEnumDeserializationUsingJsonCreator.java | 19 ++ ...nEnumDeserializationUsingJsonProperty.java | 20 ++ ...ksonEnumDeserializationUsingJsonValue.java | 19 ++ .../JacksonEnumDeserializationUnitTest.java | 52 ---- 18 files changed, 351 insertions(+), 292 deletions(-) create mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/enums/City.java create mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/enums/Distance.java create mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/City.java rename jackson/src/main/java/com/baeldung/jackson/deserialization/enums/{ => customdeserializer}/CustomEnumDeserializer.java (68%) create mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/Distance.java create mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsoncreator/City.java create mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsoncreator/Distance.java create mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonproperty/City.java create mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonproperty/Distance.java create mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonvalue/City.java create mode 100644 jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonvalue/Distance.java delete mode 100644 jackson/src/main/java/com/baeldung/jackson/entities/City.java create mode 100644 jackson/src/test/java/com/baeldung/jackson/deserialization/enums/DefaultJacksonEnumDeserialization.java create mode 100644 jackson/src/test/java/com/baeldung/jackson/deserialization/enums/customdeserializer/JacksonEnumCustomDeserialization.java create mode 100644 jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsoncreator/JacksonEnumDeserializationUsingJsonCreator.java create mode 100644 jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonproperty/JacksonEnumDeserializationUsingJsonProperty.java create mode 100644 jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonvalue/JacksonEnumDeserializationUsingJsonValue.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumDeserializationUnitTest.java diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/City.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/City.java new file mode 100644 index 0000000000..2bbef534c3 --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/City.java @@ -0,0 +1,15 @@ +package com.baeldung.jackson.deserialization.enums; + +public class City { + + private Distance distance; + + public Distance getDistance() { + return distance; + } + + public void setDistance(Distance distance) { + this.distance = distance; + } + +} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/Distance.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/Distance.java new file mode 100644 index 0000000000..ce332d34ae --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/Distance.java @@ -0,0 +1,27 @@ +package com.baeldung.jackson.deserialization.enums; + +public enum Distance { + + KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); + + private String unit; + private final double meters; + + private Distance(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + public double getMeters() { + return meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } +} + diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/City.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/City.java new file mode 100644 index 0000000000..36ef7e244a --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/City.java @@ -0,0 +1,15 @@ +package com.baeldung.jackson.deserialization.enums.customdeserializer; + +public class City { + + private Distance distance; + + public Distance getDistance() { + return distance; + } + + public void setDistance(Distance distance) { + this.distance = distance; + } + +} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/CustomEnumDeserializer.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/CustomEnumDeserializer.java similarity index 68% rename from jackson/src/main/java/com/baeldung/jackson/deserialization/enums/CustomEnumDeserializer.java rename to jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/CustomEnumDeserializer.java index 3b99490e0b..21be368e01 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/CustomEnumDeserializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/CustomEnumDeserializer.java @@ -1,15 +1,13 @@ -package com.baeldung.jackson.deserialization.enums; +package com.baeldung.jackson.deserialization.enums.customdeserializer; import java.io.IOException; -import com.baeldung.jackson.entities.City; -import com.baeldung.jackson.entities.City.CityWithCustomDeserializationEnum.Distance; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -public class CustomEnumDeserializer extends StdDeserializer { +public class CustomEnumDeserializer extends StdDeserializer { private static final long serialVersionUID = -1166032307856492833L; @@ -22,7 +20,7 @@ public class CustomEnumDeserializer extends StdDeserializer Date: Sun, 13 Oct 2019 18:00:43 +0200 Subject: [PATCH 13/38] BAEL-3089 - created examples for @SecondaryTable article --- persistence-modules/java-jpa-2/pom.xml | 11 ++- .../multipleentities/AllergensAsEntity.java | 73 ++++++++++++++ .../MealWithMultipleEntities.java | 75 ++++++++++++++ .../secondarytable/MealAsSingleEntity.java | 99 +++++++++++++++++++ .../embeddable/AllergensAsEmbeddable.java | 47 +++++++++ .../embeddable/MealWithEmbeddedAllergens.java | 78 +++++++++++++++ .../main/resources/META-INF/persistence.xml | 30 ++++++ .../MultipleTablesIntegrationTest.java | 79 +++++++++++++++ .../src/test/resources/multipletables.sql | 8 ++ 9 files changed, 498 insertions(+), 2 deletions(-) create mode 100644 persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/AllergensAsEntity.java create mode 100644 persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/MealWithMultipleEntities.java create mode 100644 persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/MealAsSingleEntity.java create mode 100644 persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/AllergensAsEmbeddable.java create mode 100644 persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/MealWithEmbeddedAllergens.java create mode 100644 persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/multipletables/MultipleTablesIntegrationTest.java create mode 100644 persistence-modules/java-jpa-2/src/test/resources/multipletables.sql diff --git a/persistence-modules/java-jpa-2/pom.xml b/persistence-modules/java-jpa-2/pom.xml index fdd482f833..3cbc15beed 100644 --- a/persistence-modules/java-jpa-2/pom.xml +++ b/persistence-modules/java-jpa-2/pom.xml @@ -1,5 +1,4 @@ - 4.0.0 java-jpa-2 @@ -47,6 +46,13 @@ ${postgres.version} runtime + + + org.assertj + assertj-core + ${assertj.version} + test + @@ -106,6 +112,7 @@ 2.7.4-RC1 42.2.5 2.2 + 3.11.1 \ No newline at end of file diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/AllergensAsEntity.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/AllergensAsEntity.java new file mode 100644 index 0000000000..e5e228d013 --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/AllergensAsEntity.java @@ -0,0 +1,73 @@ +package com.baeldung.jpa.multipletables.multipleentities; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.Table; + +import com.baeldung.jpa.multipletables.secondarytable.MealAsSingleEntity; + +@Entity +@Table(name = "allergens") +public class AllergensAsEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "meal_id") + private Long mealId; + + @OneToOne + @PrimaryKeyJoinColumn(name = "meal_id") + private MealAsSingleEntity meal; + + @Column(name = "peanuts") + private boolean peanuts; + + @Column(name = "celery") + private boolean celery; + + @Column(name = "sesame_seeds") + private boolean sesameSeeds; + + public MealAsSingleEntity getMeal() { + return meal; + } + + public void setMeal(MealAsSingleEntity meal) { + this.meal = meal; + } + + public boolean isPeanuts() { + return peanuts; + } + + public void setPeanuts(boolean peanuts) { + this.peanuts = peanuts; + } + + public boolean isCelery() { + return celery; + } + + public void setCelery(boolean celery) { + this.celery = celery; + } + + public boolean isSesameSeeds() { + return sesameSeeds; + } + + public void setSesameSeeds(boolean sesameSeeds) { + this.sesameSeeds = sesameSeeds; + } + + @Override + public String toString() { + return "AllergensAsEntity [peanuts=" + peanuts + ", celery=" + celery + ", sesameSeeds=" + sesameSeeds + "]"; + } + +} diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/MealWithMultipleEntities.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/MealWithMultipleEntities.java new file mode 100644 index 0000000000..74105f8f1f --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/MealWithMultipleEntities.java @@ -0,0 +1,75 @@ +package com.baeldung.jpa.multipletables.multipleentities; + +import java.math.BigDecimal; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "meal") +public class MealWithMultipleEntities { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "description") + private String description; + + @Column(name = "price") + private BigDecimal price; + + @OneToOne(mappedBy = "meal") + private AllergensAsEntity allergens; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public AllergensAsEntity getAllergens() { + return allergens; + } + + public void setAllergens(AllergensAsEntity allergens) { + this.allergens = allergens; + } + + public Long getId() { + return id; + } + + @Override + public String toString() { + return "MealWithMultipleEntities [id=" + id + ", name=" + name + ", description=" + description + ", price=" + price + ", allergens=" + allergens + "]"; + } + +} diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/MealAsSingleEntity.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/MealAsSingleEntity.java new file mode 100644 index 0000000000..2929f391a4 --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/MealAsSingleEntity.java @@ -0,0 +1,99 @@ +package com.baeldung.jpa.multipletables.secondarytable; + +import java.math.BigDecimal; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.SecondaryTable; +import javax.persistence.Table; + +@Entity +@Table(name = "meal") +@SecondaryTable(name = "allergens", pkJoinColumns = @PrimaryKeyJoinColumn(name = "meal_id")) +public class MealAsSingleEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "description") + private String description; + + @Column(name = "price") + private BigDecimal price; + + @Column(name = "peanuts", table = "allergens") + private boolean peanuts; + + @Column(name = "celery", table = "allergens") + private boolean celery; + + @Column(name = "sesame_seeds", table = "allergens") + private boolean sesameSeeds; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public boolean isPeanuts() { + return peanuts; + } + + public void setPeanuts(boolean peanuts) { + this.peanuts = peanuts; + } + + public boolean isCelery() { + return celery; + } + + public void setCelery(boolean celery) { + this.celery = celery; + } + + public boolean isSesameSeeds() { + return sesameSeeds; + } + + public void setSesameSeeds(boolean sesameSeeds) { + this.sesameSeeds = sesameSeeds; + } + + public Long getId() { + return id; + } + + @Override + public String toString() { + return "MealAsSingleEntity [id=" + id + ", name=" + name + ", description=" + description + ", price=" + price + ", peanuts=" + peanuts + ", celery=" + celery + ", sesameSeeds=" + sesameSeeds + "]"; + } + +} diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/AllergensAsEmbeddable.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/AllergensAsEmbeddable.java new file mode 100644 index 0000000000..1c1f05890b --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/AllergensAsEmbeddable.java @@ -0,0 +1,47 @@ +package com.baeldung.jpa.multipletables.secondarytable.embeddable; + +import javax.persistence.Column; +import javax.persistence.Embeddable; + +@Embeddable +public class AllergensAsEmbeddable { + + @Column(name = "peanuts", table = "allergens") + private boolean peanuts; + + @Column(name = "celery", table = "allergens") + private boolean celery; + + @Column(name = "sesame_seeds", table = "allergens") + private boolean sesameSeeds; + + public boolean isPeanuts() { + return peanuts; + } + + public void setPeanuts(boolean peanuts) { + this.peanuts = peanuts; + } + + public boolean isCelery() { + return celery; + } + + public void setCelery(boolean celery) { + this.celery = celery; + } + + public boolean isSesameSeeds() { + return sesameSeeds; + } + + public void setSesameSeeds(boolean sesameSeeds) { + this.sesameSeeds = sesameSeeds; + } + + @Override + public String toString() { + return "AllergensAsEmbeddable [peanuts=" + peanuts + ", celery=" + celery + ", sesameSeeds=" + sesameSeeds + "]"; + } + +} diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/MealWithEmbeddedAllergens.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/MealWithEmbeddedAllergens.java new file mode 100644 index 0000000000..87a83157d7 --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/MealWithEmbeddedAllergens.java @@ -0,0 +1,78 @@ +package com.baeldung.jpa.multipletables.secondarytable.embeddable; + +import java.math.BigDecimal; + +import javax.persistence.Column; +import javax.persistence.Embedded; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.SecondaryTable; +import javax.persistence.Table; + +@Entity +@Table(name = "meal") +@SecondaryTable(name = "allergens", pkJoinColumns = @PrimaryKeyJoinColumn(name = "meal_id")) +public class MealWithEmbeddedAllergens { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "description") + private String description; + + @Column(name = "price") + private BigDecimal price; + + @Embedded + private AllergensAsEmbeddable allergens; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public AllergensAsEmbeddable getAllergens() { + return allergens; + } + + public void setAllergens(AllergensAsEmbeddable allergens) { + this.allergens = allergens; + } + + public Long getId() { + return id; + } + + @Override + public String toString() { + return "MealWithEmbeddedAllergens [id=" + id + ", name=" + name + ", description=" + description + ", price=" + price + ", allergens=" + allergens + "]"; + } + +} diff --git a/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml index 62d7ce0f5e..0602a82f6c 100644 --- a/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml @@ -119,4 +119,34 @@ + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.multipletables.multipleentities.MealWithMultipleEntities + com.baeldung.jpa.multipletables.multipleentities.AllergensAsEntity + + com.baeldung.jpa.multipletables.secondarytable.MealAsSingleEntity + + com.baeldung.jpa.multipletables.secondarytable.embeddable.MealWithEmbeddedAllergens + com.baeldung.jpa.multipletables.secondarytable.embeddable.AllergensAsEmbeddable + + true + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/multipletables/MultipleTablesIntegrationTest.java b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/multipletables/MultipleTablesIntegrationTest.java new file mode 100644 index 0000000000..99b2cd69ee --- /dev/null +++ b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/multipletables/MultipleTablesIntegrationTest.java @@ -0,0 +1,79 @@ +package com.baeldung.jpa.multipletables; + +import static org.assertj.core.api.Assertions.*; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.jpa.multipletables.multipleentities.MealWithMultipleEntities; +import com.baeldung.jpa.multipletables.secondarytable.MealAsSingleEntity; +import com.baeldung.jpa.multipletables.secondarytable.embeddable.MealWithEmbeddedAllergens; + +public class MultipleTablesIntegrationTest { + + private static EntityManagerFactory emf; + private static EntityManager em; + + @BeforeClass + public static void setup() { + emf = Persistence.createEntityManagerFactory("jpa-h2-multipltables"); + em = emf.createEntityManager(); + } + + @Test + public void entityManager_shouldLoadMealAsSingleEntity() { + // given + + // when + MealAsSingleEntity meal = em.find(MealAsSingleEntity.class, 1L); + + // then + assertThat(meal).isNotNull(); + assertThat(meal.getId()).isEqualTo(1L); + assertThat(meal.isPeanuts()).isFalse(); + assertThat(meal.isCelery()).isTrue(); + } + + @Test + public void entityManager_shouldLoadMealWithEmbeddedAllergens() { + // given + + // when + MealWithEmbeddedAllergens meal = em.find(MealWithEmbeddedAllergens.class, 1L); + + // then + assertThat(meal).isNotNull(); + assertThat(meal.getId()).isEqualTo(1L); + assertThat(meal.getAllergens()).isNotNull(); + assertThat(meal.getAllergens().isPeanuts()).isFalse(); + assertThat(meal.getAllergens().isCelery()).isTrue(); + } + + @Test + public void entityManager_shouldLoadMealWithAllergensEntity() { + // given + + // when + MealWithMultipleEntities meal = em.find(MealWithMultipleEntities.class, 1L); + + // then + assertThat(meal).isNotNull(); + assertThat(meal.getId()).isEqualTo(1L); + assertThat(meal.getAllergens()).isNotNull(); + assertThat(meal.getAllergens().isPeanuts()).isFalse(); + assertThat(meal.getAllergens().isCelery()).isTrue(); + } + + @AfterClass + public static void teardown() { + if (emf != null) { + emf.close(); + } + } + +} diff --git a/persistence-modules/java-jpa-2/src/test/resources/multipletables.sql b/persistence-modules/java-jpa-2/src/test/resources/multipletables.sql new file mode 100644 index 0000000000..226e63258b --- /dev/null +++ b/persistence-modules/java-jpa-2/src/test/resources/multipletables.sql @@ -0,0 +1,8 @@ +drop table if exists allergens; +drop table if exists meal; + +create table meal (id bigint auto_increment, name varchar(255) not null, description varchar(255) not null, price decimal(19, 2) not null, primary key (id)); +create table allergens (meal_id bigint auto_increment, peanuts number(1) not null, celery number(1) not null, sesame_seeds number(1) not null, primary key (meal_id)); + +insert into meal (id, name, description, price) values (1, 'Pizza', 'Delicious', 5); +insert into allergens (meal_id, peanuts, celery, sesame_seeds) values (1, 0, 1, 0); From 0b7a7f6221510471cf09fc5d6248cbe80e7da117 Mon Sep 17 00:00:00 2001 From: Lukasz Rys <> Date: Sun, 13 Oct 2019 23:06:40 +0200 Subject: [PATCH 14/38] [ BAEL-3322 ]: Update --- .../com/baeldung/jimfs/FilePathReader.java | 17 +++++++ .../com/baeldung/jimfs/FileRepository.java | 2 +- .../jimfs/FileManipulationUnitTest.java | 14 +++--- .../baeldung/jimfs/FilePathReaderTest.java | 48 +++++++++++++++++++ .../jimfs/FileRepositoryUnitTest.java | 37 ++++++-------- 5 files changed, 87 insertions(+), 31 deletions(-) create mode 100644 testing-modules/mocks/src/main/java/com/baeldung/jimfs/FilePathReader.java create mode 100644 testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderTest.java diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FilePathReader.java b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FilePathReader.java new file mode 100644 index 0000000000..3504207125 --- /dev/null +++ b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FilePathReader.java @@ -0,0 +1,17 @@ +package com.baeldung.jimfs; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Path; + +class FilePathReader { + String getSystemPath(Path path) { + try { + return path + .toRealPath() + .toString(); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } +} diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileRepository.java b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileRepository.java index 7db4941bd3..55bd87ee81 100644 --- a/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileRepository.java +++ b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileRepository.java @@ -33,7 +33,7 @@ public class FileRepository { } } - void delete (final Path path){ + void delete(final Path path) { try { Files.deleteIfExists(path); } catch (final IOException ex) { diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileManipulationUnitTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileManipulationUnitTest.java index 63aaf5e571..a7cb8e53c6 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileManipulationUnitTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileManipulationUnitTest.java @@ -12,19 +12,17 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.stream.Stream; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; class FileManipulationUnitTest implements FileTestProvider { - private static Stream provideFileSystem() { - return Stream.of( - Arguments.of(Jimfs.newFileSystem(Configuration.unix())), - Arguments.of(Jimfs.newFileSystem(Configuration.windows())), - Arguments.of(Jimfs.newFileSystem(Configuration.osX()))); - } - private final FileManipulation fileManipulation = new FileManipulation(); + private static Stream provideFileSystem() { + return Stream.of(Arguments.of(Jimfs.newFileSystem(Configuration.unix())), Arguments.of(Jimfs.newFileSystem(Configuration.windows())), Arguments.of(Jimfs.newFileSystem(Configuration.osX()))); + } + @ParameterizedTest @DisplayName("Should create a file on a file system") @MethodSource("provideFileSystem") diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderTest.java new file mode 100644 index 0000000000..8a52bd3443 --- /dev/null +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderTest.java @@ -0,0 +1,48 @@ +package com.baeldung.jimfs; + +import com.google.common.jimfs.Configuration; +import com.google.common.jimfs.Jimfs; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.nio.file.FileSystem; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class FilePathReaderTest { + + private static String DIRECTORY_NAME = "baeldung"; + + private FilePathReader filePathReader = new FilePathReader(); + + @Test + @DisplayName("Should get path on windows") + void shouldGetPath_onWindows() throws Exception { + FileSystem fileSystem = Jimfs.newFileSystem(Configuration.windows()); + Path path = getPathToFile(fileSystem); + + String stringPath = filePathReader.getSystemPath(path); + + assertEquals("C:\\work\\" + DIRECTORY_NAME, stringPath); + } + + @Test + @DisplayName("Should get path on unix") + void shouldGetPath_onUnix() throws Exception { + FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix()); + Path path = getPathToFile(fileSystem); + + String stringPath = filePathReader.getSystemPath(path); + + assertEquals("/work/" + DIRECTORY_NAME, stringPath); + } + + private Path getPathToFile(FileSystem fileSystem) throws Exception { + Path path = fileSystem.getPath(DIRECTORY_NAME); + Files.createDirectory(path); + + return path; + } +} \ No newline at end of file diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java index 4d592abf70..ebb95e79ac 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java @@ -3,14 +3,11 @@ package com.baeldung.jimfs; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.api.Test; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; -import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; @@ -18,14 +15,10 @@ class FileRepositoryUnitTest implements FileTestProvider { private final FileRepository fileRepository = new FileRepository(); - private static Stream provideFileSystem() { - return Stream.of(Arguments.of(Jimfs.newFileSystem(Configuration.unix())), Arguments.of(Jimfs.newFileSystem(Configuration.windows())), Arguments.of(Jimfs.newFileSystem(Configuration.osX()))); - } - - @ParameterizedTest + @Test @DisplayName("Should create a file on a file system") - @MethodSource("provideFileSystem") - void shouldCreateFile(final FileSystem fileSystem) throws Exception { + void shouldCreateFile() { + final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix()); final String fileName = "newFile.txt"; final Path pathToStore = fileSystem.getPath(""); @@ -34,10 +27,10 @@ class FileRepositoryUnitTest implements FileTestProvider { assertTrue(Files.exists(pathToStore.resolve(fileName))); } - @ParameterizedTest + @Test @DisplayName("Should read the content of the file") - @MethodSource("provideFileSystem") - void shouldReadFileContent_thenReturnIt(final FileSystem fileSystem) throws Exception { + void shouldReadFileContent_thenReturnIt() throws Exception { + final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.osX()); final Path resourceFilePath = fileSystem.getPath(RESOURCE_FILE_NAME); Files.copy(getResourceFilePath(), resourceFilePath); @@ -46,10 +39,10 @@ class FileRepositoryUnitTest implements FileTestProvider { assertEquals(FILE_CONTENT, content); } - @ParameterizedTest - @DisplayName("Should update content of the file") - @MethodSource("provideFileSystem") - void shouldUpdateContentOfTheFile(final FileSystem fileSystem) throws Exception { + @Test + @DisplayName("Should update the content of the file") + void shouldUpdateContentOfTheFile() throws Exception { + final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.windows()); final Path resourceFilePath = fileSystem.getPath(RESOURCE_FILE_NAME); Files.copy(getResourceFilePath(), resourceFilePath); final String newContent = "I'm updating you."; @@ -60,10 +53,10 @@ class FileRepositoryUnitTest implements FileTestProvider { assertEquals(newContent, fileRepository.read(resourceFilePath)); } - @ParameterizedTest - @DisplayName("Should update delete file") - @MethodSource("provideFileSystem") - void shouldDeleteFile(final FileSystem fileSystem) throws Exception { + @Test + @DisplayName("Should delete file") + void shouldDeleteFile() throws Exception { + final FileSystem fileSystem = Jimfs.newFileSystem(); final Path resourceFilePath = fileSystem.getPath(RESOURCE_FILE_NAME); Files.copy(getResourceFilePath(), resourceFilePath); From e6ff0cd990d30d21544f33f9c38df7f223c664e6 Mon Sep 17 00:00:00 2001 From: Lukasz Rys <> Date: Mon, 14 Oct 2019 00:25:27 +0200 Subject: [PATCH 15/38] [ BAEL-3322 ] : Fix test name --- ...rTest.java => FilePathReaderUnitTest.java} | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) rename testing-modules/mocks/src/test/java/com/baeldung/jimfs/{FilePathReaderTest.java => FilePathReaderUnitTest.java} (51%) diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderUnitTest.java similarity index 51% rename from testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderTest.java rename to testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderUnitTest.java index 8a52bd3443..e5326fc84c 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderUnitTest.java @@ -11,19 +11,19 @@ import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.assertEquals; -class FilePathReaderTest { +class FilePathReaderUnitTest { - private static String DIRECTORY_NAME = "baeldung"; + private static final String DIRECTORY_NAME = "baeldung"; - private FilePathReader filePathReader = new FilePathReader(); + private final FilePathReader filePathReader = new FilePathReader(); @Test @DisplayName("Should get path on windows") void shouldGetPath_onWindows() throws Exception { - FileSystem fileSystem = Jimfs.newFileSystem(Configuration.windows()); - Path path = getPathToFile(fileSystem); + final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.windows()); + final Path path = getPathToFile(fileSystem); - String stringPath = filePathReader.getSystemPath(path); + final String stringPath = filePathReader.getSystemPath(path); assertEquals("C:\\work\\" + DIRECTORY_NAME, stringPath); } @@ -31,16 +31,16 @@ class FilePathReaderTest { @Test @DisplayName("Should get path on unix") void shouldGetPath_onUnix() throws Exception { - FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix()); - Path path = getPathToFile(fileSystem); + final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix()); + final Path path = getPathToFile(fileSystem); - String stringPath = filePathReader.getSystemPath(path); + final String stringPath = filePathReader.getSystemPath(path); assertEquals("/work/" + DIRECTORY_NAME, stringPath); } - private Path getPathToFile(FileSystem fileSystem) throws Exception { - Path path = fileSystem.getPath(DIRECTORY_NAME); + private Path getPathToFile(final FileSystem fileSystem) throws Exception { + final Path path = fileSystem.getPath(DIRECTORY_NAME); Files.createDirectory(path); return path; From 16e764c942b08449701a7b24521570ea1188bd11 Mon Sep 17 00:00:00 2001 From: Gang Date: Mon, 14 Oct 2019 14:48:50 -0600 Subject: [PATCH 16/38] BAEL-3349 Knapsack problem implementation in Java --- .../algorithms/knapsack/Knapsack.java | 32 ++++++++++++++ .../algorithms/knapsack/KnapsackUnitTest.java | 44 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/knapsack/Knapsack.java create mode 100644 algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/knapsack/KnapsackUnitTest.java diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/knapsack/Knapsack.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/knapsack/Knapsack.java new file mode 100644 index 0000000000..a53ab21429 --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/knapsack/Knapsack.java @@ -0,0 +1,32 @@ +package com.baeldung.algorithms.knapsack; + +class Knapsack { + + public int knapsackRec(int[] w, int[] v, int n, int W) { + if (n <= 0) + return 0; + else if (w[n - 1] > W) + return knapsackRec(w, v, n - 1, W); + else + return Math.max(knapsackRec(w, v, n - 1, W), v[n - 1] + knapsackRec(w, v, n - 1, W - w[n - 1])); + } + + public int knapsackDP(int[] w, int[] v, int n, int W) { + if (n <= 0 || W <= 0) + return 0; + int[][] m = new int[n + 1][W + 1]; + for (int j = 0; j <= W; j++) { + m[0][j] = 0; + } + + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= W; j++) { + if (w[i - 1] > j) + m[i][j] = m[i - 1][j]; + else + m[i][j] = Math.max(m[i - 1][j], m[i - 1][j - w[i - 1]] + v[i - 1]); + } + } + return m[n][W]; + } +} diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/knapsack/KnapsackUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/knapsack/KnapsackUnitTest.java new file mode 100644 index 0000000000..b168e6b1eb --- /dev/null +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/knapsack/KnapsackUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.algorithms.knapsack; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class KnapsackUnitTest { + + @Test + public void givenWeightsandValues_whenCalculateMax_thenOutputCorrectResult() { + final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 }; + final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 }; + final int n = 10; + final int W = 67; + final Knapsack knapsack = new Knapsack(); + + assertEquals(1270, knapsack.knapsackRec(w, v, n, W)); + assertEquals(1270, knapsack.knapsackDP(w, v, n, W)); + } + + @Test + public void givenZeroItems_whenCalculateMax_thenOutputZero() { + final int[] w = new int[] {}; + final int[] v = new int[] {}; + final int n = 0; + final int W = 67; + final Knapsack knapsack = new Knapsack(); + + assertEquals(0, knapsack.knapsackRec(w, v, n, W)); + assertEquals(0, knapsack.knapsackDP(w, v, n, W)); + } + + @Test + public void givenZeroWeightLimit_whenCalculateMax_thenOutputZero() { + final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 }; + final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 }; + final int n = 10; + final int W = 0; + final Knapsack knapsack = new Knapsack(); + + assertEquals(0, knapsack.knapsackRec(w, v, n, W)); + assertEquals(0, knapsack.knapsackDP(w, v, n, W)); + } +} From 546701f1f7c53d5628c6be1034abffaf3fb8cf26 Mon Sep 17 00:00:00 2001 From: "m.raheem" Date: Tue, 15 Oct 2019 12:42:06 +0200 Subject: [PATCH 17/38] renaming unit tests + removing unused final keyword --- .../baeldung/jackson/deserialization/enums/Distance.java | 6 +++++- .../enums/customdeserializer/CustomEnumDeserializer.java | 8 ++++---- .../enums/customdeserializer/Distance.java | 6 +++++- .../deserialization/enums/jsoncreator/Distance.java | 6 +++++- .../deserialization/enums/jsonproperty/Distance.java | 6 +++++- .../jackson/deserialization/enums/jsonvalue/Distance.java | 6 +++++- ...ation.java => DefaultEnumDeserializationUnitTest.java} | 4 ++-- ...zation.java => EnumCustomDeserializationUnitTest.java} | 4 ++-- ...a => EnumDeserializationUsingJsonCreatorUnitTest.java} | 4 ++-- ... => EnumDeserializationUsingJsonPropertyUnitTest.java} | 4 ++-- ...ava => EnumDeserializationUsingJsonValueUnitTest.java} | 4 ++-- 11 files changed, 39 insertions(+), 19 deletions(-) rename jackson/src/test/java/com/baeldung/jackson/deserialization/enums/{DefaultJacksonEnumDeserialization.java => DefaultEnumDeserializationUnitTest.java} (73%) rename jackson/src/test/java/com/baeldung/jackson/deserialization/enums/customdeserializer/{JacksonEnumCustomDeserialization.java => EnumCustomDeserializationUnitTest.java} (72%) rename jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsoncreator/{JacksonEnumDeserializationUsingJsonCreator.java => EnumDeserializationUsingJsonCreatorUnitTest.java} (72%) rename jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonproperty/{JacksonEnumDeserializationUsingJsonProperty.java => EnumDeserializationUsingJsonPropertyUnitTest.java} (71%) rename jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonvalue/{JacksonEnumDeserializationUsingJsonValue.java => EnumDeserializationUsingJsonValueUnitTest.java} (71%) diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/Distance.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/Distance.java index ce332d34ae..2c96b6eb80 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/Distance.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/Distance.java @@ -5,13 +5,17 @@ public enum Distance { KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); private String unit; - private final double meters; + private double meters; private Distance(String unit, double meters) { this.unit = unit; this.meters = meters; } + public void setMeters(double meters) { + this.meters = meters; + } + public double getMeters() { return meters; } diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/CustomEnumDeserializer.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/CustomEnumDeserializer.java index 21be368e01..bae0c0df34 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/CustomEnumDeserializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/CustomEnumDeserializer.java @@ -15,14 +15,14 @@ public class CustomEnumDeserializer extends StdDeserializer { this(null); } - public CustomEnumDeserializer(Class vc) { - super(vc); + public CustomEnumDeserializer(Class c) { + super(c); } @Override - public Distance deserialize(final JsonParser jsonParser, final DeserializationContext ctxt) throws IOException, JsonProcessingException { + public Distance deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException { - final JsonNode node = jsonParser.getCodec().readTree(jsonParser); + JsonNode node = jsonParser.getCodec().readTree(jsonParser); String unit = node.get("unit").asText(); double meters = node.get("meters").asDouble(); diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/Distance.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/Distance.java index 4766b43435..9cb3a0c391 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/Distance.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/Distance.java @@ -8,7 +8,7 @@ public enum Distance { KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); private String unit; - private final double meters; + private double meters; private Distance(String unit, double meters) { this.unit = unit; @@ -19,6 +19,10 @@ public enum Distance { return meters; } + public void setMeters(double meters) { + this.meters = meters; + } + public String getUnit() { return unit; } diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsoncreator/Distance.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsoncreator/Distance.java index 05c089ef69..18235fb5c6 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsoncreator/Distance.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsoncreator/Distance.java @@ -8,13 +8,17 @@ public enum Distance { KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); private String unit; - private final double meters; + private double meters; private Distance(String unit, double meters) { this.unit = unit; this.meters = meters; } + public void setMeters(double meters) { + this.meters = meters; + } + public double getMeters() { return meters; } diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonproperty/Distance.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonproperty/Distance.java index 2d324d7f8e..e671a9ae5b 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonproperty/Distance.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonproperty/Distance.java @@ -23,13 +23,17 @@ public enum Distance { MILLIMETER("mm", 0.001); private String unit; - private final double meters; + private double meters; private Distance(String unit, double meters) { this.unit = unit; this.meters = meters; } + public void setMeters(double meters) { + this.meters = meters; + } + public double getMeters() { return meters; } diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonvalue/Distance.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonvalue/Distance.java index 06a6f870f5..44bb5f20c3 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonvalue/Distance.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonvalue/Distance.java @@ -7,13 +7,17 @@ public enum Distance { KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); private String unit; - private final double meters; + private double meters; private Distance(String unit, double meters) { this.unit = unit; this.meters = meters; } + public void setMeters(double meters) { + this.meters = meters; + } + @JsonValue public double getMeters() { return meters; diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/DefaultJacksonEnumDeserialization.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/DefaultEnumDeserializationUnitTest.java similarity index 73% rename from jackson/src/test/java/com/baeldung/jackson/deserialization/enums/DefaultJacksonEnumDeserialization.java rename to jackson/src/test/java/com/baeldung/jackson/deserialization/enums/DefaultEnumDeserializationUnitTest.java index 12c9ffa10c..c7ce96e013 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/DefaultJacksonEnumDeserialization.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/DefaultEnumDeserializationUnitTest.java @@ -6,10 +6,10 @@ import org.junit.Test; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.ObjectMapper; -public class DefaultJacksonEnumDeserialization { +public class DefaultEnumDeserializationUnitTest { @Test - public final void givenEnum_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + public void givenEnum_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { String json = "{\"distance\":\"KILOMETER\"}"; City city = new ObjectMapper().readValue(json, City.class); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/customdeserializer/JacksonEnumCustomDeserialization.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/customdeserializer/EnumCustomDeserializationUnitTest.java similarity index 72% rename from jackson/src/test/java/com/baeldung/jackson/deserialization/enums/customdeserializer/JacksonEnumCustomDeserialization.java rename to jackson/src/test/java/com/baeldung/jackson/deserialization/enums/customdeserializer/EnumCustomDeserializationUnitTest.java index 02354a336f..e8dbfa8df8 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/customdeserializer/JacksonEnumCustomDeserialization.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/customdeserializer/EnumCustomDeserializationUnitTest.java @@ -6,10 +6,10 @@ import org.junit.Test; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.ObjectMapper; -public class JacksonEnumCustomDeserialization { +public class EnumCustomDeserializationUnitTest { @Test - public final void givenEnumWithCustomDeserializer_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + public void givenEnumWithCustomDeserializer_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { String json = "{\"distance\": {\"unit\":\"miles\",\"meters\":1609.34}}"; City city = new ObjectMapper().readValue(json, City.class); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsoncreator/JacksonEnumDeserializationUsingJsonCreator.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsoncreator/EnumDeserializationUsingJsonCreatorUnitTest.java similarity index 72% rename from jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsoncreator/JacksonEnumDeserializationUsingJsonCreator.java rename to jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsoncreator/EnumDeserializationUsingJsonCreatorUnitTest.java index eaa06d34b0..d778cbe26b 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsoncreator/JacksonEnumDeserializationUsingJsonCreator.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsoncreator/EnumDeserializationUsingJsonCreatorUnitTest.java @@ -6,10 +6,10 @@ import org.junit.Test; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.ObjectMapper; -public class JacksonEnumDeserializationUsingJsonCreator { +public class EnumDeserializationUsingJsonCreatorUnitTest { @Test - public final void givenEnumWithJsonCreator_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + public void givenEnumWithJsonCreator_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { String json = "{\"distance\": {\"unit\":\"miles\",\"meters\":1609.34}}"; City city = new ObjectMapper().readValue(json, City.class); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonproperty/JacksonEnumDeserializationUsingJsonProperty.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonproperty/EnumDeserializationUsingJsonPropertyUnitTest.java similarity index 71% rename from jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonproperty/JacksonEnumDeserializationUsingJsonProperty.java rename to jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonproperty/EnumDeserializationUsingJsonPropertyUnitTest.java index 2743727f98..134f4a29cc 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonproperty/JacksonEnumDeserializationUsingJsonProperty.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonproperty/EnumDeserializationUsingJsonPropertyUnitTest.java @@ -6,10 +6,10 @@ import org.junit.Test; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.ObjectMapper; -public class JacksonEnumDeserializationUsingJsonProperty { +public class EnumDeserializationUsingJsonPropertyUnitTest { @Test - public final void givenEnumWithJsonProperty_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + public void givenEnumWithJsonProperty_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { String json = "{\"distance\": \"distance-in-km\"}"; City city = new ObjectMapper().readValue(json, City.class); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonvalue/JacksonEnumDeserializationUsingJsonValue.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonvalue/EnumDeserializationUsingJsonValueUnitTest.java similarity index 71% rename from jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonvalue/JacksonEnumDeserializationUsingJsonValue.java rename to jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonvalue/EnumDeserializationUsingJsonValueUnitTest.java index d49cd4771b..85afcb9a69 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonvalue/JacksonEnumDeserializationUsingJsonValue.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonvalue/EnumDeserializationUsingJsonValueUnitTest.java @@ -6,10 +6,10 @@ import org.junit.Test; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.ObjectMapper; -public class JacksonEnumDeserializationUsingJsonValue { +public class EnumDeserializationUsingJsonValueUnitTest { @Test - public final void givenEnumWithJsonValue_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + public void givenEnumWithJsonValue_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { String json = "{\"distance\": \"0.0254\"}"; City city = new ObjectMapper().readValue(json, City.class); From 7bc98e99c10657757e04f29de371eaf0b2a4b622 Mon Sep 17 00:00:00 2001 From: Kamlesh Kumar Date: Sun, 13 Oct 2019 12:48:59 +0530 Subject: [PATCH 18/38] BAEL-1363: Review Comments - applications port updated --- .../api-gateway/src/main/resources/application.yml | 4 ++-- .../weather-service/src/main/resources/application.yml | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/resources/application.yml b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/resources/application.yml index 9a7d3314a3..4a0662a960 100644 --- a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/resources/application.yml @@ -2,7 +2,7 @@ spring: application: name: api-gateway server: - port: 8008 + port: 7070 zuul: igoredServices: '*' @@ -18,5 +18,5 @@ ribbon: weather-service: ribbon: - listOfServers: localhost:7070 + listOfServers: localhost:8080 diff --git a/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/resources/application.yml b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/resources/application.yml index 30ceeee438..242f842f44 100644 --- a/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/resources/application.yml @@ -1,5 +1,4 @@ spring: application: name: weather-service -server: - port: 7070 + From 85b5042cb7c6ca1c7c09dcfa7f782cc66648376e Mon Sep 17 00:00:00 2001 From: Gang Date: Tue, 15 Oct 2019 21:19:57 -0600 Subject: [PATCH 19/38] BAEL-3349, Add brackets and make the class public --- .../baeldung/algorithms/knapsack/Knapsack.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/knapsack/Knapsack.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/knapsack/Knapsack.java index a53ab21429..61c3f05a95 100644 --- a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/knapsack/Knapsack.java +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/knapsack/Knapsack.java @@ -1,19 +1,22 @@ package com.baeldung.algorithms.knapsack; -class Knapsack { +public class Knapsack { public int knapsackRec(int[] w, int[] v, int n, int W) { - if (n <= 0) + if (n <= 0) { return 0; - else if (w[n - 1] > W) + } else if (w[n - 1] > W) { return knapsackRec(w, v, n - 1, W); - else + } else { return Math.max(knapsackRec(w, v, n - 1, W), v[n - 1] + knapsackRec(w, v, n - 1, W - w[n - 1])); + } } public int knapsackDP(int[] w, int[] v, int n, int W) { - if (n <= 0 || W <= 0) + if (n <= 0 || W <= 0) { return 0; + } + int[][] m = new int[n + 1][W + 1]; for (int j = 0; j <= W; j++) { m[0][j] = 0; @@ -21,10 +24,11 @@ class Knapsack { for (int i = 1; i <= n; i++) { for (int j = 1; j <= W; j++) { - if (w[i - 1] > j) + if (w[i - 1] > j) { m[i][j] = m[i - 1][j]; - else + } else { m[i][j] = Math.max(m[i - 1][j], m[i - 1][j - w[i - 1]] + v[i - 1]); + } } } return m[n][W]; From ba4c7594a63ff1bb4ecb504e3851ef453c96a173 Mon Sep 17 00:00:00 2001 From: Lukasz Rys <> Date: Fri, 18 Oct 2019 19:40:55 +0200 Subject: [PATCH 20/38] [ BAEL-3322 ] : Change method test names --- .../java/com/baeldung/jimfs/FileManipulationUnitTest.java | 4 ++-- .../java/com/baeldung/jimfs/FilePathReaderUnitTest.java | 4 ++-- .../java/com/baeldung/jimfs/FileRepositoryUnitTest.java | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileManipulationUnitTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileManipulationUnitTest.java index a7cb8e53c6..05f3405e57 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileManipulationUnitTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileManipulationUnitTest.java @@ -24,9 +24,9 @@ class FileManipulationUnitTest implements FileTestProvider { } @ParameterizedTest - @DisplayName("Should create a file on a file system") + @DisplayName("Should move file to new destination") @MethodSource("provideFileSystem") - void shouldCreateFile(final FileSystem fileSystem) throws Exception { + void givenEachSystem_whenMovingFile_thenMovedToNewPath(final FileSystem fileSystem) throws Exception { final Path origin = fileSystem.getPath(RESOURCE_FILE_NAME); Files.copy(getResourceFilePath(), origin); final Path destination = fileSystem.getPath("newDirectory", RESOURCE_FILE_NAME); diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderUnitTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderUnitTest.java index e5326fc84c..f95b76a86d 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderUnitTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderUnitTest.java @@ -19,7 +19,7 @@ class FilePathReaderUnitTest { @Test @DisplayName("Should get path on windows") - void shouldGetPath_onWindows() throws Exception { + void givenWindowsSystem_shouldGetPath_thenReturnWindowsPath() throws Exception { final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.windows()); final Path path = getPathToFile(fileSystem); @@ -30,7 +30,7 @@ class FilePathReaderUnitTest { @Test @DisplayName("Should get path on unix") - void shouldGetPath_onUnix() throws Exception { + void givenUnixSystem_shouldGetPath_thenReturnUnixPath() throws Exception { final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix()); final Path path = getPathToFile(fileSystem); diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java index ebb95e79ac..b7dc1f91de 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java @@ -17,7 +17,7 @@ class FileRepositoryUnitTest implements FileTestProvider { @Test @DisplayName("Should create a file on a file system") - void shouldCreateFile() { + void givenUnixSystem_whenCreatingFile_thenCreatedInPath() { final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix()); final String fileName = "newFile.txt"; final Path pathToStore = fileSystem.getPath(""); @@ -29,7 +29,7 @@ class FileRepositoryUnitTest implements FileTestProvider { @Test @DisplayName("Should read the content of the file") - void shouldReadFileContent_thenReturnIt() throws Exception { + void givenOSXSystem_whenReadingFile_thenContentIsReturned() throws Exception { final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.osX()); final Path resourceFilePath = fileSystem.getPath(RESOURCE_FILE_NAME); Files.copy(getResourceFilePath(), resourceFilePath); @@ -41,7 +41,7 @@ class FileRepositoryUnitTest implements FileTestProvider { @Test @DisplayName("Should update the content of the file") - void shouldUpdateContentOfTheFile() throws Exception { + void givenWindowsSystem_whenUpdatingFile_thenContentHasChanged() throws Exception { final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.windows()); final Path resourceFilePath = fileSystem.getPath(RESOURCE_FILE_NAME); Files.copy(getResourceFilePath(), resourceFilePath); @@ -55,7 +55,7 @@ class FileRepositoryUnitTest implements FileTestProvider { @Test @DisplayName("Should delete file") - void shouldDeleteFile() throws Exception { + void givenRandomSystem_whenDeletingFile_thenFileHasBeenDeleted() throws Exception { final FileSystem fileSystem = Jimfs.newFileSystem(); final Path resourceFilePath = fileSystem.getPath(RESOURCE_FILE_NAME); Files.copy(getResourceFilePath(), resourceFilePath); From bb0178340dd165664d2ffa4e4e94776d6f89c388 Mon Sep 17 00:00:00 2001 From: Lukasz Rys <> Date: Fri, 18 Oct 2019 20:04:51 +0200 Subject: [PATCH 21/38] [ BAEL-3322 ] : Change naming, add final --- .../src/main/java/com/baeldung/jimfs/FilePathReader.java | 5 +++-- .../test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FilePathReader.java b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FilePathReader.java index 3504207125..9c5371910e 100644 --- a/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FilePathReader.java +++ b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FilePathReader.java @@ -5,12 +5,13 @@ import java.io.UncheckedIOException; import java.nio.file.Path; class FilePathReader { - String getSystemPath(Path path) { + + String getSystemPath(final Path path) { try { return path .toRealPath() .toString(); - } catch (IOException ex) { + } catch (final IOException ex) { throw new UncheckedIOException(ex); } } diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java index b7dc1f91de..c72c2f1a1f 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java @@ -55,7 +55,7 @@ class FileRepositoryUnitTest implements FileTestProvider { @Test @DisplayName("Should delete file") - void givenRandomSystem_whenDeletingFile_thenFileHasBeenDeleted() throws Exception { + void givenCurrentSystem_whenDeletingFile_thenFileHasBeenDeleted() throws Exception { final FileSystem fileSystem = Jimfs.newFileSystem(); final Path resourceFilePath = fileSystem.getPath(RESOURCE_FILE_NAME); Files.copy(getResourceFilePath(), resourceFilePath); From f0df9a7998b9c02bf131e63b857c85f87fcfb665 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Fri, 18 Oct 2019 23:39:07 +0530 Subject: [PATCH 22/38] BAEL-17684 Pom properties cleanup --- ddd/pom.xml | 4 --- disruptor/pom.xml | 11 +-------- dozer/pom.xml | 1 - dubbo/pom.xml | 1 - ethereum/pom.xml | 3 --- flyway-cdi-extension/pom.xml | 3 --- google-web-toolkit/pom.xml | 1 - gson/pom.xml | 1 - guava-collections-map/pom.xml | 6 ----- guava-collections-set/pom.xml | 3 --- guava-collections/pom.xml | 2 -- guava-io/pom.xml | 1 - guava-modules/guava-18/pom.xml | 4 --- guava-modules/guava-19/pom.xml | 4 --- guava-modules/guava-21/pom.xml | 1 - guava/pom.xml | 4 --- hazelcast/pom.xml | 1 - httpclient-simple/pom.xml | 1 - httpclient/pom.xml | 45 ---------------------------------- hystrix/pom.xml | 14 ----------- 20 files changed, 1 insertion(+), 110 deletions(-) diff --git a/ddd/pom.xml b/ddd/pom.xml index 4ac65ea841..c249007ba4 100644 --- a/ddd/pom.xml +++ b/ddd/pom.xml @@ -3,7 +3,6 @@ 4.0.0 com.baeldung.ddd ddd - 0.0.1-SNAPSHOT ddd jar DDD series examples @@ -35,7 +34,6 @@ org.junit.platform junit-platform-launcher - ${junit-platform.version} test @@ -85,8 +83,6 @@ 1.0.1 - 2.22.0 - 2.0.6.RELEASE \ No newline at end of file diff --git a/disruptor/pom.xml b/disruptor/pom.xml index e1d78e7ed6..a4859d4bae 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung disruptor 0.1.0-SNAPSHOT disruptor @@ -15,11 +14,6 @@ - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - com.lmax disruptor @@ -116,10 +110,7 @@ 3.3.6 - - 6.10 - 3.6.1 - + 2.4.3 3.0.2 1.4.4 diff --git a/dozer/pom.xml b/dozer/pom.xml index 8234eb4c79..c781962d83 100644 --- a/dozer/pom.xml +++ b/dozer/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung dozer 1.0 dozer diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 9fe228bf89..947175b6a0 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -32,7 +32,6 @@ 2.5.7 3.4.11 0.10 - 2.19.1 diff --git a/ethereum/pom.xml b/ethereum/pom.xml index 80e1c04676..f4850df844 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -3,7 +3,6 @@ 4.0.0 com.baeldung.ethereum ethereum - 0.0.1-SNAPSHOT ethereum @@ -207,8 +206,6 @@ - UTF-8 - 8.5.4 1.5.0-RELEASE 3.3.1 1.5.6.RELEASE diff --git a/flyway-cdi-extension/pom.xml b/flyway-cdi-extension/pom.xml index e8b327e35f..49bd6bd9fd 100644 --- a/flyway-cdi-extension/pom.xml +++ b/flyway-cdi-extension/pom.xml @@ -3,7 +3,6 @@ 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"> 4.0.0 - com.baeldung flyway-cdi-extension 1.0-SNAPSHOT flyway-cdi-extension @@ -51,8 +50,6 @@ - 1.8 - 1.8 2.0.SP1 3.0.5.Final 5.1.4 diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml index 0723cd3be2..8a7cb87701 100644 --- a/google-web-toolkit/pom.xml +++ b/google-web-toolkit/pom.xml @@ -5,7 +5,6 @@ 4.0.0 - com.baeldung google-web-toolkit 1.0-SNAPSHOT google-web-toolkit diff --git a/gson/pom.xml b/gson/pom.xml index 9d2cf630d0..4aa6c00458 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -2,7 +2,6 @@ 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"> 4.0.0 - com.baeldung gson 0.1-SNAPSHOT gson diff --git a/guava-collections-map/pom.xml b/guava-collections-map/pom.xml index 45bb6b8caa..21597d0e28 100644 --- a/guava-collections-map/pom.xml +++ b/guava-collections-map/pom.xml @@ -13,9 +13,6 @@ ../parent-java - - - guava-collections-map @@ -26,7 +23,4 @@ - - - \ No newline at end of file diff --git a/guava-collections-set/pom.xml b/guava-collections-set/pom.xml index 46dcae492d..640a28c4c1 100644 --- a/guava-collections-set/pom.xml +++ b/guava-collections-set/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung guava-collections-set 0.1.0-SNAPSHOT guava-collections-set @@ -28,8 +27,6 @@ - - 27.1-jre 3.6.1 diff --git a/guava-collections/pom.xml b/guava-collections/pom.xml index 8cdb086029..9dfcceaab8 100644 --- a/guava-collections/pom.xml +++ b/guava-collections/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung guava-collections 0.1.0-SNAPSHOT guava-collections @@ -54,7 +53,6 @@ - 24.0-jre 4.1 diff --git a/guava-io/pom.xml b/guava-io/pom.xml index 2a66baba80..aaaf7edd4e 100644 --- a/guava-io/pom.xml +++ b/guava-io/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung guava-io 0.1.0-SNAPSHOT guava-io diff --git a/guava-modules/guava-18/pom.xml b/guava-modules/guava-18/pom.xml index d55aa9ce82..199d735a41 100644 --- a/guava-modules/guava-18/pom.xml +++ b/guava-modules/guava-18/pom.xml @@ -13,8 +13,4 @@ ../../parent-java - - 18.0 - - \ No newline at end of file diff --git a/guava-modules/guava-19/pom.xml b/guava-modules/guava-19/pom.xml index 0548bb0c1f..c431f78cf7 100644 --- a/guava-modules/guava-19/pom.xml +++ b/guava-modules/guava-19/pom.xml @@ -13,8 +13,4 @@ ../../parent-java - - 19.0 - - \ No newline at end of file diff --git a/guava-modules/guava-21/pom.xml b/guava-modules/guava-21/pom.xml index bdb1058a48..150ce2d4d2 100644 --- a/guava-modules/guava-21/pom.xml +++ b/guava-modules/guava-21/pom.xml @@ -22,7 +22,6 @@ - 21.0 0.9.12 diff --git a/guava/pom.xml b/guava/pom.xml index 3a19901a02..fb8989111c 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung guava 0.1.0-SNAPSHOT guava @@ -41,9 +40,6 @@ - - 24.0-jre - 3.6.1 diff --git a/hazelcast/pom.xml b/hazelcast/pom.xml index 705792ad05..9e0b0671d0 100644 --- a/hazelcast/pom.xml +++ b/hazelcast/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung hazelcast 0.0.1-SNAPSHOT hazelcast diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml index b2b0f98dd1..183c4438de 100644 --- a/httpclient-simple/pom.xml +++ b/httpclient-simple/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung httpclient-simple 0.1-SNAPSHOT httpclient-simple diff --git a/httpclient/pom.xml b/httpclient/pom.xml index 8cd483cfc6..6316ee4eed 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung httpclient 0.1-SNAPSHOT httpclient @@ -48,11 +47,6 @@ httpmime ${httpclient.version} - - commons-codec - commons-codec - ${commons-codec.version} - org.apache.httpcomponents httpasyncclient @@ -82,51 +76,12 @@ - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*LiveTest.java - - - - - - - json - - - - - - - - - 19.0 - 1.10 4.1.4 2.5.1 4.5.8 - - 1.6.1 \ No newline at end of file diff --git a/hystrix/pom.xml b/hystrix/pom.xml index e08af2c40f..4aeb47f095 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -41,23 +41,11 @@ hystrix-metrics-event-stream ${hystrix-metrics-event-stream.version} - com.netflix.rxjava rxjava-core ${rxjava-core.version} - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - test - - - org.springframework - spring-test - test - @@ -65,9 +53,7 @@ 1.5.8 0.20.7 - 2.7 1.5.8 - 1.5.8 From 9405318805ceeb2e389ea497c3d178f7d2130b2d Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Fri, 18 Oct 2019 23:48:22 +0530 Subject: [PATCH 23/38] BAEL-17684 Pom properties cleanup --- disruptor/pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/disruptor/pom.xml b/disruptor/pom.xml index a4859d4bae..213331f25c 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -14,6 +14,11 @@ + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + com.lmax disruptor From 88a83f5d2c0eb15ffd574ddb9b3ed929bf497694 Mon Sep 17 00:00:00 2001 From: Vivek Balasubramaniam Date: Sat, 19 Oct 2019 17:46:30 +0530 Subject: [PATCH 24/38] BAEL-3091: The Prototype Pattern in Java (Code review comments) --- .../src/main/java/com/baeldung/prototype/Tree.java | 8 ++++---- .../main/java/com/baeldung/prototype/TreeCloneable.java | 7 ------- .../com/baeldung/prototype/TreePrototypeUnitTest.java | 4 ++-- 3 files changed, 6 insertions(+), 13 deletions(-) delete mode 100644 patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/TreeCloneable.java diff --git a/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java index 242ed2176e..470704765c 100644 --- a/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java +++ b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java @@ -1,6 +1,6 @@ package com.baeldung.prototype; -public class Tree implements TreeCloneable { +public class Tree implements Cloneable { private double mass; private double height; @@ -36,10 +36,10 @@ public class Tree implements TreeCloneable { } @Override - public TreeCloneable createA_Clone() { - TreeCloneable tree = null; + public Tree clone() { + Tree tree = null; try { - tree = (TreeCloneable) super.clone(); + tree = (Tree) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } diff --git a/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/TreeCloneable.java b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/TreeCloneable.java deleted file mode 100644 index e554058624..0000000000 --- a/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/TreeCloneable.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.prototype; - -public interface TreeCloneable extends Cloneable { - - public TreeCloneable createA_Clone(); - -} diff --git a/patterns/design-patterns-creational/src/test/java/com/baeldung/prototype/TreePrototypeUnitTest.java b/patterns/design-patterns-creational/src/test/java/com/baeldung/prototype/TreePrototypeUnitTest.java index 7f260c52bf..0d06da53d6 100644 --- a/patterns/design-patterns-creational/src/test/java/com/baeldung/prototype/TreePrototypeUnitTest.java +++ b/patterns/design-patterns-creational/src/test/java/com/baeldung/prototype/TreePrototypeUnitTest.java @@ -12,10 +12,10 @@ public class TreePrototypeUnitTest { double height = 3.7; Position position = new Position(3, 7); Position otherPosition = new Position(4, 8); - + Tree tree = new Tree(mass, height); tree.setPosition(position); - Tree anotherTree = (Tree) tree.createA_Clone(); + Tree anotherTree = tree.clone(); anotherTree.setPosition(otherPosition); assertEquals(position, tree.getPosition()); From a5f90502fc8a584646102416fcb258bc13924d62 Mon Sep 17 00:00:00 2001 From: Vivek Balasubramaniam Date: Sat, 19 Oct 2019 18:00:56 +0530 Subject: [PATCH 25/38] Minor changes to the toString() method --- .../src/main/java/com/baeldung/prototype/Tree.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java index 470704765c..f95d568647 100644 --- a/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java +++ b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java @@ -48,7 +48,7 @@ public class Tree implements Cloneable { @Override public String toString() { - return "SomeTree [mass=" + mass + ", height=" + height + ", position=" + position + "]"; + return "Tree [mass=" + mass + ", height=" + height + ", position=" + position + "]"; } } From 33a31701cd5d5b21ae64467cfc7d83b7ed1d87e5 Mon Sep 17 00:00:00 2001 From: fejera Date: Sat, 19 Oct 2019 16:43:11 +0200 Subject: [PATCH 26/38] cleaned up persistence.xml --- .../java-jpa-2/src/main/resources/META-INF/persistence.xml | 2 -- 1 file changed, 2 deletions(-) diff --git a/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml index 0602a82f6c..faf00e1b2b 100644 --- a/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml @@ -144,8 +144,6 @@ - - From 22deaaa756ee547ed0b00a6a192fd1541c315f93 Mon Sep 17 00:00:00 2001 From: NickTononi <48349671+NickTononi@users.noreply.github.com> Date: Sat, 19 Oct 2019 22:19:09 +0200 Subject: [PATCH 27/38] [BAEL-3147] Java 'protected' modifier (#7886) * [BAEL-3147] Java 'protected' modifier * updated README.md * Update README.md * Update SecondGenericClass.java --- .../baeldung/core/modifiers/FirstClass.java | 18 +++++++++++++++++ .../baeldung/core/modifiers/GenericClass.java | 15 ++++++++++++++ .../modifiers/otherpackage/SecondClass.java | 18 +++++++++++++++++ .../otherpackage/SecondGenericClass.java | 20 +++++++++++++++++++ 4 files changed, 71 insertions(+) create mode 100644 core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/FirstClass.java create mode 100644 core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/GenericClass.java create mode 100644 core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/otherpackage/SecondClass.java create mode 100644 core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/otherpackage/SecondGenericClass.java diff --git a/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/FirstClass.java b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/FirstClass.java new file mode 100644 index 0000000000..a80387d61a --- /dev/null +++ b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/FirstClass.java @@ -0,0 +1,18 @@ +package com.baeldung.core.modifiers; + +public class FirstClass { + + protected String name; + + protected FirstClass(String name) { + this.name = name; + } + + protected String getName() { + return name; + } + + protected static class InnerClass { + public InnerClass() {} + } +} diff --git a/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/GenericClass.java b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/GenericClass.java new file mode 100644 index 0000000000..83381931d0 --- /dev/null +++ b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/GenericClass.java @@ -0,0 +1,15 @@ +package com.baeldung.core.modifiers; + +public class GenericClass { + + public static void main(String[] args) { + // accessing protected constructor + FirstClass first = new FirstClass("random name"); + // using protected method + System.out.println("FirstClass name is " + first.getName()); + // accessing a protected field + first.name = "new name"; + // instantiating protected inner class + FirstClass.InnerClass innerClass = new FirstClass.InnerClass(); + } +} diff --git a/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/otherpackage/SecondClass.java b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/otherpackage/SecondClass.java new file mode 100644 index 0000000000..528f97539a --- /dev/null +++ b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/otherpackage/SecondClass.java @@ -0,0 +1,18 @@ +package com.baeldung.core.modifiers.otherpackage; + +import com.baeldung.core.modifiers.FirstClass; + +public class SecondClass extends FirstClass { + + public SecondClass(String name) { + // accessing protected constructor + super(name); + // using protected method + System.out.println("SecondClass name is " + this.getName()); + // accessing a protected field + this.name = "new name"; + // instantiating protected inner class -> add public constructor to InnerClass + FirstClass.InnerClass innerClass = new FirstClass.InnerClass(); + } + +} diff --git a/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/otherpackage/SecondGenericClass.java b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/otherpackage/SecondGenericClass.java new file mode 100644 index 0000000000..d29533edef --- /dev/null +++ b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/otherpackage/SecondGenericClass.java @@ -0,0 +1,20 @@ +package com.baeldung.core.modifiers.otherpackage; + +import com.baeldung.core.modifiers.FirstClass; +//import com.baeldung.core.modifiers.FirstClass.InnerClass; + +public class SecondGenericClass { + + // uncomment the following lines to see the errors + public static void main(String[] args) { + // accessing protected constructor + // FirstClass first = new FirstClass("random name"); + // using protected method + // System.out.println("FirstClass name is " + first.getName()); + // accessing a protected field + // first.name = "new name"; + // instantiating protected inner class + // FirstClass.InnerClass innerClass = new FirstClass.InnerClass(); + } + +} From 1fb34e3c6ae0a2562297a1414ece52f41b547898 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Mon, 21 Oct 2019 21:42:13 +0530 Subject: [PATCH 28/38] BAEL-17684 Pom properties cleanup - Reverted guava module changes --- guava-modules/guava-18/pom.xml | 4 ++++ guava-modules/guava-19/pom.xml | 4 ++++ guava-modules/guava-21/pom.xml | 1 + 3 files changed, 9 insertions(+) diff --git a/guava-modules/guava-18/pom.xml b/guava-modules/guava-18/pom.xml index 199d735a41..d55aa9ce82 100644 --- a/guava-modules/guava-18/pom.xml +++ b/guava-modules/guava-18/pom.xml @@ -13,4 +13,8 @@ ../../parent-java + + 18.0 + + \ No newline at end of file diff --git a/guava-modules/guava-19/pom.xml b/guava-modules/guava-19/pom.xml index c431f78cf7..0548bb0c1f 100644 --- a/guava-modules/guava-19/pom.xml +++ b/guava-modules/guava-19/pom.xml @@ -13,4 +13,8 @@ ../../parent-java + + 19.0 + + \ No newline at end of file diff --git a/guava-modules/guava-21/pom.xml b/guava-modules/guava-21/pom.xml index 150ce2d4d2..bdb1058a48 100644 --- a/guava-modules/guava-21/pom.xml +++ b/guava-modules/guava-21/pom.xml @@ -22,6 +22,7 @@ + 21.0 0.9.12 From 15bf90a2bed930d9403f2c066cc53021c143454f Mon Sep 17 00:00:00 2001 From: at508 Date: Mon, 21 Oct 2019 22:04:26 -0400 Subject: [PATCH 29/38] [BAEL-2998] - Fix jenkins tests --- testing-modules/spring-testing/pom.xml | 8 +++++++- .../dirtiescontext/DirtiesContextIntegrationTest.java | 2 ++ .../ProfilePropertySourceResolverIntegrationTest.java | 10 +++++++--- ...pringBootPropertySourceResolverIntegrationTest.java | 8 ++++++-- ...tResourcePropertySourceResolverIntegrationTest.java | 10 +++++++--- 5 files changed, 29 insertions(+), 9 deletions(-) diff --git a/testing-modules/spring-testing/pom.xml b/testing-modules/spring-testing/pom.xml index 8a76dc903c..15431cfb77 100644 --- a/testing-modules/spring-testing/pom.xml +++ b/testing-modules/spring-testing/pom.xml @@ -84,6 +84,11 @@ ${junit.jupiter.version} test + + org.junit.platform + junit-platform-commons + ${junit.commons.version} + org.awaitility awaitility @@ -112,7 +117,8 @@ 2.0.0.0 3.1.6 - 5.4.0 + 5.5.0 + 1.5.2 5.1.4.RELEASE 4.0.1 2.1.1 diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/dirtiescontext/DirtiesContextIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/dirtiescontext/DirtiesContextIntegrationTest.java index f3e7b8c228..7afd4a22d4 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/dirtiescontext/DirtiesContextIntegrationTest.java +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/dirtiescontext/DirtiesContextIntegrationTest.java @@ -10,10 +10,12 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.MethodMode; import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; @TestMethodOrder(OrderAnnotation.class) @ExtendWith(SpringExtension.class) @SpringBootTest(classes = SpringDataRestApplication.class) +@EnableWebMvc class DirtiesContextIntegrationTest { @Autowired diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java index 95d83420b7..815b628f0a 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java @@ -1,21 +1,25 @@ package com.baeldung.overrideproperties; -import com.baeldung.overrideproperties.resolver.PropertySourceResolver; +import static org.junit.Assert.assertEquals; + 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.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.junit.Assert.assertEquals; +import com.baeldung.overrideproperties.resolver.PropertySourceResolver; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") +@EnableWebMvc public class ProfilePropertySourceResolverIntegrationTest { - @Autowired private PropertySourceResolver propertySourceResolver; + @Autowired + private PropertySourceResolver propertySourceResolver; @Test public void shouldProfiledProperty_overridePropertyValues() { diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java index 573a46dd5f..d00aa51e6c 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java @@ -1,18 +1,22 @@ package com.baeldung.overrideproperties; -import com.baeldung.overrideproperties.resolver.PropertySourceResolver; import org.junit.Assert; 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.test.context.junit4.SpringRunner; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +import com.baeldung.overrideproperties.resolver.PropertySourceResolver; @RunWith(SpringRunner.class) @SpringBootTest(properties = { "example.firstProperty=annotation" }) +@EnableWebMvc public class SpringBootPropertySourceResolverIntegrationTest { - @Autowired private PropertySourceResolver propertySourceResolver; + @Autowired + private PropertySourceResolver propertySourceResolver; @Test public void shouldSpringBootTestAnnotation_overridePropertyValues() { diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java index c724713854..dc15851277 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java @@ -1,19 +1,23 @@ package com.baeldung.overrideproperties; -import com.baeldung.overrideproperties.resolver.PropertySourceResolver; +import static org.junit.Assert.assertEquals; + 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.test.context.junit4.SpringRunner; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.junit.Assert.assertEquals; +import com.baeldung.overrideproperties.resolver.PropertySourceResolver; @RunWith(SpringRunner.class) @SpringBootTest +@EnableWebMvc public class TestResourcePropertySourceResolverIntegrationTest { - @Autowired private PropertySourceResolver propertySourceResolver; + @Autowired + private PropertySourceResolver propertySourceResolver; @Test public void shouldTestResourceFile_overridePropertyValues() { From bcf119bf1a0c00c33418c7c0de3dc1c0ccd26cda Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Wed, 23 Oct 2019 06:50:50 +0530 Subject: [PATCH 30/38] Spring Integration Java DSL - Github Issue 7885 (#8060) * Spring Integration Java DSL - Github Issue 7885 - Fixed the bridge example * Spring Integration Java DSL - Github Issue 7885 - Fixed the bridge example --- .../java/com/baeldung/dsl/JavaDSLFileCopyConfig.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java b/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java index 7e91345f04..e79eec3e83 100644 --- a/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java +++ b/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java @@ -16,8 +16,10 @@ import org.springframework.integration.core.MessageSource; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.Pollers; +import org.springframework.integration.dsl.channel.MessageChannels; import org.springframework.integration.file.FileReadingMessageSource; import org.springframework.integration.file.FileWritingMessageHandler; +import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; /** @@ -104,9 +106,14 @@ public class JavaDSLFileCopyConfig { return handler; } + @Bean + public MessageChannel holdingTank() { + return MessageChannels.queue().get(); + } + // @Bean public IntegrationFlow fileReader() { - return IntegrationFlows.from(sourceDirectory()) + return IntegrationFlows.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10))) .filter(onlyJpgs()) .channel("holdingTank") .get(); From 1de7b016a87b375e4573661f880cfcd24265c3e2 Mon Sep 17 00:00:00 2001 From: Martin van Wingerden Date: Wed, 23 Oct 2019 11:04:40 +0200 Subject: [PATCH 31/38] [BAEL-3315] Added missing code snippets from the Java 8 Date/Time article Also: - formatted changed files with Eclipse profile - corrected failing test: givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix --- .../datetime/UseDateTimeFormatter.java | 21 ++++++++++ .../com/baeldung/datetime/UseLocalDate.java | 7 +++- .../baeldung/datetime/UseLocalDateTime.java | 4 ++ .../com/baeldung/datetime/UseLocalTime.java | 4 ++ .../baeldung/datetime/UseOffsetDateTime.java | 11 +++++ .../baeldung/datetime/UseZonedDateTime.java | 24 ++++++----- .../com/baeldung/date/DateDiffUnitTest.java | 11 ++--- ...DateTimeApiGeneralComparisonsUnitTest.java | 28 +++++++++---- .../dateapi/JavaDurationUnitTest.java | 35 ++++++++++++++-- .../baeldung/dateapi/JavaPeriodUnitTest.java | 41 +++++++++++++++---- .../UseDateTimeFormatterUnitTest.java | 36 ++++++++++++++++ .../datetime/UseLocalDateTimeUnitTest.java | 27 +++++++++++- .../datetime/UseLocalDateUnitTest.java | 29 ++++++++++++- .../datetime/UseLocalTimeUnitTest.java | 17 ++++++-- .../datetime/UseOffsetDateTimeUnitTest.java | 24 +++++++++++ .../datetime/UseToInstantUnitTest.java | 33 +++++++++++++++ .../datetime/UseZonedDateTimeUnitTest.java | 21 +++++++++- 17 files changed, 330 insertions(+), 43 deletions(-) create mode 100644 java-dates/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java create mode 100644 java-dates/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java create mode 100644 java-dates/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java create mode 100644 java-dates/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java create mode 100644 java-dates/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java b/java-dates/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java new file mode 100644 index 0000000000..13a2ba6a1a --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java @@ -0,0 +1,21 @@ +package com.baeldung.datetime; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.FormatStyle; +import java.util.Locale; + +public class UseDateTimeFormatter { + public String formatAsIsoDate(LocalDateTime localDateTime) { + return localDateTime.format(DateTimeFormatter.ISO_DATE); + } + + public String formatCustom(LocalDateTime localDateTime, String pattern) { + return localDateTime.format(DateTimeFormatter.ofPattern(pattern)); + } + + public String formatWithStyleAndLocale(LocalDateTime localDateTime, FormatStyle formatStyle, Locale locale) { + return localDateTime.format(DateTimeFormatter.ofLocalizedDateTime(formatStyle) + .withLocale(locale)); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseLocalDate.java b/java-dates/src/main/java/com/baeldung/datetime/UseLocalDate.java index b380c04fc2..ec8dfa2fc4 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/UseLocalDate.java +++ b/java-dates/src/main/java/com/baeldung/datetime/UseLocalDate.java @@ -36,10 +36,15 @@ class UseLocalDate { } LocalDate getFirstDayOfMonth() { - LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()); + LocalDate firstDayOfMonth = LocalDate.now() + .with(TemporalAdjusters.firstDayOfMonth()); return firstDayOfMonth; } + boolean isLeapYear(LocalDate localDate) { + return localDate.isLeapYear(); + } + LocalDateTime getStartOfDay(LocalDate localDate) { LocalDateTime startofDay = localDate.atStartOfDay(); return startofDay; diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/java-dates/src/main/java/com/baeldung/datetime/UseLocalDateTime.java index b2ff11ba16..267a9412eb 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/UseLocalDateTime.java +++ b/java-dates/src/main/java/com/baeldung/datetime/UseLocalDateTime.java @@ -2,6 +2,7 @@ package com.baeldung.datetime; import java.time.LocalDateTime; import java.time.LocalTime; +import java.time.ZoneOffset; import java.time.temporal.ChronoField; public class UseLocalDateTime { @@ -21,4 +22,7 @@ public class UseLocalDateTime { return endOfDate; } + LocalDateTime ofEpochSecond(int epochSecond, ZoneOffset zoneOffset) { + return LocalDateTime.ofEpochSecond(epochSecond, 0, zoneOffset); + } } diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseLocalTime.java b/java-dates/src/main/java/com/baeldung/datetime/UseLocalTime.java index 8d166c413f..876516e365 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/UseLocalTime.java +++ b/java-dates/src/main/java/com/baeldung/datetime/UseLocalTime.java @@ -9,6 +9,10 @@ public class UseLocalTime { return LocalTime.of(hour, min, seconds); } + LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min) { + return LocalTime.of(hour, min); + } + LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) { return LocalTime.parse(timeRepresentation); } diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java b/java-dates/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java new file mode 100644 index 0000000000..ed8499d6e0 --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java @@ -0,0 +1,11 @@ +package com.baeldung.datetime; + +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; + +public class UseOffsetDateTime { + public OffsetDateTime offsetOfLocalDateTimeAndOffset(LocalDateTime localDateTime, ZoneOffset offset) { + return OffsetDateTime.of(localDateTime, offset); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/java-dates/src/main/java/com/baeldung/datetime/UseZonedDateTime.java index 505bfa741f..a8948e5ce1 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/UseZonedDateTime.java +++ b/java-dates/src/main/java/com/baeldung/datetime/UseZonedDateTime.java @@ -12,31 +12,35 @@ class UseZonedDateTime { return ZonedDateTime.of(localDateTime, zoneId); } + ZonedDateTime getZonedDateTimeUsingParseMethod(String parsableString) { + return ZonedDateTime.parse(parsableString); + } + ZonedDateTime getStartOfDay(LocalDate localDate, ZoneId zone) { - ZonedDateTime startofDay = localDate.atStartOfDay() + ZonedDateTime startOfDay = localDate.atStartOfDay() .atZone(zone); - return startofDay; + return startOfDay; } ZonedDateTime getStartOfDayShorthand(LocalDate localDate, ZoneId zone) { - ZonedDateTime startofDay = localDate.atStartOfDay(zone); - return startofDay; + ZonedDateTime startOfDay = localDate.atStartOfDay(zone); + return startOfDay; } ZonedDateTime getStartOfDayFromZonedDateTime(ZonedDateTime zonedDateTime) { - ZonedDateTime startofDay = zonedDateTime.toLocalDateTime() + ZonedDateTime startOfDay = zonedDateTime.toLocalDateTime() .toLocalDate() .atStartOfDay(zonedDateTime.getZone()); - return startofDay; + return startOfDay; } ZonedDateTime getStartOfDayAtMinTime(ZonedDateTime zonedDateTime) { - ZonedDateTime startofDay = zonedDateTime.with(ChronoField.HOUR_OF_DAY, 0); - return startofDay; + ZonedDateTime startOfDay = zonedDateTime.with(ChronoField.HOUR_OF_DAY, 0); + return startOfDay; } ZonedDateTime getStartOfDayAtMidnightTime(ZonedDateTime zonedDateTime) { - ZonedDateTime startofDay = zonedDateTime.with(ChronoField.NANO_OF_DAY, 0); - return startofDay; + ZonedDateTime startOfDay = zonedDateTime.with(ChronoField.NANO_OF_DAY, 0); + return startOfDay; } } diff --git a/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java index a35699e469..226556d4bb 100644 --- a/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java @@ -1,6 +1,6 @@ package com.baeldung.date; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -16,7 +16,7 @@ import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; +import org.junit.Test; public class DateDiffUnitTest { @@ -31,14 +31,14 @@ public class DateDiffUnitTest { assertEquals(diff, 6); } - + @Test public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() { LocalDate now = LocalDate.now(); LocalDate sixDaysBehind = now.minusDays(6); Period period = Period.between(now, sixDaysBehind); - int diff = period.getDays(); + int diff = Math.abs(period.getDays()); assertEquals(diff, 6); } @@ -68,7 +68,8 @@ public class DateDiffUnitTest { public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() { LocalDateTime ldt = LocalDateTime.now(); ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal")); - ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore")).minusDays(6); + ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore")) + .minusDays(6); long diff = ChronoUnit.DAYS.between(sixDaysBehind, now); assertEquals(diff, 6); } diff --git a/java-dates/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java b/java-dates/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java index ff51476e7c..af72f9e58a 100644 --- a/java-dates/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java @@ -1,12 +1,16 @@ package com.baeldung.date.comparison; -import org.junit.Test; - -import java.time.*; - import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; + +import org.junit.Test; + public class Java8DateTimeApiGeneralComparisonsUnitTest { @Test @@ -54,10 +58,8 @@ public class Java8DateTimeApiGeneralComparisonsUnitTest { @Test public void givenZonedDateTimes_whenComparing_thenAssertsPass() { - ZonedDateTime timeInNewYork = ZonedDateTime.of(2019, 8, 10, 8, 0, 0, 0, - ZoneId.of("America/New_York")); - ZonedDateTime timeInBerlin = ZonedDateTime.of(2019, 8, 10, 14, 0, 0, 0, - ZoneId.of("Europe/Berlin")); + ZonedDateTime timeInNewYork = ZonedDateTime.of(2019, 8, 10, 8, 0, 0, 0, ZoneId.of("America/New_York")); + ZonedDateTime timeInBerlin = ZonedDateTime.of(2019, 8, 10, 14, 0, 0, 0, ZoneId.of("Europe/Berlin")); assertThat(timeInNewYork.isAfter(timeInBerlin), is(false)); assertThat(timeInNewYork.isBefore(timeInBerlin), is(false)); @@ -80,4 +82,14 @@ public class Java8DateTimeApiGeneralComparisonsUnitTest { assertThat(firstTime.compareTo(secondTime), is(-1)); } + + @Test + public void givenMinMaxLocalTimes_whenComparing_thenAssertsPass() { + LocalTime minTime = LocalTime.MIN; + LocalTime time = LocalTime.of(8, 30); + LocalTime maxTime = LocalTime.MAX; + + assertThat(minTime.isBefore(time), is(true)); + assertThat(time.isBefore(maxTime), is(true)); + } } \ No newline at end of file diff --git a/java-dates/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java b/java-dates/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java index db6b353ba6..be43fb609a 100644 --- a/java-dates/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java @@ -1,16 +1,39 @@ package com.baeldung.dateapi; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.time.Duration; import java.time.Instant; +import java.time.LocalTime; import java.time.temporal.ChronoUnit; import org.junit.Test; public class JavaDurationUnitTest { + @Test + public void givenATimePlus30Seconds_whenRequestingDuration_thenExpect30() { + LocalTime initialTime = LocalTime.of(6, 30, 0); + LocalTime finalTime = initialTime.plus(Duration.ofSeconds(30)); + + long seconds = Duration.between(initialTime, finalTime) + .getSeconds(); + + assertThat(seconds).isEqualTo(30); + } + + @Test + public void givenATimePlus30Seconds_whenRequestingSecondsBetween_thenExpect30() { + LocalTime initialTime = LocalTime.of(6, 30, 0); + LocalTime finalTime = initialTime.plus(Duration.ofSeconds(30)); + + long seconds = ChronoUnit.SECONDS.between(initialTime, finalTime); + + assertThat(seconds).isEqualTo(30); + } + @Test public void test2() { Instant start = Instant.parse("2017-10-03T10:15:30.00Z"); @@ -29,11 +52,15 @@ public class JavaDurationUnitTest { Duration fromMinutes = Duration.ofMinutes(60); assertEquals(1, fromMinutes.toHours()); - assertEquals(120, duration.plusSeconds(60).getSeconds()); - assertEquals(30, duration.minusSeconds(30).getSeconds()); + assertEquals(120, duration.plusSeconds(60) + .getSeconds()); + assertEquals(30, duration.minusSeconds(30) + .getSeconds()); - assertEquals(120, duration.plus(60, ChronoUnit.SECONDS).getSeconds()); - assertEquals(30, duration.minus(30, ChronoUnit.SECONDS).getSeconds()); + assertEquals(120, duration.plus(60, ChronoUnit.SECONDS) + .getSeconds()); + assertEquals(30, duration.minus(30, ChronoUnit.SECONDS) + .getSeconds()); Duration fromChar1 = Duration.parse("P1DT1H10M10.5S"); Duration fromChar2 = Duration.parse("PT10M"); diff --git a/java-dates/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java b/java-dates/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java index 81e9153a51..6dfbbe8c24 100644 --- a/java-dates/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java @@ -1,18 +1,41 @@ package com.baeldung.dateapi; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.time.LocalDate; +import java.time.Period; +import java.time.temporal.ChronoUnit; + import org.apache.log4j.Logger; import org.junit.Test; -import java.time.LocalDate; -import java.time.Period; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - public class JavaPeriodUnitTest { private static final Logger LOG = Logger.getLogger(JavaPeriodUnitTest.class); + @Test + public void givenADatePlus5Days_whenRequestingPeriod_thenExpectFive() { + LocalDate initialDate = LocalDate.parse("2007-05-10"); + LocalDate finalDate = initialDate.plus(Period.ofDays(5)); + + int days = Period.between(initialDate, finalDate) + .getDays(); + + assertThat(days).isEqualTo(5); + } + + @Test + public void givenADatePlus5Days_whenRequestingDaysBetween_thenExpectFive() { + LocalDate initialDate = LocalDate.parse("2007-05-10"); + LocalDate finalDate = initialDate.plus(Period.ofDays(5)); + + long days = ChronoUnit.DAYS.between(initialDate, finalDate); + + assertThat(days).isEqualTo(5); + } + @Test public void whenTestPeriod_thenOk() { @@ -24,8 +47,10 @@ public class JavaPeriodUnitTest { LOG.info(String.format("Years:%d months:%d days:%d", period.getYears(), period.getMonths(), period.getDays())); assertFalse(period.isNegative()); - assertEquals(56, period.plusDays(50).getDays()); - assertEquals(9, period.minusMonths(2).getMonths()); + assertEquals(56, period.plusDays(50) + .getDays()); + assertEquals(9, period.minusMonths(2) + .getMonths()); Period fromUnits = Period.of(3, 10, 10); Period fromDays = Period.ofDays(50); diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java new file mode 100644 index 0000000000..797e0b954a --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.datetime; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.LocalDateTime; +import java.time.Month; +import java.time.format.FormatStyle; +import java.util.Locale; + +import org.junit.Test; + +public class UseDateTimeFormatterUnitTest { + private final UseDateTimeFormatter subject = new UseDateTimeFormatter(); + private final LocalDateTime localDateTime = LocalDateTime.of(2015, Month.JANUARY, 25, 6, 30); + + @Test + public void givenALocalDate_whenFormattingAsIso_thenPass() { + String result = subject.formatAsIsoDate(localDateTime); + + assertThat(result).isEqualTo("2015-01-25"); + } + + @Test + public void givenALocalDate_whenFormattingWithPattern_thenPass() { + String result = subject.formatCustom(localDateTime, "yyyy/MM/dd"); + + assertThat(result).isEqualTo("2015/01/25"); + } + + @Test + public void givenALocalDate_whenFormattingWithStyleAndLocale_thenPass() { + String result = subject.formatWithStyleAndLocale(localDateTime, FormatStyle.MEDIUM, Locale.UK); + + assertThat(result).isEqualTo("25 Jan 2015, 06:30:00"); + } +} \ No newline at end of file diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java index 5709fc7209..2bbee16e25 100644 --- a/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java @@ -7,12 +7,13 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; +import java.time.ZoneOffset; import org.junit.Test; public class UseLocalDateTimeUnitTest { - UseLocalDateTime useLocalDateTime = new UseLocalDateTime(); + private UseLocalDateTime useLocalDateTime = new UseLocalDateTime(); @Test public void givenString_whenUsingParse_thenLocalDateTime() { @@ -33,4 +34,28 @@ public class UseLocalDateTimeUnitTest { assertThat(endOfDayFromGivenDirectly.toLocalTime()).isEqualTo(LocalTime.MAX); assertThat(endOfDayFromGivenDirectly.toString()).isEqualTo("2018-06-23T23:59:59.999999999"); } + + @Test + public void givenLocalDateTimeInFebruary_whenRequestingMonth_thenMonthIsFebruary() { + LocalDateTime givenLocalDateTime = LocalDateTime.of(2015, Month.FEBRUARY, 20, 6, 30); + + assertThat(givenLocalDateTime.getMonth()).isEqualTo(Month.FEBRUARY); + } + + @Test + public void givenLocalDateTime_whenManipulating_thenResultIsAsExpected() { + LocalDateTime givenLocalDateTime = LocalDateTime.parse("2015-02-20T06:30:00"); + + LocalDateTime manipulatedLocalDateTime = givenLocalDateTime.plusDays(1); + manipulatedLocalDateTime = manipulatedLocalDateTime.minusHours(2); + + assertThat(manipulatedLocalDateTime).isEqualTo(LocalDateTime.of(2015, Month.FEBRUARY, 21, 4, 30)); + } + + @Test + public void whenRequestTimeFromEpoch_thenResultIsAsExpected() { + LocalDateTime result = useLocalDateTime.ofEpochSecond(1465817690, ZoneOffset.UTC); + + assertThat(result.toString()).isEqualTo("2016-06-13T11:34:50"); + } } diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java index bb9b60956d..fd22be9260 100644 --- a/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java @@ -12,7 +12,7 @@ import org.junit.Test; public class UseLocalDateUnitTest { - UseLocalDate useLocalDate = new UseLocalDate(); + private UseLocalDate useLocalDate = new UseLocalDate(); @Test public void givenValues_whenUsingFactoryOf_thenLocalDate() { @@ -88,4 +88,31 @@ public class UseLocalDateUnitTest { assertThat(endOfDayWithMax.toString()).isEqualTo("2018-06-23T23:59:59.999999999"); } + @Test + public void givenTheYear2000_whenCheckingForLeapYear_thenReturnTrue() { + LocalDate given = LocalDate.parse("2000-06-23"); + + boolean leapYear = useLocalDate.isLeapYear(given); + + assertThat(leapYear).isEqualTo(true); + } + + @Test + public void givenTheYear2004_whenCheckingForLeapYear_thenReturnTrue() { + LocalDate given = LocalDate.parse("2004-06-23"); + + boolean leapYear = useLocalDate.isLeapYear(given); + + assertThat(leapYear).isEqualTo(true); + } + + @Test + public void givenTheYear2019_whenCheckingForLeapYear_thenReturnFalse() { + LocalDate given = LocalDate.parse("2019-06-23"); + + boolean leapYear = useLocalDate.isLeapYear(given); + + assertThat(leapYear).isEqualTo(false); + } + } diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java index 996e200ae9..afee9126f9 100644 --- a/java-dates/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java @@ -7,21 +7,30 @@ import org.junit.Test; public class UseLocalTimeUnitTest { - UseLocalTime useLocalTime = new UseLocalTime(); + private UseLocalTime useLocalTime = new UseLocalTime(); @Test public void givenValues_whenUsingFactoryOf_thenLocalTime() { - Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7).toString()); + Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7) + .toString()); + } + + @Test + public void givenValues_whenUsingFactoryOfWithoutSeconds_thenLocalTime() { + Assert.assertEquals("07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7) + .toString()); } @Test public void givenString_whenUsingParse_thenLocalTime() { - Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30").toString()); + Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30") + .toString()); } @Test public void givenTime_whenAddHour_thenLocalTime() { - Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)).toString()); + Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)) + .toString()); } @Test diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java new file mode 100644 index 0000000000..5b58dd3848 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.datetime; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.LocalDateTime; +import java.time.Month; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; + +import org.junit.Test; + +public class UseOffsetDateTimeUnitTest { + private final UseOffsetDateTime subject = new UseOffsetDateTime(); + + @Test + public void givenAZoneOffSetAndLocalDateTime_whenCombing_thenValidResult() { + ZoneOffset offset = ZoneOffset.of("+02:00"); + LocalDateTime localDateTime = LocalDateTime.of(2015, Month.FEBRUARY, 20, 6, 30); + + OffsetDateTime result = subject.offsetOfLocalDateTimeAndOffset(localDateTime, offset); + + assertThat(result.toString()).isEqualTo("2015-02-20T06:30+02:00"); + } +} \ No newline at end of file diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java new file mode 100644 index 0000000000..78d9a647fe --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.datetime; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.LocalDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import org.junit.Test; + +public class UseToInstantUnitTest { + + private UseToInstant subject = new UseToInstant(); + + @Test + public void givenAGregorianCalenderDate_whenConvertingToLocalDate_thenAsExpected() { + GregorianCalendar givenCalender = new GregorianCalendar(2018, Calendar.JULY, 28); + + LocalDateTime localDateTime = subject.convertDateToLocalDate(givenCalender); + + assertThat(localDateTime).isEqualTo("2018-07-28T00:00:00"); + } + + @Test + public void givenADate_whenConvertingToLocalDate_thenAsExpected() { + Date givenDate = new Date(1465817690000L); + + LocalDateTime localDateTime = subject.convertDateToLocalDate(givenDate); + + assertThat(localDateTime).isEqualTo("2016-06-13T13:34:50"); + } +} \ No newline at end of file diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java index f9b4008888..4a39f6056e 100644 --- a/java-dates/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java @@ -7,13 +7,14 @@ import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; +import java.util.Set; import org.junit.Assert; import org.junit.Test; public class UseZonedDateTimeUnitTest { - UseZonedDateTime zonedDateTime = new UseZonedDateTime(); + private UseZonedDateTime zonedDateTime = new UseZonedDateTime(); @Test public void givenZoneId_thenZonedDateTime() { @@ -22,6 +23,13 @@ public class UseZonedDateTimeUnitTest { Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime)); } + @Test + public void whenRequestingZones_thenAtLeastOneIsReturned() { + Set allZoneIds = ZoneId.getAvailableZoneIds(); + + assertThat(allZoneIds.size()).isGreaterThan(1); + } + @Test public void givenLocalDateOrZoned_whenSettingStartOfDay_thenReturnMidnightInAllCases() { LocalDate given = LocalDate.parse("2018-06-23"); @@ -42,4 +50,15 @@ public class UseZonedDateTimeUnitTest { assertThat(startOfOfDayWithMethod.toLocalTime() .toString()).isEqualTo("00:00"); } + + @Test + public void givenAStringWithTimeZone_whenParsing_thenEqualsExpected() { + ZonedDateTime resultFromString = zonedDateTime.getZonedDateTimeUsingParseMethod("2015-05-03T10:15:30+01:00[Europe/Paris]"); + ZonedDateTime resultFromLocalDateTime = ZonedDateTime.of(2015, 5, 3, 11, 15, 30, 0, ZoneId.of("Europe/Paris")); + + assertThat(resultFromString.getZone()).isEqualTo(ZoneId.of("Europe/Paris")); + assertThat(resultFromLocalDateTime.getZone()).isEqualTo(ZoneId.of("Europe/Paris")); + + assertThat(resultFromString).isEqualTo(resultFromLocalDateTime); + } } From 546acf842fc4d542cfe7bf7d6092933acb1704d0 Mon Sep 17 00:00:00 2001 From: Martin van Wingerden Date: Wed, 23 Oct 2019 11:33:00 +0200 Subject: [PATCH 32/38] [BAEL-3289] Add missing code snippets from the Spring Scheduled article All the samples still existed with some slight variation, I updated where applicable Main thing is that the link in the article has to be corrected --- spring-scheduling/README.md | 1 + .../baeldung/scheduling/ScheduledAnnotationExample.java | 8 +++++--- .../src/main/resources/springScheduled-config.xml | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/spring-scheduling/README.md b/spring-scheduling/README.md index 72d5a7dc83..2e3bb2b5e5 100644 --- a/spring-scheduling/README.md +++ b/spring-scheduling/README.md @@ -1,5 +1,6 @@ ### Relevant articles: - [A Guide to the Spring Task Scheduler](http://www.baeldung.com/spring-task-scheduler) +- [The @Scheduled Annotation in Spring](https://www.baeldung.com/spring-scheduled-tasks) - [Guide to Spring Retry](http://www.baeldung.com/spring-retry) - [How To Do @Async in Spring](http://www.baeldung.com/spring-async) diff --git a/spring-scheduling/src/main/java/org/baeldung/scheduling/ScheduledAnnotationExample.java b/spring-scheduling/src/main/java/org/baeldung/scheduling/ScheduledAnnotationExample.java index 284bcf5e6a..23bbee3bc3 100644 --- a/spring-scheduling/src/main/java/org/baeldung/scheduling/ScheduledAnnotationExample.java +++ b/spring-scheduling/src/main/java/org/baeldung/scheduling/ScheduledAnnotationExample.java @@ -31,9 +31,10 @@ public class ScheduledAnnotationExample { System.out.println("Fixed rate task - " + System.currentTimeMillis() / 1000); } - @Scheduled(fixedDelay = 1000, initialDelay = 100) + @Scheduled(fixedDelay = 1000, initialDelay = 1000) public void scheduleFixedRateWithInitialDelayTask() { - System.out.println("Fixed delay task with one second initial delay - " + System.currentTimeMillis() / 1000); + long now = System.currentTimeMillis() / 1000; + System.out.println("Fixed rate task with one second initial delay - " + now); } /** @@ -41,7 +42,8 @@ public class ScheduledAnnotationExample { */ @Scheduled(cron = "0 15 10 15 * ?") public void scheduleTaskUsingCronExpression() { - System.out.println("schedule tasks using cron expressions - " + System.currentTimeMillis() / 1000); + long now = System.currentTimeMillis() / 1000; + System.out.println("schedule tasks using cron jobs - " + now); } @Scheduled(cron = "${cron.expression}") diff --git a/spring-scheduling/src/main/resources/springScheduled-config.xml b/spring-scheduling/src/main/resources/springScheduled-config.xml index d1ff9dc028..4078f535da 100644 --- a/spring-scheduling/src/main/resources/springScheduled-config.xml +++ b/spring-scheduling/src/main/resources/springScheduled-config.xml @@ -15,7 +15,7 @@ - + From a42fc708fb92127504c8eda61f8ec276fa2c5ffd Mon Sep 17 00:00:00 2001 From: Martin van Wingerden Date: Wed, 23 Oct 2019 12:04:31 +0200 Subject: [PATCH 33/38] [BAEL-3292] Add missing code snippets from the Java 8 groupingBy article The Tuple had to be changed because it required an equals/hashcode Also: formatted with eclipse profile --- .../java_8_features/groupingby/Tuple.java | 31 ++++++++----- .../Java8GroupingByCollectorUnitTest.java | 46 ++++++++++++++++--- 2 files changed, 58 insertions(+), 19 deletions(-) diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java index 7a9f62341e..82a84bb2d6 100644 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java +++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java @@ -1,12 +1,12 @@ package com.baeldung.java_8_features.groupingby; -public class Tuple { +import java.util.Objects; + +public class Tuple { + private final BlogPostType type; + private final String author; - private BlogPostType type; - private String author; - public Tuple(BlogPostType type, String author) { - super(); this.type = type; this.author = author; } @@ -15,20 +15,27 @@ public class Tuple { return type; } - public void setType(BlogPostType type) { - this.type = type; - } - public String getAuthor() { return author; } - public void setAuthor(String author) { - this.author = author; + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Tuple tuple = (Tuple) o; + return type == tuple.type && author.equals(tuple.author); + } + + @Override + public int hashCode() { + return Objects.hash(type, author); } @Override public String toString() { - return "Tuple [type=" + type + ", author=" + author + ", getType()=" + getType() + ", getAuthor()=" + getAuthor() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; + return "Tuple{" + "type=" + type + ", author='" + author + '\'' + '}'; } } diff --git a/core-java-modules/core-java-8/src/test/java/com/baeldung/java_8_features/groupingby/Java8GroupingByCollectorUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java_8_features/groupingby/Java8GroupingByCollectorUnitTest.java index 323586b85f..1da705294e 100644 --- a/core-java-modules/core-java-8/src/test/java/com/baeldung/java_8_features/groupingby/Java8GroupingByCollectorUnitTest.java +++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/java_8_features/groupingby/Java8GroupingByCollectorUnitTest.java @@ -1,15 +1,32 @@ package com.baeldung.java_8_features.groupingby; -import com.baeldung.java_8_features.groupingby.BlogPost; -import com.baeldung.java_8_features.groupingby.BlogPostType; -import org.junit.Test; +import static java.util.Comparator.comparingInt; +import static java.util.stream.Collectors.averagingInt; +import static java.util.stream.Collectors.counting; +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.groupingByConcurrent; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.mapping; +import static java.util.stream.Collectors.maxBy; +import static java.util.stream.Collectors.summarizingInt; +import static java.util.stream.Collectors.summingInt; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toSet; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; -import java.util.*; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.IntSummaryStatistics; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import java.util.concurrent.ConcurrentMap; -import static java.util.Comparator.comparingInt; -import static java.util.stream.Collectors.*; -import static org.junit.Assert.*; +import org.junit.Test; public class Java8GroupingByCollectorUnitTest { @@ -180,4 +197,19 @@ public class Java8GroupingByCollectorUnitTest { assertEquals(15, newsLikeStatistics.getMin()); } + @Test + public void givenAListOfPosts_whenGroupedByComplexMapKeyType_thenGetAMapBetweenTupleAndList() { + Map> postsPerTypeAndAuthor = posts.stream() + .collect(groupingBy(post -> new Tuple(post.getType(), post.getAuthor()))); + + List result = postsPerTypeAndAuthor.get(new Tuple(BlogPostType.GUIDE, "Author 1")); + + assertThat(result.size()).isEqualTo(1); + + BlogPost blogPost = result.get(0); + + assertThat(blogPost.getTitle()).isEqualTo("Programming guide"); + assertThat(blogPost.getType()).isEqualTo(BlogPostType.GUIDE); + assertThat(blogPost.getAuthor()).isEqualTo("Author 1"); + } } From f20d2a61947d13e2c7f02816eb03eb168b512ca4 Mon Sep 17 00:00:00 2001 From: Martin van Wingerden Date: Wed, 23 Oct 2019 13:27:02 +0200 Subject: [PATCH 34/38] [BAEL-3295] Add missing code snippets from the Spring Session article --- .../com/baeldung/session/bean/Constants.java | 5 +++ .../java/com/baeldung/session/bean/Foo.java | 29 ++++++++++++ .../security/config/SecSecurityConfig.java | 2 +- .../baeldung/session/web/FooController.java | 44 +++++++++++++++++++ .../session/web/SessionRestController.java | 4 +- .../src/main/resources/application.properties | 2 + .../src/main/resources/webSecurityConfig.xml | 5 +-- .../src/main/webapp/WEB-INF/web.xml | 3 +- 8 files changed, 86 insertions(+), 8 deletions(-) create mode 100644 spring-security-mvc/src/main/java/com/baeldung/session/bean/Constants.java create mode 100644 spring-security-mvc/src/main/java/com/baeldung/session/bean/Foo.java create mode 100644 spring-security-mvc/src/main/java/com/baeldung/session/web/FooController.java diff --git a/spring-security-mvc/src/main/java/com/baeldung/session/bean/Constants.java b/spring-security-mvc/src/main/java/com/baeldung/session/bean/Constants.java new file mode 100644 index 0000000000..bf204c3b99 --- /dev/null +++ b/spring-security-mvc/src/main/java/com/baeldung/session/bean/Constants.java @@ -0,0 +1,5 @@ +package com.baeldung.session.bean; + +public class Constants { + public static final String FOO = "foo"; +} diff --git a/spring-security-mvc/src/main/java/com/baeldung/session/bean/Foo.java b/spring-security-mvc/src/main/java/com/baeldung/session/bean/Foo.java new file mode 100644 index 0000000000..c9c9c011d4 --- /dev/null +++ b/spring-security-mvc/src/main/java/com/baeldung/session/bean/Foo.java @@ -0,0 +1,29 @@ +package com.baeldung.session.bean; + +import static org.springframework.context.annotation.ScopedProxyMode.TARGET_CLASS; +import static org.springframework.web.context.WebApplicationContext.SCOPE_SESSION; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = SCOPE_SESSION, proxyMode = TARGET_CLASS) +public class Foo { + private final String created; + + public Foo() { + this.created = LocalDateTime.now() + .format(DateTimeFormatter.ISO_DATE_TIME); + } + + public Foo(Foo theFoo) { + this.created = theFoo.created; + } + + public String getCreated() { + return created; + } +} diff --git a/spring-security-mvc/src/main/java/com/baeldung/session/security/config/SecSecurityConfig.java b/spring-security-mvc/src/main/java/com/baeldung/session/security/config/SecSecurityConfig.java index 35b53a0e7f..9a4978c27e 100644 --- a/spring-security-mvc/src/main/java/com/baeldung/session/security/config/SecSecurityConfig.java +++ b/spring-security-mvc/src/main/java/com/baeldung/session/security/config/SecSecurityConfig.java @@ -38,7 +38,7 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { .csrf().disable() .authorizeRequests() .antMatchers("/anonymous*").anonymous() - .antMatchers("/login*","/invalidSession*", "/sessionExpired*").permitAll() + .antMatchers("/login*","/invalidSession*", "/sessionExpired*", "/foo/**").permitAll() .anyRequest().authenticated() .and() .formLogin() diff --git a/spring-security-mvc/src/main/java/com/baeldung/session/web/FooController.java b/spring-security-mvc/src/main/java/com/baeldung/session/web/FooController.java new file mode 100644 index 0000000000..7c3385dcbd --- /dev/null +++ b/spring-security-mvc/src/main/java/com/baeldung/session/web/FooController.java @@ -0,0 +1,44 @@ +package com.baeldung.session.web; + +import javax.servlet.http.HttpSession; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import com.baeldung.session.bean.Constants; +import com.baeldung.session.bean.Foo; + +@RestController +@RequestMapping(path = "/foo") +public class FooController { + + @Autowired + private Foo theFoo; + + @GetMapping(path = "set") + public void fooSet(HttpSession session) { + session.setAttribute(Constants.FOO, new Foo()); + } + + @GetMapping(path = "autowired") + public Foo getAutowired() { + return new Foo(theFoo); + } + + @GetMapping(path = "inject") + public Foo fooInject(HttpSession session) { + return (Foo) session.getAttribute(Constants.FOO); + } + + @GetMapping(path = "raw") + public Foo fromRaw() { + ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); + HttpSession session = attr.getRequest() + .getSession(true); + return (Foo) session.getAttribute(Constants.FOO); + } +} diff --git a/spring-security-mvc/src/main/java/com/baeldung/session/web/SessionRestController.java b/spring-security-mvc/src/main/java/com/baeldung/session/web/SessionRestController.java index 82199a9e4e..79f57246a9 100644 --- a/spring-security-mvc/src/main/java/com/baeldung/session/web/SessionRestController.java +++ b/spring-security-mvc/src/main/java/com/baeldung/session/web/SessionRestController.java @@ -3,15 +3,13 @@ package com.baeldung.session.web; import javax.servlet.http.HttpSession; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController public class SessionRestController { @GetMapping("/session-max-interval") - @ResponseBody - public String retrieveMaxSessionIncativeInterval(HttpSession session) { + public String retrieveMaxSessionInactiveInterval(HttpSession session) { return "Max Inactive Interval before Session expires: " + session.getMaxInactiveInterval(); } } diff --git a/spring-security-mvc/src/main/resources/application.properties b/spring-security-mvc/src/main/resources/application.properties index 56b2b7b123..6f0d0519ef 100644 --- a/spring-security-mvc/src/main/resources/application.properties +++ b/spring-security-mvc/src/main/resources/application.properties @@ -1,3 +1,5 @@ +spring.jackson.serialization.fail-on-empty-beans=false + server.servlet.session.timeout=65s spring.mvc.view.prefix=/WEB-INF/view/ diff --git a/spring-security-mvc/src/main/resources/webSecurityConfig.xml b/spring-security-mvc/src/main/resources/webSecurityConfig.xml index 42ff4c2186..e91755d394 100644 --- a/spring-security-mvc/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc/src/main/resources/webSecurityConfig.xml @@ -7,7 +7,7 @@ http://www.springframework.org/schema/beans/spring-beans.xsd" > - + @@ -22,10 +22,9 @@ - - + diff --git a/spring-security-mvc/src/main/webapp/WEB-INF/web.xml b/spring-security-mvc/src/main/webapp/WEB-INF/web.xml index 2ef734441b..88087c92ed 100644 --- a/spring-security-mvc/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-mvc/src/main/webapp/WEB-INF/web.xml @@ -8,13 +8,14 @@ 1 + COOKIE - org.baeldung.web.SessionListenerWithMetrics + com.baeldung.web.SessionListenerWithMetrics spring-data-neo4j @@ -60,7 +61,7 @@ spring-jpa spring-persistence-simple jpa-hibernate-cascade-type - r2dbc + r2dbc spring-boot-jdbi diff --git a/persistence-modules/spring-data-jpa-3/pom.xml b/persistence-modules/spring-data-jpa-3/pom.xml new file mode 100644 index 0000000000..f743fce2a3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/pom.xml @@ -0,0 +1,78 @@ + + + + 4.0.0 + spring-data-jpa-3 + spring-data-jpa-3 + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + ${postgresql.version} + + + + + org.testcontainers + junit-jupiter + ${testcontainers.version} + test + + + org.testcontainers + postgresql + ${testcontainers.version} + test + + + org.springframework.boot + spring-boot-starter-test + test + + + junit + junit + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.platform + junit-platform-launcher + ${junit-platform.version} + test + + + + + 1.12.2 + 42.2.8 + + + diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..c0490d50c6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/Application.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/tx/Payment.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/tx/Payment.java new file mode 100644 index 0000000000..37f3d09381 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/tx/Payment.java @@ -0,0 +1,55 @@ +package com.baeldung.tx; + +import javax.persistence.*; + +@Entity +public class Payment { + + @Id + @GeneratedValue + private Long id; + + private Long amount; + + @Column(unique = true) + private String referenceNumber; + + @Enumerated(EnumType.STRING) + private State state; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getAmount() { + return amount; + } + + public void setAmount(Long amount) { + this.amount = amount; + } + + public String getReferenceNumber() { + return referenceNumber; + } + + public void setReferenceNumber(String referenceNumber) { + this.referenceNumber = referenceNumber; + } + + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } + + public enum State { + STARTED, FAILED, SUCCESSFUL + } +} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java new file mode 100644 index 0000000000..62d64d4372 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java @@ -0,0 +1,171 @@ +package com.baeldung.tx; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.DefaultTransactionDefinition; +import org.springframework.transaction.support.TransactionCallbackWithoutResult; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import javax.persistence.EntityManager; + +import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace.NONE; +import static org.springframework.transaction.annotation.Propagation.NOT_SUPPORTED; + +@DataJpaTest +@Testcontainers +@ActiveProfiles("test") +@AutoConfigureTestDatabase(replace = NONE) +@Transactional(propagation = NOT_SUPPORTED) +class ManualTransactionIntegrationTest { + + @Container + private static PostgreSQLContainer pg = initPostgres(); + + @Autowired + private PlatformTransactionManager transactionManager; + + @Autowired + private EntityManager entityManager; + + private TransactionTemplate transactionTemplate; + + @BeforeEach + void setUp() { + transactionTemplate = new TransactionTemplate(transactionManager); + } + + @AfterEach + void flushDb() { + transactionTemplate.execute(status -> entityManager + .createQuery("delete from Payment") + .executeUpdate()); + } + + @Test + void givenAPayment_WhenNotDuplicate_ThenShouldCommit() { + Long id = transactionTemplate.execute(status -> { + Payment payment = new Payment(); + payment.setAmount(1000L); + payment.setReferenceNumber("Ref-1"); + payment.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(payment); + + return payment.getId(); + }); + + Payment payment = entityManager.find(Payment.class, id); + assertThat(payment).isNotNull(); + } + + @Test + void givenAPayment_WhenMarkAsRollback_ThenShouldRollback() { + transactionTemplate.execute(status -> { + Payment payment = new Payment(); + payment.setAmount(1000L); + payment.setReferenceNumber("Ref-1"); + payment.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(payment); + status.setRollbackOnly(); + + return payment.getId(); + }); + + assertThat(entityManager + .createQuery("select p from Payment p") + .getResultList()).isEmpty(); + } + + @Test + void givenTwoPayments_WhenRefIsDuplicate_ThenShouldRollback() { + try { + transactionTemplate.execute(s -> { + Payment first = new Payment(); + first.setAmount(1000L); + first.setReferenceNumber("Ref-1"); + first.setState(Payment.State.SUCCESSFUL); + + Payment second = new Payment(); + second.setAmount(2000L); + second.setReferenceNumber("Ref-1"); + second.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(first); + entityManager.persist(second); + + return "Ref-1"; + }); + } catch (Exception ignored) { + } + + assertThat(entityManager + .createQuery("select p from Payment p") + .getResultList()).isEmpty(); + } + + @Test + void givenAPayment_WhenNotExpectingAnyResult_ThenShouldCommit() { + transactionTemplate.execute(new TransactionCallbackWithoutResult() { + @Override + protected void doInTransactionWithoutResult(TransactionStatus status) { + Payment payment = new Payment(); + payment.setReferenceNumber("Ref-1"); + payment.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(payment); + } + }); + + assertThat(entityManager + .createQuery("select p from Payment p") + .getResultList()).hasSize(1); + } + + @Test + void givenAPayment_WhenUsingTxManager_ThenShouldCommit() { + DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); + definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + definition.setTimeout(3); + + TransactionStatus status = transactionManager.getTransaction(definition); + try { + Payment payment = new Payment(); + payment.setReferenceNumber("Ref-1"); + payment.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(payment); + transactionManager.commit(status); + } catch (Exception ex) { + transactionManager.rollback(status); + } + + assertThat(entityManager + .createQuery("select p from Payment p") + .getResultList()).hasSize(1); + } + + private static PostgreSQLContainer initPostgres() { + PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:11.1") + .withDatabaseName("baeldung") + .withUsername("test") + .withPassword("test"); + pg.setPortBindings(singletonList("54320:5432")); + + return pg; + } +} diff --git a/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties b/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties new file mode 100644 index 0000000000..aa7093f751 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties @@ -0,0 +1,4 @@ +spring.jpa.hibernate.ddl-auto=update +spring.datasource.url=jdbc:postgresql://localhost:54320/baeldung +spring.datasource.username=test +spring.datasource.password=test