From ca16e787e93e891df3cbb9dd6af642efc72fad11 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sat, 4 Apr 2020 11:42:54 +0530 Subject: [PATCH 01/16] JAVA-991 Week 14 | Do we have any Spring Milestone/RC repos defined? - Removed spring milestone/snapshots repositories from modules --- parent-kotlin/pom.xml | 7 +---- spring-boot-modules/spring-boot-mvc-2/pom.xml | 30 +------------------ 2 files changed, 2 insertions(+), 35 deletions(-) diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index 52a753439c..4a54264510 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -28,11 +28,6 @@ kotlin-eap http://dl.bintray.com/kotlin/kotlin-eap - - spring-milestone - Spring Milestone Repository - https://repo.spring.io/milestone - @@ -217,7 +212,7 @@ 0.9.5 3.12.0 1.3.2 - 2.2.0.M4 + 2.2.6.RELEASE diff --git a/spring-boot-modules/spring-boot-mvc-2/pom.xml b/spring-boot-modules/spring-boot-mvc-2/pom.xml index 3c503eb23d..45202d1e4c 100644 --- a/spring-boot-modules/spring-boot-mvc-2/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-2/pom.xml @@ -87,19 +87,6 @@ - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - jcenter-snapshots jcenter @@ -107,27 +94,12 @@ - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - 3.0.0-SNAPSHOT com.baeldung.swagger2boot.SpringBootSwaggerApplication - 2.2.0.BUILD-SNAPSHOT + 2.2.6.RELEASE 1.4.11.1 From d4e7a4bc9dc1fe6b838a566618e5ca1404f9218a Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sat, 4 Apr 2020 17:39:54 +0530 Subject: [PATCH 02/16] JAVA-991 Week 14 | Do we have any Spring Milestone/RC repos defined? - Reverted removal of snapshot repository from parent-kotlin as some of the artifacts are used by child modules --- parent-kotlin/pom.xml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index 4a54264510..52a753439c 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -28,6 +28,11 @@ kotlin-eap http://dl.bintray.com/kotlin/kotlin-eap + + spring-milestone + Spring Milestone Repository + https://repo.spring.io/milestone + @@ -212,7 +217,7 @@ 0.9.5 3.12.0 1.3.2 - 2.2.6.RELEASE + 2.2.0.M4 From b2ce70b8fb9509ef7e24678e0939b167e067525b Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 15 May 2020 23:06:26 +0800 Subject: [PATCH 03/16] Create README.md --- libraries-concurrency/coroutines-with-quasar/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 libraries-concurrency/coroutines-with-quasar/README.md diff --git a/libraries-concurrency/coroutines-with-quasar/README.md b/libraries-concurrency/coroutines-with-quasar/README.md new file mode 100644 index 0000000000..d1ffe81fa8 --- /dev/null +++ b/libraries-concurrency/coroutines-with-quasar/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Intro to Coroutines with Quasar](https://www.baeldung.com/java-quasar-coroutines) From f139085a1de085cee528b95ee95d2747f5e2f891 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 15 May 2020 23:07:50 +0800 Subject: [PATCH 04/16] Create README.md --- apache-cxf/cxf-aegis/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 apache-cxf/cxf-aegis/README.md diff --git a/apache-cxf/cxf-aegis/README.md b/apache-cxf/cxf-aegis/README.md new file mode 100644 index 0000000000..1cdb6efbb5 --- /dev/null +++ b/apache-cxf/cxf-aegis/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf) From b20271ef347e3458b13a9845c6a14a809ebd53e3 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sat, 16 May 2020 02:57:46 +0800 Subject: [PATCH 05/16] Update README.md --- libraries-concurrency/README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/libraries-concurrency/README.md b/libraries-concurrency/README.md index d1ffe81fa8..8b13789179 100644 --- a/libraries-concurrency/README.md +++ b/libraries-concurrency/README.md @@ -1,3 +1 @@ -### Relevant Articles: -- [Intro to Coroutines with Quasar](https://www.baeldung.com/java-quasar-coroutines) From b660f1cefa61caa3967941fba7fb119466730eec Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sat, 16 May 2020 02:57:55 +0800 Subject: [PATCH 06/16] Delete README.md --- libraries-concurrency/README.md | 1 - 1 file changed, 1 deletion(-) delete mode 100644 libraries-concurrency/README.md diff --git a/libraries-concurrency/README.md b/libraries-concurrency/README.md deleted file mode 100644 index 8b13789179..0000000000 --- a/libraries-concurrency/README.md +++ /dev/null @@ -1 +0,0 @@ - From afeeba6ef5749d571f860d934acb7f6a8d593d77 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sat, 16 May 2020 02:58:46 +0800 Subject: [PATCH 07/16] Update README.md --- apache-cxf/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-cxf/README.md b/apache-cxf/README.md index f825b85bb3..bedd19a91a 100644 --- a/apache-cxf/README.md +++ b/apache-cxf/README.md @@ -3,7 +3,7 @@ This module contains articles about Apache CXF ## Relevant Articles: -- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf) + - [Apache CXF Support for RESTful Web Services](https://www.baeldung.com/apache-cxf-rest-api) - [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring) - [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf) From bccc9c836e87bf20a6662c9c9d206949bed7bd04 Mon Sep 17 00:00:00 2001 From: Dhrubajyoti Bhattacharjee Date: Fri, 15 May 2020 22:17:08 +0200 Subject: [PATCH 08/16] BAEL-3858 Java Exchanger introduction (#9000) --- .../ExchangerPipeLineManualTest.java | 83 +++++++++++++++++++ .../baeldung/exchanger/ExchangerUnitTest.java | 63 ++++++++++++++ 2 files changed, 146 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerPipeLineManualTest.java create mode 100644 core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerUnitTest.java diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerPipeLineManualTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerPipeLineManualTest.java new file mode 100644 index 0000000000..093580654b --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerPipeLineManualTest.java @@ -0,0 +1,83 @@ +package com.baeldung.exchanger; + +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.Exchanger; +import java.util.concurrent.ExecutionException; +import org.junit.Test; + +import static java.util.concurrent.CompletableFuture.runAsync; + + + +public class ExchangerPipeLineManualTest { + + private static final int BUFFER_SIZE = 100; + + @Test + public void givenData_whenPassedThrough_thenCorrect() throws InterruptedException, ExecutionException { + + Exchanger> readerExchanger = new Exchanger<>(); + Exchanger> writerExchanger = new Exchanger<>(); + int counter = 0; + + Runnable reader = () -> { + Queue readerBuffer = new ConcurrentLinkedQueue<>(); + while (true) { + readerBuffer.add(UUID.randomUUID().toString()); + if (readerBuffer.size() >= BUFFER_SIZE) { + try { + readerBuffer = readerExchanger.exchange(readerBuffer); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + } + } + }; + + Runnable processor = () -> { + Queue processorBuffer = new ConcurrentLinkedQueue<>(); + Queue writterBuffer = new ConcurrentLinkedQueue<>(); + try { + processorBuffer = readerExchanger.exchange(processorBuffer); + while (true) { + writterBuffer.add(processorBuffer.poll()); + if (processorBuffer.isEmpty()) { + try { + processorBuffer = readerExchanger.exchange(processorBuffer); + writterBuffer = writerExchanger.exchange(writterBuffer); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + }; + + Runnable writer = () -> { + Queue writterBuffer = new ConcurrentLinkedQueue<>(); + try { + writterBuffer = writerExchanger.exchange(writterBuffer); + while (true) { + System.out.println(writterBuffer.poll()); + if (writterBuffer.isEmpty()) { + writterBuffer = writerExchanger.exchange(writterBuffer); + } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + }; + + CompletableFuture.allOf(runAsync(reader), runAsync(processor), runAsync(writer)).get(); + } + +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerUnitTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerUnitTest.java new file mode 100644 index 0000000000..ec567a3563 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.exchanger; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Exchanger; + +import java.util.concurrent.ExecutionException; +import org.junit.Test; + +import static java.util.concurrent.CompletableFuture.runAsync; + +public class ExchangerUnitTest { + + + @Test + public void givenThreads_whenMessageExchanged_thenCorrect() { + Exchanger exchanger = new Exchanger<>(); + + Runnable taskA = () -> { + try { + String message = exchanger.exchange("from A"); + assertEquals("from B", message); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + }; + + Runnable taskB = () -> { + try { + String message = exchanger.exchange("from B"); + assertEquals("from A", message); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + }; + + CompletableFuture.allOf(runAsync(taskA), runAsync(taskB)).join(); + } + + @Test + public void givenThread_WhenExchangedMessage_thenCorrect() throws InterruptedException, ExecutionException { + Exchanger exchanger = new Exchanger<>(); + + Runnable runner = () -> { + try { + String message = exchanger.exchange("from runner"); + assertEquals("to runner", message); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + }; + + CompletableFuture result = CompletableFuture.runAsync(runner); + String msg = exchanger.exchange("to runner"); + assertEquals("from runner", msg); + result.join(); + } + +} From b707c20297ac4857f314b50efb7d3758aac5e0f7 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Fri, 15 May 2020 22:26:41 +0200 Subject: [PATCH 09/16] BAEL-4042: Add new test case using BufferedReader.lines method (#9288) --- .../JavaInputStreamToXUnitTest.java | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java index eb8c39f2d9..c8c711e328 100644 --- a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java +++ b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java @@ -11,13 +11,26 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.*; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Scanner; import java.util.UUID; +import java.util.stream.Collectors; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.hamcrest.Matchers.equalTo; @@ -46,6 +59,18 @@ public class JavaInputStreamToXUnitTest { assertEquals(textBuilder.toString(), originalString); } + @Test + public void givenUsingJava8_whenConvertingAnInputStreamToAString_thenCorrect() { + final String originalString = randomAlphabetic(DEFAULT_SIZE); + final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes()); + + final String text = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name()))) + .lines() + .collect(Collectors.joining("\n")); + + assertThat(text, equalTo(originalString)); + } + @Test public final void givenUsingJava7_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException { final String originalString = randomAlphabetic(DEFAULT_SIZE); From 708e85ce38e7bfaaea423e5ea3995fb7abf4aacb Mon Sep 17 00:00:00 2001 From: Sampada <46674082+sampada07@users.noreply.github.com> Date: Sat, 16 May 2020 02:07:36 +0530 Subject: [PATCH 10/16] BAEL-3493: Spring REST Docs vs OpenAPI (#9295) --- .../spring-boot-springdoc/pom.xml | 50 +++++- .../baeldung/restdocopenapi/Application.java | 28 ++++ .../java/com/baeldung/restdocopenapi/Foo.java | 93 +++++++++++ .../restdocopenapi/FooController.java | 83 ++++++++++ .../restdocopenapi/FooRepository.java | 9 ++ .../springdoc/FooBarController.java | 121 ++++++++++++++ .../src/main/resources/application.properties | 5 +- .../src/main/resources/asciidocs/fooapi.adoc | 153 ++++++++++++++++++ .../src/main/resources/data.sql | 4 + .../src/main/resources/schema.sql | 8 + .../restdoc/SpringRestDocsUnitTest.java | 120 ++++++++++++++ 11 files changed, 672 insertions(+), 2 deletions(-) create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Application.java create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/resources/asciidocs/fooapi.adoc create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/resources/data.sql create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/resources/schema.sql create mode 100644 spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/restdocopenapi/restdoc/SpringRestDocsUnitTest.java diff --git a/spring-boot-modules/spring-boot-springdoc/pom.xml b/spring-boot-modules/spring-boot-springdoc/pom.xml index 375cf06c2c..1c1f27b5a5 100644 --- a/spring-boot-modules/spring-boot-springdoc/pom.xml +++ b/spring-boot-modules/spring-boot-springdoc/pom.xml @@ -37,7 +37,7 @@ test - + org.hibernate hibernate-core ${hibernate.version} @@ -53,7 +53,19 @@ org.springdoc springdoc-openapi-data-rest ${springdoc.version} + + + + + org.springframework.restdocs + spring-restdocs-mockmvc + test + + org.springframework.restdocs + spring-restdocs-restassured + test + @@ -62,13 +74,49 @@ org.springframework.boot spring-boot-maven-plugin + + org.asciidoctor + asciidoctor-maven-plugin + ${asciidoctor-plugin.version} + + + generate-docs + package + + process-asciidoc + + + html + book + + ${snippetsDirectory} + + src/main/resources/asciidocs + target/generated-docs + + + + + + + true + src/main/resources + + application.properties + data.sql + schema.sql + + + 1.8 5.2.10.Final 1.2.32 + 1.5.6 + ${project.build.directory}/generated-snippets diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Application.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Application.java new file mode 100644 index 0000000000..93a28a2b49 --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Application.java @@ -0,0 +1,28 @@ +package com.baeldung.restdocopenapi; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.info.License; + +@SpringBootApplication() +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Bean + public OpenAPI customOpenAPI(@Value("${springdoc.version}") String appVersion) { + return new OpenAPI().info(new Info().title("Foobar API") + .version(appVersion) + .description("This is a sample Foobar server created using springdocs - a library for OpenAPI 3 with spring boot.") + .termsOfService("http://swagger.io/terms/") + .license(new License().name("Apache 2.0") + .url("http://springdoc.org"))); + } +} diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java new file mode 100644 index 0000000000..99d63581be --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java @@ -0,0 +1,93 @@ +package com.baeldung.restdocopenapi; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Foo { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String title; + + @Column() + private String body; + + + protected Foo() { + } + + public Foo(long id, String title, String body) { + this.id = id; + this.title = title; + this.body = body; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((title == null) ? 0 : title.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Foo other = (Foo) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (title == null) { + if (other.title != null) + return false; + } else if (!title.equals(other.title)) + return false; + return true; + } + + @Override + public String toString() { + return "Foo [id=" + id + ", title=" + title + "]"; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java new file mode 100644 index 0000000000..55c2cccb3c --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java @@ -0,0 +1,83 @@ +package com.baeldung.restdocopenapi; + +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; + +import java.util.List; +import java.util.Optional; + +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/foo") +public class FooController { + + @Autowired + FooRepository repository; + + @GetMapping + public ResponseEntity> getAllFoos() { + List fooList = (List) repository.findAll(); + if (fooList.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + return new ResponseEntity<>(fooList, HttpStatus.OK); + } + + @GetMapping(value = "{id}") + public ResponseEntity getFooById(@PathVariable("id") Long id) { + + Optional foo = repository.findById(id); + return foo.isPresent() ? new ResponseEntity<>(foo.get(), HttpStatus.OK) : new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + @PostMapping + public ResponseEntity addFoo(@RequestBody @Valid Foo foo) { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setLocation(linkTo(FooController.class).slash(foo.getId()) + .toUri()); + Foo savedFoo; + try { + savedFoo = repository.save(foo); + } catch (Exception e) { + return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + } + + return new ResponseEntity<>(savedFoo, httpHeaders, HttpStatus.CREATED); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteFoo(@PathVariable("id") long id) { + try { + repository.deleteById(id); + } catch (Exception e) { + return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + } + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + + @PutMapping("/{id}") + public ResponseEntity updateFoo(@PathVariable("id") long id, @RequestBody Foo foo) { + boolean isFooPresent = repository.existsById(Long.valueOf(id)); + + if (!isFooPresent) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + Foo updatedFoo = repository.save(foo); + + return new ResponseEntity<>(updatedFoo, HttpStatus.OK); + } +} diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java new file mode 100644 index 0000000000..105b57b2ef --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.restdocopenapi; + +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface FooRepository extends PagingAndSortingRepository{ + +} diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java new file mode 100644 index 0000000000..8af414c8fd --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java @@ -0,0 +1,121 @@ +package com.baeldung.restdocopenapi.springdoc; + +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; + +import java.util.List; +import java.util.Optional; + +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.restdocopenapi.Foo; +import com.baeldung.restdocopenapi.FooRepository; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; + +@RestController +@RequestMapping("/foobar") +@Tag(name = "foobar", description = "the foobar API with documentation annotations") +public class FooBarController { + + @Autowired + FooRepository repository; + + @Operation(summary = "Get all foos") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "found foos", content = { + @Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = Foo.class)))}), + @ApiResponse(responseCode = "404", description = "No Foos found", content = @Content) }) + @GetMapping + public ResponseEntity> getAllFoos() { + List fooList = (List) repository.findAll(); + if (fooList.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + return new ResponseEntity<>(fooList, HttpStatus.OK); + } + + @Operation(summary = "Get a foo by foo id") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "found the foo", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Foo.class))}), + @ApiResponse(responseCode = "400", description = "Invalid id supplied", content = @Content), + @ApiResponse(responseCode = "404", description = "Foo not found", content = @Content) }) + @GetMapping(value = "{id}") + public ResponseEntity getFooById(@Parameter(description = "id of foo to be searched") @PathVariable("id") String id) { + + Optional foo = repository.findById(Long.valueOf(id)); + return foo.isPresent() ? new ResponseEntity<>(foo.get(), HttpStatus.OK) : new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + @Operation(summary = "Create a foo") + @ApiResponses(value = { + @ApiResponse(responseCode = "201", description = "foo created", content = { @ + Content(mediaType = "application/json", schema = @Schema(implementation = Foo.class))}), + @ApiResponse(responseCode = "404", description = "Bad request", content = @Content) }) + @PostMapping + public ResponseEntity addFoo(@Parameter(description = "foo object to be created") @RequestBody @Valid Foo foo) { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setLocation(linkTo(FooBarController.class).slash(foo.getId()).toUri()); + Foo savedFoo; + try { + savedFoo = repository.save(foo); + } catch (Exception e) { + return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + } + + return new ResponseEntity<>(savedFoo, httpHeaders, HttpStatus.CREATED); + } + + @Operation(summary = "Delete a foo") + @ApiResponses(value = { + @ApiResponse(responseCode = "204", description = "foo deleted"), + @ApiResponse(responseCode = "404", description = "Bad request", content = @Content) }) + @DeleteMapping("/{id}") + public ResponseEntity deleteFoo(@Parameter(description = "id of foo to be deleted") @PathVariable("id") long id) { + try { + repository.deleteById(id); + } catch (Exception e) { + return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + } + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + + @Operation(summary = "Update a foo") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "foo updated successfully", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Foo.class))}), + @ApiResponse(responseCode = "404", description = "No Foo exists with given id", content = @Content) }) + @PutMapping("/{id}") + public ResponseEntity updateFoo(@Parameter(description = "id of foo to be updated") @PathVariable("id") long id, @RequestBody Foo foo) { + + boolean isFooPresent = repository.existsById(Long.valueOf(id)); + + if (!isFooPresent) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + Foo updatedFoo = repository.save(foo); + + return new ResponseEntity<>(updatedFoo, HttpStatus.OK); + } +} diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties b/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties index 45378e610b..4191d8ba25 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties @@ -5,4 +5,7 @@ springdoc.swagger-ui.path=/swagger-ui-custom.html springdoc.api-docs.path=/api-docs # H2 Related Configurations -spring.datasource.url=jdbc:h2:mem:springdoc \ No newline at end of file +spring.datasource.url=jdbc:h2:mem:springdoc + +springdoc.version=@springdoc.version@ +spring.jpa.hibernate.ddl-auto=none \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/resources/asciidocs/fooapi.adoc b/spring-boot-modules/spring-boot-springdoc/src/main/resources/asciidocs/fooapi.adoc new file mode 100644 index 0000000000..90791cbbcf --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/resources/asciidocs/fooapi.adoc @@ -0,0 +1,153 @@ += RESTful Notes API Guide +Baeldung; +:doctype: book +:icons: font +:source-highlighter: highlightjs +:toc: left +:toclevels: 4 +:sectlinks: + +[[overview]] += Overview + +[[overview-http-verbs]] +== HTTP verbs + +RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its +use of HTTP verbs. + +|=== +| Verb | Usage + +| `GET` +| Used to retrieve a resource + +| `POST` +| Used to create a new resource + +| `PUT` +| Used to update an existing resource + +| `DELETE` +| Used to delete an existing resource +|=== + +RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its +use of HTTP status codes. + +|=== +| Status code | Usage + +| `200 OK` +| The request completed successfully + +| `201 Created` +| A new resource has been created successfully. The resource's URI is available from the response's +`Location` header + +| `204 No Content` +| An update to an existing resource has been applied successfully + +| `400 Bad Request` +| The request was malformed. The response body will include an error providing further information + +| `404 Not Found` +| The requested resource did not exist +|=== + +[[overview-hypermedia]] +== Hypermedia + +RESTful Notes uses hypermedia and resources include links to other resources in their +responses. Responses are in http://stateless.co/hal_specification.html[Hypertext Application +from resource to resource. +Language (HAL)] format. Links can be found beneath the `_links` key. Users of the API should +not create URIs themselves, instead they should use the above-described links to navigate + +[[resources]] += Resources + +[[resources-FOO]] +== FOO REST Service + +The FOO provides the entry point into the service. + +[[resources-foo-get]] +=== Accessing the foo GET + +A `GET` request is used to access the foo read. + +==== Request structure + +include::{snippets}/getAFoo/http-request.adoc[] + +==== Path Parameters +include::{snippets}/getAFoo/path-parameters.adoc[] + +==== Example response + +include::{snippets}/getAFoo/http-response.adoc[] + +==== CURL request + +include::{snippets}/getAFoo/curl-request.adoc[] + +[[resources-foo-post]] +=== Accessing the foo POST + +A `POST` request is used to access the foo create. + +==== Request structure + +include::{snippets}/createFoo/http-request.adoc[] + +==== Example response + +include::{snippets}/createFoo/http-response.adoc[] + +==== CURL request + +include::{snippets}/createFoo/curl-request.adoc[] + +[[resources-foo-delete]] +=== Accessing the foo DELETE + +A `DELETE` request is used to access the foo delete. + +==== Request structure + +include::{snippets}/deleteFoo/http-request.adoc[] + +==== Path Parameters +include::{snippets}/deleteFoo/path-parameters.adoc[] + +==== Example response + +include::{snippets}/deleteFoo/http-response.adoc[] + +==== CURL request + +include::{snippets}/deleteFoo/curl-request.adoc[] + +[[resources-foo-put]] +=== Accessing the foo PUT + +A `PUT` request is used to access the foo update. + +==== Request structure + +include::{snippets}/updateFoo/http-request.adoc[] + +==== Path Parameters +include::{snippets}/updateFoo/path-parameters.adoc[] + +==== Example response + +include::{snippets}/updateFoo/http-response.adoc[] + +==== CURL request + +include::{snippets}/updateFoo/curl-request.adoc[] + + + diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/resources/data.sql b/spring-boot-modules/spring-boot-springdoc/src/main/resources/data.sql new file mode 100644 index 0000000000..f80e53b717 --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/resources/data.sql @@ -0,0 +1,4 @@ +INSERT INTO Foo(id, title, body) VALUES (1, 'Foo 1', 'Foo body 1'); +INSERT INTO Foo(id, title, body) VALUES (2, 'Foo 2', 'Foo body 2'); +INSERT INTO Foo(id, title, body) VALUES (3, 'Foo 3', 'Foo body 3'); + diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/resources/schema.sql b/spring-boot-modules/spring-boot-springdoc/src/main/resources/schema.sql new file mode 100644 index 0000000000..e5d33da019 --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/resources/schema.sql @@ -0,0 +1,8 @@ +DROP TABLE IF EXISTS foo; + +CREATE TABLE foo ( + id INTEGER NOT NULL AUTO_INCREMENT, + title VARCHAR(250) NOT NULL, + body VARCHAR(250), + PRIMARY KEY (id) +); \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/restdocopenapi/restdoc/SpringRestDocsUnitTest.java b/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/restdocopenapi/restdoc/SpringRestDocsUnitTest.java new file mode 100644 index 0000000000..4d37abf78a --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/restdocopenapi/restdoc/SpringRestDocsUnitTest.java @@ -0,0 +1,120 @@ +package com.baeldung.restdocopenapi.restdoc; + +import static org.hamcrest.Matchers.containsString; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; +import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; +import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; +import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; +import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; +import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; +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 static org.springframework.util.StringUtils.collectionToDelimitedString; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.hateoas.MediaTypes; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; +import org.springframework.restdocs.constraints.ConstraintDescriptions; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.restdocopenapi.Application; +import com.baeldung.restdocopenapi.Foo; +import com.fasterxml.jackson.databind.ObjectMapper; + +@ExtendWith({ RestDocumentationExtension.class, SpringExtension.class }) +@SpringBootTest(classes = Application.class) +public class SpringRestDocsUnitTest { + + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @BeforeEach + public void setup(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) { + this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) + .apply(documentationConfiguration(restDocumentation)) + .build(); + } + + @Test + public void whenGetFoo_thenSuccessful() throws Exception { + this.mockMvc.perform(get("/foo")) + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("Foo 1"))) + .andDo(document("getAllFoos")); + } + + @Test + public void whenGetFooById_thenSuccessful() throws Exception { + ConstraintDescriptions desc = new ConstraintDescriptions(Foo.class); + + this.mockMvc.perform(get("/foo/{id}", 1)) + .andExpect(status().isOk()) + .andDo(document("getAFoo", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), + pathParameters(parameterWithName("id").description("id of foo to be searched")), + responseFields(fieldWithPath("id").description("The id of the foo" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")), + fieldWithPath("title").description("The title of the foo"), fieldWithPath("body").description("The body of the foo")))); + } + + @Test + public void whenPostFoo_thenSuccessful() throws Exception { + Map foo = new HashMap<>(); + foo.put("id", 4L); + foo.put("title", "New Foo"); + foo.put("body", "Body of New Foo"); + + this.mockMvc.perform(post("/foo").contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(foo))) + .andExpect(status().isCreated()) + .andDo(document("createFoo", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the foo"), fieldWithPath("title").description("The title of the foo"), + fieldWithPath("body").description("The body of the foo")))); + } + + @Test + public void whenDeleteFoo_thenSuccessful() throws Exception { + this.mockMvc.perform(delete("/foo/{id}", 2)) + .andExpect(status().isNoContent()) + .andDo(document("deleteFoo", pathParameters(parameterWithName("id").description("The id of the foo to delete")))); + } + + @Test + public void whenUpdateFoo_thenSuccessful() throws Exception { + + ConstraintDescriptions desc = new ConstraintDescriptions(Foo.class); + + Map foo = new HashMap<>(); + foo.put("title", "Updated Foo"); + foo.put("body", "Body of Updated Foo"); + + this.mockMvc.perform(put("/foo/{id}", 3).contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(foo))) + .andExpect(status().isOk()) + .andDo(document("updateFoo", pathParameters(parameterWithName("id").description("The id of the foo to update")), + responseFields(fieldWithPath("id").description("The id of the updated foo" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")), + fieldWithPath("title").description("The title of the updated foo"), fieldWithPath("body").description("The body of the updated foo")))); + } + + +} From e264ffd4bc99e7bba12b692a5e27d2749fc17ffa Mon Sep 17 00:00:00 2001 From: Anirban Date: Sat, 16 May 2020 09:43:14 +0200 Subject: [PATCH 11/16] Added if-else expression examples in kotlin (#9296) --- .../IfElseExpressionExample.kt | 86 +++++++++++++++++++ .../IfElseExpressionExampleTest.kt | 43 ++++++++++ 2 files changed, 129 insertions(+) create mode 100644 core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExample.kt create mode 100644 core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExampleTest.kt diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExample.kt b/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExample.kt new file mode 100644 index 0000000000..f4e42a4f4f --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExample.kt @@ -0,0 +1,86 @@ +package com.baeldung.ifelseexpression + +fun ifStatementUsage(): String { + val number = 15 + + if (number > 0) { + return "Positive number" + } + return "Positive number not found" +} + +fun ifElseStatementUsage(): String { + val number = -50 + + if (number > 0) { + return "Positive number" + } else { + return "Negative number" + } +} + +fun ifElseExpressionUsage(): String { + val number = -50 + + val result = if (number > 0) { + "Positive number" + } else { + "Negative number" + } + return result +} + +fun ifElseExpressionSingleLineUsage(): String { + val number = -50 + val result = if (number > 0) "Positive number" else "Negative number" + + return result +} + +fun ifElseMultipleExpressionUsage(): Int { + val x = 24 + val y = 73 + + val result = if (x > y) { + println("$x is greater than $y") + x + } else { + println("$x is less than or equal to $y") + y + } + return result +} + +fun ifElseLadderExpressionUsage(): String { + val number = 60 + + val result = if (number < 0) { + "Negative number" + } else if (number in 0..9) { + "Single digit number" + } else if (number in 10..99) { + "Double digit number" + } else { + "Number has more digits" + } + return result +} + +fun ifElseNestedExpressionUsage(): Int { + val x = 37 + val y = 89 + val z = 6 + + val result = if (x > y) { + if (x > z) + x + else + z + } else { + if (y > z) + y + else + z + } + return result +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExampleTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExampleTest.kt new file mode 100644 index 0000000000..266e41e07b --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExampleTest.kt @@ -0,0 +1,43 @@ +package com.baeldung.ifelseexpression + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotEquals + +class IfElseExpressionExampleTest { + + @Test + fun givenNumber_whenIfStatementCalled_thenReturnsString() { + assertEquals("Positive number", ifStatementUsage()) + } + + @Test + fun givenNumber_whenIfElseStatementCalled_thenReturnsString() { + assertEquals("Negative number", ifElseStatementUsage()) + } + + @Test + fun givenNumber_whenIfElseExpressionCalled_thenReturnsString() { + assertEquals("Negative number", ifElseExpressionUsage()) + } + + @Test + fun givenNumber_whenIfElseExpressionSingleLineCalled_thenReturnsString() { + assertEquals("Negative number", ifElseExpressionSingleLineUsage()) + } + + @Test + fun givenNumber_whenIfElseMultipleExpressionCalled_thenReturnsNumber() { + assertEquals(73, ifElseMultipleExpressionUsage()) + } + + @Test + fun givenNumber_whenIfElseLadderExpressionCalled_thenReturnsString() { + assertEquals("Double digit number", ifElseLadderExpressionUsage()) + } + + @Test + fun givenNumber_whenIfElseNestedExpressionCalled_thenReturnsNumber() { + assertEquals(89, ifElseNestedExpressionUsage()) + } +} \ No newline at end of file From c72b2846d5e8b65868a1196f2cc11fb520d791d2 Mon Sep 17 00:00:00 2001 From: sasam0320 <63002713+sasam0320@users.noreply.github.com> Date: Sat, 16 May 2020 10:03:47 +0200 Subject: [PATCH 12/16] BAEL 3234 - Add missing code snippets (#9285) --- .../ConfigPropertiesDemoApplication.java | 2 +- .../com/baeldung/properties/Database.java | 33 ------------------- .../main/resources/configForProperties.xml | 4 --- .../src/main/resources/database.properties | 1 - .../src/main/resources/database.yml | 3 +- .../ConfigPropertiesIntegrationTest.java | 14 ++------ .../DatabasePropertiesIntegrationTest.java | 10 +++--- .../src/test/resources/application.properties | 3 -- 8 files changed, 11 insertions(+), 59 deletions(-) delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java index e54f28837d..e280bbd79f 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -7,7 +7,7 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.configurationproperties.ConfigProperties; @SpringBootApplication -@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class, Database.class }) +@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class}) public class ConfigPropertiesDemoApplication { public static void main(String[] args) { new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer()) diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java deleted file mode 100644 index 6e798672e7..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.properties; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ConfigurationProperties(prefix = "database") -public class Database { - - private String url; - private String username; - private String password; - - public String getUrl() { - return url; - } - public void setUrl(String url) { - this.url = url; - } - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - -} diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml b/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml index bf4452da4a..16db00ace3 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml @@ -14,8 +14,4 @@ - - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties index eb5703ca72..24bfdf2096 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties @@ -1,4 +1,3 @@ - jdbc.url=jdbc:postgresql:/localhost:5432 database.username=foo database.password=bar diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/database.yml b/spring-boot-modules/spring-boot-properties/src/main/resources/database.yml index 8404d9411a..83432f65bc 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/database.yml +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/database.yml @@ -1,5 +1,6 @@ database: - url: jdbc:postresql:/localhost:5432/instance + jdbc: + url: jdbc:postresql:/localhost:5432 username: foo password: bar secret: foo \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java index 2b0833c387..3b80fa66fe 100644 --- a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java @@ -14,17 +14,13 @@ import com.baeldung.properties.AdditionalProperties; import com.baeldung.properties.ConfigPropertiesDemoApplication; @RunWith(SpringRunner.class) -@SpringBootTest(classes = {ConfigPropertiesDemoApplication.class, DatabaseConfigPropertiesApp.class}) -@TestPropertySource(locations = {"classpath:configprops-test.properties", "classpath:database-test.properties"}) +@SpringBootTest(classes = {ConfigPropertiesDemoApplication.class}) +@TestPropertySource(locations = {"classpath:configprops-test.properties"}) public class ConfigPropertiesIntegrationTest { @Autowired private ConfigProperties properties; - @Autowired - @Qualifier("dataSource") - private Database databaseProperties; - @Autowired private AdditionalProperties additionalProperties; @@ -59,10 +55,4 @@ public class ConfigPropertiesIntegrationTest { Assert.assertTrue(additionalProperties.getMax() == 100); } - @Test - public void whenDatabasePropertyQueriedthenReturnsProperty() { - Assert.assertTrue(databaseProperties.getUrl().equals("jdbc:postgresql:/localhost:5432")); - Assert.assertTrue(databaseProperties.getUsername().equals("foo")); - Assert.assertTrue(databaseProperties.getPassword().equals("bar")); - } } diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java index 0b9bd797ae..50a129916f 100644 --- a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java @@ -4,26 +4,28 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.properties.ConfigPropertiesDemoApplication; -import com.baeldung.properties.Database; +import com.baeldung.configurationproperties.Database; @RunWith(SpringRunner.class) -@SpringBootTest(classes = ConfigPropertiesDemoApplication.class) -@TestPropertySource("classpath:application.properties") +@SpringBootTest(classes = DatabaseConfigPropertiesApp.class) +@TestPropertySource("classpath:database-test.properties") public class DatabasePropertiesIntegrationTest { @Autowired + @Qualifier("dataSource") private Database database; @Test public void testDatabaseProperties() { Assert.assertNotNull(database); - Assert.assertEquals("jdbc:postgresql:/localhost:5432/instance", database.getUrl()); + Assert.assertEquals("jdbc:postgresql:/localhost:5432", database.getUrl()); Assert.assertEquals("foo", database.getUsername()); Assert.assertEquals("bar", database.getPassword()); } diff --git a/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties b/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties index d4d1df7abc..af38556f81 100644 --- a/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties +++ b/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties @@ -3,6 +3,3 @@ spring.properties.refreshDelay=1000 spring.config.location=file:extra.properties spring.main.allow-bean-definition-overriding=true -database.url=jdbc:postgresql:/localhost:5432/instance -database.username=foo -database.password=bar \ No newline at end of file From ab9d1cd461e80a3a263096f3263d122f960b8e93 Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sat, 16 May 2020 15:24:23 +0530 Subject: [PATCH 13/16] updated java comment --- .../CollectionToArrayListUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java index 15960c300d..b8134de08a 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java @@ -88,7 +88,7 @@ public class CollectionToArrayListUnitTest { Iterator iterA = a.iterator(); Iterator iterB = b.iterator(); while (iterA.hasNext()) { - // use '==' to test instance identity + // test instance identity assertSame("Foo instances differ!", iterA.next(), iterB.next()); } } From 29dde3b4855c49ddba924a035099d752fa10c46a Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sat, 16 May 2020 17:06:29 +0530 Subject: [PATCH 14/16] updated spring kafka version --- spring-kafka/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index d60a2ee506..2b4a0914e6 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -33,7 +33,7 @@ - 2.2.7.RELEASE + 2.3.7.RELEASE \ No newline at end of file From 44a1ec0195c5e92200f60fea26f1eb39ec73f716 Mon Sep 17 00:00:00 2001 From: ajay74984 <51405689+ajay74984@users.noreply.github.com> Date: Sun, 17 May 2020 05:27:15 +0200 Subject: [PATCH 15/16] OCP change (#9266) * OCP change * calculator unit test --- .../main/java/com/baeldung/o/Addition.java | 41 +++++++++++++++++ .../main/java/com/baeldung/o/Calculator.java | 14 ++++++ .../com/baeldung/o/CalculatorOperation.java | 7 +++ .../main/java/com/baeldung/o/Division.java | 43 ++++++++++++++++++ .../main/java/com/baeldung/o/Subtraction.java | 41 +++++++++++++++++ .../com/baeldung/o/CalculatorUnitTest.java | 44 +++++++++++++++++++ 6 files changed, 190 insertions(+) create mode 100644 patterns/solid/src/main/java/com/baeldung/o/Addition.java create mode 100644 patterns/solid/src/main/java/com/baeldung/o/Calculator.java create mode 100644 patterns/solid/src/main/java/com/baeldung/o/CalculatorOperation.java create mode 100644 patterns/solid/src/main/java/com/baeldung/o/Division.java create mode 100644 patterns/solid/src/main/java/com/baeldung/o/Subtraction.java create mode 100644 patterns/solid/src/main/test/com/baeldung/o/CalculatorUnitTest.java diff --git a/patterns/solid/src/main/java/com/baeldung/o/Addition.java b/patterns/solid/src/main/java/com/baeldung/o/Addition.java new file mode 100644 index 0000000000..6145b386d9 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/o/Addition.java @@ -0,0 +1,41 @@ +package com.baeldung.o; + +public class Addition implements CalculatorOperation { + private double number1; + private double number2; + private double result = 0.0; + + public Addition(double number1, double number2) { + this.number1 = number1; + this.number2 = number2; + } + + public double getNumber1() { + return number1; + } + + public void setNumber1(double number1) { + this.number1 = number1; + } + + public double getNumber2() { + return number2; + } + + public void setNumber2(double number2) { + this.number2 = number2; + } + + public double getResult() { + return result; + } + + public void setResult(double result) { + this.result = result; + } + + @Override + public void perform() { + result = number1 + number2; + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/o/Calculator.java b/patterns/solid/src/main/java/com/baeldung/o/Calculator.java new file mode 100644 index 0000000000..11ace8eb20 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/o/Calculator.java @@ -0,0 +1,14 @@ +package com.baeldung.o; + +import java.security.InvalidParameterException; + +public class Calculator { + + public void calculate(CalculatorOperation operation) { + if (operation == null) { + throw new InvalidParameterException("Can not perform operation"); + } + + operation.perform(); + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/o/CalculatorOperation.java b/patterns/solid/src/main/java/com/baeldung/o/CalculatorOperation.java new file mode 100644 index 0000000000..46648e25d8 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/o/CalculatorOperation.java @@ -0,0 +1,7 @@ +package com.baeldung.o; + +public interface CalculatorOperation { + + void perform(); + +} diff --git a/patterns/solid/src/main/java/com/baeldung/o/Division.java b/patterns/solid/src/main/java/com/baeldung/o/Division.java new file mode 100644 index 0000000000..24ab4355c2 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/o/Division.java @@ -0,0 +1,43 @@ +package com.baeldung.o; + +public class Division implements CalculatorOperation { + private double number1; + private double number2; + private double result = 0.0; + + public Division(double number1, double number2) { + this.number1 = number1; + this.number2 = number2; + } + + public double getNumber1() { + return number1; + } + + public void setNumber1(double number1) { + this.number1 = number1; + } + + public double getNumber2() { + return number2; + } + + public void setNumber2(double number2) { + this.number2 = number2; + } + + public double getResult() { + return result; + } + + public void setResult(double result) { + this.result = result; + } + + @Override + public void perform() { + if (number2 != 0) { + result = number1 / number2; + } + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/o/Subtraction.java b/patterns/solid/src/main/java/com/baeldung/o/Subtraction.java new file mode 100644 index 0000000000..b74e0c5f73 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/o/Subtraction.java @@ -0,0 +1,41 @@ +package com.baeldung.o; + +public class Subtraction implements CalculatorOperation { + private double number1; + private double number2; + private double result = 0.0; + + public Subtraction(double number1, double number2) { + this.number1 = number1; + this.number2 = number2; + } + + public double getNumber1() { + return number1; + } + + public void setNumber1(double number1) { + this.number1 = number1; + } + + public double getNumber2() { + return number2; + } + + public void setNumber2(double number2) { + this.number2 = number2; + } + + public double getResult() { + return result; + } + + public void setResult(double result) { + this.result = result; + } + + @Override + public void perform() { + result = number1 - number2; + } +} diff --git a/patterns/solid/src/main/test/com/baeldung/o/CalculatorUnitTest.java b/patterns/solid/src/main/test/com/baeldung/o/CalculatorUnitTest.java new file mode 100644 index 0000000000..f372d450a7 --- /dev/null +++ b/patterns/solid/src/main/test/com/baeldung/o/CalculatorUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.o; + +import static org.junit.Assert.assertEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class CalculatorUnitTest { + + private static final double NUMBER_1 = 10.0; + private static final double NUMBER_2 = 20.0; + private static final double SUM = 30.0; + private static final double SUBTRACTION_RESULT = 10.0; + private static final double DIVISION_RESULT = 2.0; + + private Calculator calculator; + + @BeforeEach + public void setUp() { + calculator = new Calculator(); + } + + @Test + public void whenAddTwoNumber_returnSum() { + Addition addition = new Addition(NUMBER_1, NUMBER_2); + calculator.calculate(addition); + assertEquals(SUM, addition.getResult(), 0.0); + } + + @Test + public void whenSutractTwoNumber_returnCorrectResult() { + Subtraction subtraction = new Subtraction(NUMBER_2, NUMBER_1); + calculator.calculate(subtraction); + assertEquals(SUBTRACTION_RESULT, subtraction.getResult(), 0.0); + } + + @Test + public void whenDivideTwoNumber_returnCorrectResult() { + Division division = new Division(NUMBER_2, NUMBER_1); + calculator.calculate(division); + assertEquals(DIVISION_RESULT, division.getResult(), 0.0); + } + +} From 832b32210c2843ac0c1168005c5e5e07dcfbe461 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Sun, 17 May 2020 12:59:16 +0200 Subject: [PATCH 16/16] BAEL-3745: Implement PropertySourceFactory to load YAML files (new module) (#9307) --- .../spring-boot-properties-2/README.md | 5 +++ .../spring-boot-properties-2/pom.xml | 25 +++++++++++ .../properties/yaml/YamlApplication.java | 22 ++++++++++ .../properties/yaml/YamlFooProperties.java | 42 +++++++++++++++++++ .../factory/YamlPropertySourceFactory.java | 24 +++++++++++ .../src/main/resources/foo.yml | 5 +++ .../YamlFooPropertiesIntegrationTest.java | 23 ++++++++++ 7 files changed, 146 insertions(+) create mode 100644 spring-boot-modules/spring-boot-properties-2/README.md create mode 100644 spring-boot-modules/spring-boot-properties-2/pom.xml create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlApplication.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlFooProperties.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/factory/YamlPropertySourceFactory.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/resources/foo.yml create mode 100644 spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/yaml/YamlFooPropertiesIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-properties-2/README.md b/spring-boot-modules/spring-boot-properties-2/README.md new file mode 100644 index 0000000000..01e2970e89 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/README.md @@ -0,0 +1,5 @@ +## Spring Boot Properties + +This module contains articles about Properties in Spring Boot. + +### Relevant Articles: diff --git a/spring-boot-modules/spring-boot-properties-2/pom.xml b/spring-boot-modules/spring-boot-properties-2/pom.xml new file mode 100644 index 0000000000..c3c3e57251 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + spring-boot-properties-2 + spring-boot-properties-2 + jar + Spring Boot Properties Module + 0.0.1-SNAPSHOT + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter + + + + diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlApplication.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlApplication.java new file mode 100644 index 0000000000..f1244925f1 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlApplication.java @@ -0,0 +1,22 @@ +package com.baeldung.properties.yaml; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class YamlApplication implements CommandLineRunner { + + @Autowired + private YamlFooProperties yamlFooProperties; + + public static void main(String[] args) { + SpringApplication.run(YamlApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + System.out.println("YAML Properties " + yamlFooProperties); + } +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlFooProperties.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlFooProperties.java new file mode 100644 index 0000000000..264fc865ad --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlFooProperties.java @@ -0,0 +1,42 @@ +package com.baeldung.properties.yaml; + +import com.baeldung.properties.yaml.factory.YamlPropertySourceFactory; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; + +import java.util.List; + +@Configuration +@ConfigurationProperties(prefix = "yaml") +@PropertySource(value = "classpath:foo.yml", factory = YamlPropertySourceFactory.class) +public class YamlFooProperties { + + private String name; + + private List aliases; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getAliases() { + return aliases; + } + + public void setAliases(List aliases) { + this.aliases = aliases; + } + + @Override + public String toString() { + return "YamlFooProperties{" + + "name='" + name + '\'' + + ", aliases=" + aliases + + '}'; + } +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/factory/YamlPropertySourceFactory.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/factory/YamlPropertySourceFactory.java new file mode 100644 index 0000000000..50201f9377 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/factory/YamlPropertySourceFactory.java @@ -0,0 +1,24 @@ +package com.baeldung.properties.yaml.factory; + +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; +import org.springframework.core.env.PropertiesPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.support.EncodedResource; +import org.springframework.core.io.support.PropertySourceFactory; + +import java.io.IOException; +import java.util.Properties; + +public class YamlPropertySourceFactory implements PropertySourceFactory { + + @Override + public PropertySource createPropertySource(String name, EncodedResource encodedResource) throws IOException { + YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); + factory.setResources(encodedResource.getResource()); + + Properties properties = factory.getObject(); + + return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties); + } + +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/resources/foo.yml b/spring-boot-modules/spring-boot-properties-2/src/main/resources/foo.yml new file mode 100644 index 0000000000..6320510a94 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/resources/foo.yml @@ -0,0 +1,5 @@ +yaml: + name: foo + aliases: + - abc + - xyz \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/yaml/YamlFooPropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/yaml/YamlFooPropertiesIntegrationTest.java new file mode 100644 index 0000000000..dfe1c830b4 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/yaml/YamlFooPropertiesIntegrationTest.java @@ -0,0 +1,23 @@ +package com.baeldung.properties.yaml; + +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 static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class YamlFooPropertiesIntegrationTest { + + @Autowired + private YamlFooProperties yamlFooProperties; + + @Test + public void whenFactoryProvidedThenYamlPropertiesInjected() { + assertThat(yamlFooProperties.getName()).isEqualTo("foo"); + assertThat(yamlFooProperties.getAliases()).containsExactly("abc", "xyz"); + } +} \ No newline at end of file