From b7d4a00dacdcddc877e1726832c4aeec378b6ed8 Mon Sep 17 00:00:00 2001 From: RanjeetKaur17 Date: Tue, 3 Jul 2018 22:55:47 +0400 Subject: [PATCH 01/41] A simple Real Time streaming example with Spring Webflux. 1. Added an API to generate a real time stream returning numbers. 2. Added Test case to consume that API with a webTestClient. 3. Added a client to consume that API, over the network. --- .../pom.xml | 70 +++++++++++++++++ .../java/com/springwebflux/sample/Client.java | 29 +++++++ .../src/main/resources/application.properties | 1 + springflux-5-reactive-ranjeetkaur/pom.xml | 76 +++++++++++++++++++ .../springwebflux/controller/Controller.java | 28 +++++++ .../com/springwebflux/sample/Application.java | 17 +++++ .../src/main/resources/application.properties | 1 + .../sample/ApplicationTests.java | 36 +++++++++ 8 files changed, 258 insertions(+) create mode 100644 springflux-5-reactive-client-ranjeetkaur/pom.xml create mode 100644 springflux-5-reactive-client-ranjeetkaur/src/main/java/com/springwebflux/sample/Client.java create mode 100644 springflux-5-reactive-client-ranjeetkaur/src/main/resources/application.properties create mode 100644 springflux-5-reactive-ranjeetkaur/pom.xml create mode 100644 springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/controller/Controller.java create mode 100644 springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/sample/Application.java create mode 100644 springflux-5-reactive-ranjeetkaur/src/main/resources/application.properties create mode 100644 springflux-5-reactive-ranjeetkaur/src/test/java/com/springwebflux/sample/ApplicationTests.java diff --git a/springflux-5-reactive-client-ranjeetkaur/pom.xml b/springflux-5-reactive-client-ranjeetkaur/pom.xml new file mode 100644 index 0000000000..bb832ae055 --- /dev/null +++ b/springflux-5-reactive-client-ranjeetkaur/pom.xml @@ -0,0 +1,70 @@ + + + 4.0.0 + + com.springboot + sample + 0.0.1-SNAPSHOT + jar + + client + SpringFlux Sample Client + + + org.springframework.boot + spring-boot-starter-parent + 2.0.3.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + --spring.profiles.active=dev + + + + + + + + + spring-releases + https://repo.spring.io/libs-release + + + + + spring-releases + https://repo.spring.io/libs-release + + + + diff --git a/springflux-5-reactive-client-ranjeetkaur/src/main/java/com/springwebflux/sample/Client.java b/springflux-5-reactive-client-ranjeetkaur/src/main/java/com/springwebflux/sample/Client.java new file mode 100644 index 0000000000..5846969803 --- /dev/null +++ b/springflux-5-reactive-client-ranjeetkaur/src/main/java/com/springwebflux/sample/Client.java @@ -0,0 +1,29 @@ +package com.springwebflux.sample; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.web.reactive.function.client.WebClient; + +/** + * @author ranjeetkaur + * + */ +@SpringBootApplication(scanBasePackages = "com.springwebflux.*") +@EnableAsync +public class Client { + + public static void main(String[] args) throws InterruptedException { + + WebClient webClient = WebClient.builder() + .baseUrl("http://localhost:8090") + .build(); + + webClient.get() + .uri("/v1/dice") + .retrieve() + .bodyToFlux(Integer.class) + .log(); + + Thread.sleep(10000); + } +} \ No newline at end of file diff --git a/springflux-5-reactive-client-ranjeetkaur/src/main/resources/application.properties b/springflux-5-reactive-client-ranjeetkaur/src/main/resources/application.properties new file mode 100644 index 0000000000..f667a68bc2 --- /dev/null +++ b/springflux-5-reactive-client-ranjeetkaur/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port =8091 \ No newline at end of file diff --git a/springflux-5-reactive-ranjeetkaur/pom.xml b/springflux-5-reactive-ranjeetkaur/pom.xml new file mode 100644 index 0000000000..3fe4156360 --- /dev/null +++ b/springflux-5-reactive-ranjeetkaur/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + + com.springboot + sample + 0.0.1-SNAPSHOT + jar + + webflux-server + SpringFlux Sample Server + + + org.springframework.boot + spring-boot-starter-parent + 2.0.3.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + --spring.profiles.active=dev + + + + + + + + + spring-releases + https://repo.spring.io/libs-release + + + + + spring-releases + https://repo.spring.io/libs-release + + + + diff --git a/springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/controller/Controller.java b/springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/controller/Controller.java new file mode 100644 index 0000000000..fa3070640e --- /dev/null +++ b/springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/controller/Controller.java @@ -0,0 +1,28 @@ +package com.springwebflux.controller; + +import java.time.Duration; +import java.util.Random; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Flux; + +/** + * @author ranjeetkaur + * + */ +@RestController +@RequestMapping(value = "/v1") +public class Controller { + + private static Random random = new Random(); + + @GetMapping("/dice") + public Flux rollDice() { + return Flux.interval(Duration.ofSeconds(1)) + .map(pulse -> random.nextInt(5) + 1); + } + +} diff --git a/springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/sample/Application.java b/springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/sample/Application.java new file mode 100644 index 0000000000..1641885f41 --- /dev/null +++ b/springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/sample/Application.java @@ -0,0 +1,17 @@ +package com.springwebflux.sample; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * @author ranjeetkaur + * + */ +@SpringBootApplication(scanBasePackages = "com.springwebflux.*") +public class Application { + + public static void main(String[] args) { + + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/springflux-5-reactive-ranjeetkaur/src/main/resources/application.properties b/springflux-5-reactive-ranjeetkaur/src/main/resources/application.properties new file mode 100644 index 0000000000..91f7491179 --- /dev/null +++ b/springflux-5-reactive-ranjeetkaur/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port = 8090 \ No newline at end of file diff --git a/springflux-5-reactive-ranjeetkaur/src/test/java/com/springwebflux/sample/ApplicationTests.java b/springflux-5-reactive-ranjeetkaur/src/test/java/com/springwebflux/sample/ApplicationTests.java new file mode 100644 index 0000000000..ce09d9ae37 --- /dev/null +++ b/springflux-5-reactive-ranjeetkaur/src/test/java/com/springwebflux/sample/ApplicationTests.java @@ -0,0 +1,36 @@ +package com.springwebflux.sample; + +import java.time.Duration; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ApplicationTests { + + @Autowired + private WebTestClient webTestClient; + + @Before + private void setUp() { + webTestClient = webTestClient.mutate() + .responseTimeout(Duration.ofMillis(10000)) + .build(); + } + + @Test + public void rollDice() throws InterruptedException { + webTestClient.get() + .uri("/v1/dice") + .exchange() + .expectStatus() + .isOk() + .expectBodyList(Integer.class); + } +} \ No newline at end of file From 8eb1b1bb9fd0dcba5e89de2a43e5f0e7504b04c0 Mon Sep 17 00:00:00 2001 From: RanjeetKaur17 Date: Mon, 30 Jul 2018 23:48:50 +0400 Subject: [PATCH 02/41] Examples for Reading a file into an arraylist. 1. Using FileReader 2. Using BufferedReader 3. Using Scanner(String and int) 4. Using Files.readAllLines --- .../fileparser/BufferedReaderExample.java | 34 +++++++++++++++++ .../fileparser/FileReaderExample.java | 37 +++++++++++++++++++ .../fileparser/FilesReadLineExample.java | 28 ++++++++++++++ .../fileparser/ScannerIntExample.java | 34 +++++++++++++++++ .../fileparser/ScannerStringExample.java | 34 +++++++++++++++++ file-parser/src/resources/num.txt | 2 + file-parser/src/resources/txt.txt | 2 + 7 files changed, 171 insertions(+) create mode 100644 file-parser/src/com/baeldung/fileparser/BufferedReaderExample.java create mode 100644 file-parser/src/com/baeldung/fileparser/FileReaderExample.java create mode 100644 file-parser/src/com/baeldung/fileparser/FilesReadLineExample.java create mode 100644 file-parser/src/com/baeldung/fileparser/ScannerIntExample.java create mode 100644 file-parser/src/com/baeldung/fileparser/ScannerStringExample.java create mode 100644 file-parser/src/resources/num.txt create mode 100644 file-parser/src/resources/txt.txt diff --git a/file-parser/src/com/baeldung/fileparser/BufferedReaderExample.java b/file-parser/src/com/baeldung/fileparser/BufferedReaderExample.java new file mode 100644 index 0000000000..a139ed80ab --- /dev/null +++ b/file-parser/src/com/baeldung/fileparser/BufferedReaderExample.java @@ -0,0 +1,34 @@ +package com.baeldung.fileparser; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; + +public class BufferedReaderExample { + + private static final String FILENAME = "src/resources/txt.txt"; + + public static void main(String[] args) { + try { + System.out.println(generateArrayListFromFile(FILENAME)); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (BufferedReader br = new BufferedReader(new FileReader(filename))) { + + while (br.ready()) { + result.add(br.readLine()); + } + return result; + } + + } + +} diff --git a/file-parser/src/com/baeldung/fileparser/FileReaderExample.java b/file-parser/src/com/baeldung/fileparser/FileReaderExample.java new file mode 100644 index 0000000000..1ab98973c7 --- /dev/null +++ b/file-parser/src/com/baeldung/fileparser/FileReaderExample.java @@ -0,0 +1,37 @@ +package com.baeldung.fileparser; + +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; + +public class FileReaderExample { + + private static final String FILENAME = "src/resources/txt.txt"; + + public static void main(String[] args) { + try { + System.out.println(generateArrayListFromFile(FILENAME)); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (FileReader f = new FileReader(filename)) { + + while (f.ready()) { + char c = (char) f.read(); + + if (c != ' ' && c != '\t' && c != '\n') { + result.add(c); + } + } + return result; + } + + } + +} diff --git a/file-parser/src/com/baeldung/fileparser/FilesReadLineExample.java b/file-parser/src/com/baeldung/fileparser/FilesReadLineExample.java new file mode 100644 index 0000000000..7f94525c22 --- /dev/null +++ b/file-parser/src/com/baeldung/fileparser/FilesReadLineExample.java @@ -0,0 +1,28 @@ +package com.baeldung.fileparser; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +public class FilesReadLineExample { + + private static final String FILENAME = "src/resources/txt.txt"; + + public static void main(String[] args) { + try { + System.out.println(generateArrayListFromFile(FILENAME)); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static ArrayList generateArrayListFromFile(String filename) throws IOException { + + List result = Files.readAllLines(Paths.get(filename)); + + return (ArrayList) result; + } + +} diff --git a/file-parser/src/com/baeldung/fileparser/ScannerIntExample.java b/file-parser/src/com/baeldung/fileparser/ScannerIntExample.java new file mode 100644 index 0000000000..aab7455c30 --- /dev/null +++ b/file-parser/src/com/baeldung/fileparser/ScannerIntExample.java @@ -0,0 +1,34 @@ +package com.baeldung.fileparser; + +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Scanner; + +public class ScannerIntExample { + + private static final String FILENAME = "src/resources/num.txt"; + + public static void main(String[] args) { + try { + System.out.println(generateArrayListFromFile(FILENAME)); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (Scanner s = new Scanner(new FileReader(filename))) { + + while (s.hasNext()) { + result.add(s.nextInt()); + } + return result; + } + + } + +} diff --git a/file-parser/src/com/baeldung/fileparser/ScannerStringExample.java b/file-parser/src/com/baeldung/fileparser/ScannerStringExample.java new file mode 100644 index 0000000000..fc18b53609 --- /dev/null +++ b/file-parser/src/com/baeldung/fileparser/ScannerStringExample.java @@ -0,0 +1,34 @@ +package com.baeldung.fileparser; + +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Scanner; + +public class ScannerStringExample { + + private static final String FILENAME = "src/resources/txt.txt"; + + public static void main(String[] args) { + try { + System.out.println(generateArrayListFromFile(FILENAME)); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (Scanner s = new Scanner(new FileReader(filename))) { + + while (s.hasNext()) { + result.add(s.nextLine()); + } + return result; + } + + } + +} diff --git a/file-parser/src/resources/num.txt b/file-parser/src/resources/num.txt new file mode 100644 index 0000000000..7787faa3c1 --- /dev/null +++ b/file-parser/src/resources/num.txt @@ -0,0 +1,2 @@ +111 +222 \ No newline at end of file diff --git a/file-parser/src/resources/txt.txt b/file-parser/src/resources/txt.txt new file mode 100644 index 0000000000..75cb50aafa --- /dev/null +++ b/file-parser/src/resources/txt.txt @@ -0,0 +1,2 @@ +Hello +World \ No newline at end of file From 72d592c8d174cf14df49c1115d554a0d3263cdbf Mon Sep 17 00:00:00 2001 From: RanjeetKaur17 Date: Wed, 1 Aug 2018 10:12:20 +0400 Subject: [PATCH 03/41] Revert "A simple Real Time streaming example with Spring Webflux." This reverts commit b7d4a00dacdcddc877e1726832c4aeec378b6ed8. --- .../pom.xml | 70 ----------------- .../java/com/springwebflux/sample/Client.java | 29 ------- .../src/main/resources/application.properties | 1 - springflux-5-reactive-ranjeetkaur/pom.xml | 76 ------------------- .../springwebflux/controller/Controller.java | 28 ------- .../com/springwebflux/sample/Application.java | 17 ----- .../src/main/resources/application.properties | 1 - .../sample/ApplicationTests.java | 36 --------- 8 files changed, 258 deletions(-) delete mode 100644 springflux-5-reactive-client-ranjeetkaur/pom.xml delete mode 100644 springflux-5-reactive-client-ranjeetkaur/src/main/java/com/springwebflux/sample/Client.java delete mode 100644 springflux-5-reactive-client-ranjeetkaur/src/main/resources/application.properties delete mode 100644 springflux-5-reactive-ranjeetkaur/pom.xml delete mode 100644 springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/controller/Controller.java delete mode 100644 springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/sample/Application.java delete mode 100644 springflux-5-reactive-ranjeetkaur/src/main/resources/application.properties delete mode 100644 springflux-5-reactive-ranjeetkaur/src/test/java/com/springwebflux/sample/ApplicationTests.java diff --git a/springflux-5-reactive-client-ranjeetkaur/pom.xml b/springflux-5-reactive-client-ranjeetkaur/pom.xml deleted file mode 100644 index bb832ae055..0000000000 --- a/springflux-5-reactive-client-ranjeetkaur/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - 4.0.0 - - com.springboot - sample - 0.0.1-SNAPSHOT - jar - - client - SpringFlux Sample Client - - - org.springframework.boot - spring-boot-starter-parent - 2.0.3.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-webflux - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - - - - --spring.profiles.active=dev - - - - - - - - - spring-releases - https://repo.spring.io/libs-release - - - - - spring-releases - https://repo.spring.io/libs-release - - - - diff --git a/springflux-5-reactive-client-ranjeetkaur/src/main/java/com/springwebflux/sample/Client.java b/springflux-5-reactive-client-ranjeetkaur/src/main/java/com/springwebflux/sample/Client.java deleted file mode 100644 index 5846969803..0000000000 --- a/springflux-5-reactive-client-ranjeetkaur/src/main/java/com/springwebflux/sample/Client.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.springwebflux.sample; - -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.scheduling.annotation.EnableAsync; -import org.springframework.web.reactive.function.client.WebClient; - -/** - * @author ranjeetkaur - * - */ -@SpringBootApplication(scanBasePackages = "com.springwebflux.*") -@EnableAsync -public class Client { - - public static void main(String[] args) throws InterruptedException { - - WebClient webClient = WebClient.builder() - .baseUrl("http://localhost:8090") - .build(); - - webClient.get() - .uri("/v1/dice") - .retrieve() - .bodyToFlux(Integer.class) - .log(); - - Thread.sleep(10000); - } -} \ No newline at end of file diff --git a/springflux-5-reactive-client-ranjeetkaur/src/main/resources/application.properties b/springflux-5-reactive-client-ranjeetkaur/src/main/resources/application.properties deleted file mode 100644 index f667a68bc2..0000000000 --- a/springflux-5-reactive-client-ranjeetkaur/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -server.port =8091 \ No newline at end of file diff --git a/springflux-5-reactive-ranjeetkaur/pom.xml b/springflux-5-reactive-ranjeetkaur/pom.xml deleted file mode 100644 index 3fe4156360..0000000000 --- a/springflux-5-reactive-ranjeetkaur/pom.xml +++ /dev/null @@ -1,76 +0,0 @@ - - - 4.0.0 - - com.springboot - sample - 0.0.1-SNAPSHOT - jar - - webflux-server - SpringFlux Sample Server - - - org.springframework.boot - spring-boot-starter-parent - 2.0.3.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-webflux - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - - - - --spring.profiles.active=dev - - - - - - - - - spring-releases - https://repo.spring.io/libs-release - - - - - spring-releases - https://repo.spring.io/libs-release - - - - diff --git a/springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/controller/Controller.java b/springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/controller/Controller.java deleted file mode 100644 index fa3070640e..0000000000 --- a/springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/controller/Controller.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.springwebflux.controller; - -import java.time.Duration; -import java.util.Random; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import reactor.core.publisher.Flux; - -/** - * @author ranjeetkaur - * - */ -@RestController -@RequestMapping(value = "/v1") -public class Controller { - - private static Random random = new Random(); - - @GetMapping("/dice") - public Flux rollDice() { - return Flux.interval(Duration.ofSeconds(1)) - .map(pulse -> random.nextInt(5) + 1); - } - -} diff --git a/springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/sample/Application.java b/springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/sample/Application.java deleted file mode 100644 index 1641885f41..0000000000 --- a/springflux-5-reactive-ranjeetkaur/src/main/java/com/springwebflux/sample/Application.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.springwebflux.sample; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - * @author ranjeetkaur - * - */ -@SpringBootApplication(scanBasePackages = "com.springwebflux.*") -public class Application { - - public static void main(String[] args) { - - SpringApplication.run(Application.class, args); - } -} \ No newline at end of file diff --git a/springflux-5-reactive-ranjeetkaur/src/main/resources/application.properties b/springflux-5-reactive-ranjeetkaur/src/main/resources/application.properties deleted file mode 100644 index 91f7491179..0000000000 --- a/springflux-5-reactive-ranjeetkaur/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -server.port = 8090 \ No newline at end of file diff --git a/springflux-5-reactive-ranjeetkaur/src/test/java/com/springwebflux/sample/ApplicationTests.java b/springflux-5-reactive-ranjeetkaur/src/test/java/com/springwebflux/sample/ApplicationTests.java deleted file mode 100644 index ce09d9ae37..0000000000 --- a/springflux-5-reactive-ranjeetkaur/src/test/java/com/springwebflux/sample/ApplicationTests.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.springwebflux.sample; - -import java.time.Duration; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.reactive.server.WebTestClient; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public class ApplicationTests { - - @Autowired - private WebTestClient webTestClient; - - @Before - private void setUp() { - webTestClient = webTestClient.mutate() - .responseTimeout(Duration.ofMillis(10000)) - .build(); - } - - @Test - public void rollDice() throws InterruptedException { - webTestClient.get() - .uri("/v1/dice") - .exchange() - .expectStatus() - .isOk() - .expectBodyList(Integer.class); - } -} \ No newline at end of file From 2fae0783706a6ef2f070139233fb3373b76a7783 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Fri, 3 Aug 2018 10:32:50 +0400 Subject: [PATCH 04/41] added benchmark tests for set and list performance --- core-java-collections/pom.xml | 18 +++---- .../performance/CollectionsBenchmark.java | 53 +++++++++++++++++++ .../com/baeldung/performance/Employee.java | 31 +++++++++++ 3 files changed, 93 insertions(+), 9 deletions(-) create mode 100644 core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java create mode 100644 core-java-collections/src/main/java/com/baeldung/performance/Employee.java diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml index ff06714bfe..f954e8542e 100644 --- a/core-java-collections/pom.xml +++ b/core-java-collections/pom.xml @@ -47,26 +47,26 @@ ${eclipse.collections.version} - org.assertj - assertj-core - ${assertj.version} - test + org.openjdk.jmh + jmh-core + ${openjdk.jmh.version} - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test + org.openjdk.jmh + jmh-generator-annprocess + ${openjdk.jmh.version} + + 1.19 1.2.0 3.5 4.1 4.01 1.7.0 3.6.1 - 9.2.0 + 7.1.0 diff --git a/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java new file mode 100644 index 0000000000..64cff16cd7 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java @@ -0,0 +1,53 @@ +package com.baeldung.performance; + +import org.openjdk.jmh.annotations.*; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +public class CollectionsBenchmark { + + @State(Scope.Thread) + public static class MyState { + private Set employeeSet = new HashSet<>(); + private List employeeList = new ArrayList<>(); + + private final long m_count = 16; + + private Employee employee = new Employee(100L, "Harry"); + + @Setup(Level.Invocation) + public void setUp() { + + for (long ii = 0; ii < m_count; ii++) { + employeeSet.add(new Employee(ii, "John")); + employeeList.add(new Employee(ii, "John")); + + employeeList.add(employee); + employeeSet.add(employee); + } + } + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.MINUTES) + public boolean testArrayList(MyState state) { + return state.employeeList.contains(state.employee); + } + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.MINUTES) + public boolean testHashSet(MyState state) { + return state.employeeSet.contains(state.employee); + } + + public static void main(String[] args) throws Exception { + org.openjdk.jmh.Main.main(args); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/Employee.java b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java new file mode 100644 index 0000000000..daa68ae2f1 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java @@ -0,0 +1,31 @@ +package com.baeldung.performance; + +public class Employee { + + private Long id; + private String name; + + public Employee(Long id, String name) { + this.name = name; + this.id = id; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Employee employee = (Employee) o; + + if (!id.equals(employee.id)) return false; + return name.equals(employee.name); + + } + + @Override + public int hashCode() { + int result = id.hashCode(); + result = 31 * result + name.hashCode(); + return result; + } +} From adb14c2b95dff9ef5aeab3701e26eefb4fb3e66a Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Fri, 3 Aug 2018 10:43:37 +0400 Subject: [PATCH 05/41] bring back dependencies --- core-java-collections/pom.xml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml index f954e8542e..f9c2ec8249 100644 --- a/core-java-collections/pom.xml +++ b/core-java-collections/pom.xml @@ -46,6 +46,18 @@ eclipse-collections ${eclipse.collections.version} + + org.assertj + assertj-core + ${assertj.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + org.openjdk.jmh jmh-core From b2aeac4eb88dc7ebdf7cb7252c087032a32da0f2 Mon Sep 17 00:00:00 2001 From: RanjeetKaur17 Date: Sat, 4 Aug 2018 16:45:02 +0400 Subject: [PATCH 06/41] Moving file parser inside the core-java module. Adding Test cases for reading files. --- .../fileparser/BufferedReaderExample.java | 12 +----- .../baeldung/fileparser/FileConstants.java | 8 ++++ .../fileparser/FileReaderExample.java | 31 ++++++++++++++++ .../fileparser/FilesReadLinesExample.java | 18 +++++++++ .../fileparser/ScannerIntExample.java | 12 +----- .../fileparser/ScannerStringExample.java | 12 +----- .../fileparser/BufferedReaderUnitTest.java | 19 ++++++++++ .../fileparser/FileReaderUnitTest.java | 19 ++++++++++ .../fileparser/FilesReadAllLinesUnitTest.java | 19 ++++++++++ .../fileparser/ScannerIntUnitTest.java | 19 ++++++++++ .../fileparser/ScannerStringUnitTest.java | 19 ++++++++++ .../src/test/resources/sampleNumberFile.txt | 2 + .../src/test/resources/sampleTextFile.txt | 2 + .../fileparser/FileReaderExample.java | 37 ------------------- .../fileparser/FilesReadLineExample.java | 28 -------------- 15 files changed, 159 insertions(+), 98 deletions(-) rename {file-parser/src => core-java/src/main/java}/com/baeldung/fileparser/BufferedReaderExample.java (54%) create mode 100644 core-java/src/main/java/com/baeldung/fileparser/FileConstants.java create mode 100644 core-java/src/main/java/com/baeldung/fileparser/FileReaderExample.java create mode 100644 core-java/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java rename {file-parser/src => core-java/src/main/java}/com/baeldung/fileparser/ScannerIntExample.java (53%) rename {file-parser/src => core-java/src/main/java}/com/baeldung/fileparser/ScannerStringExample.java (54%) create mode 100644 core-java/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java create mode 100644 core-java/src/test/resources/sampleNumberFile.txt create mode 100644 core-java/src/test/resources/sampleTextFile.txt delete mode 100644 file-parser/src/com/baeldung/fileparser/FileReaderExample.java delete mode 100644 file-parser/src/com/baeldung/fileparser/FilesReadLineExample.java diff --git a/file-parser/src/com/baeldung/fileparser/BufferedReaderExample.java b/core-java/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java similarity index 54% rename from file-parser/src/com/baeldung/fileparser/BufferedReaderExample.java rename to core-java/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java index a139ed80ab..45ff486a79 100644 --- a/file-parser/src/com/baeldung/fileparser/BufferedReaderExample.java +++ b/core-java/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java @@ -7,18 +7,8 @@ import java.util.ArrayList; public class BufferedReaderExample { - private static final String FILENAME = "src/resources/txt.txt"; + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { - public static void main(String[] args) { - try { - System.out.println(generateArrayListFromFile(FILENAME)); - } catch (IOException e) { - e.printStackTrace(); - } - } - - private static ArrayList generateArrayListFromFile(String filename) throws IOException { - ArrayList result = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(filename))) { diff --git a/core-java/src/main/java/com/baeldung/fileparser/FileConstants.java b/core-java/src/main/java/com/baeldung/fileparser/FileConstants.java new file mode 100644 index 0000000000..1d3cce79f2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/fileparser/FileConstants.java @@ -0,0 +1,8 @@ +package com.baeldung.fileparser; + +public class FileConstants { + + protected static final String TEXT_FILENAME = "src/main/resources/sampleTextFile.txt"; + + protected static final String NNUMBER_FILENAME = "src/main/resources/sampleNumberFile.txt"; +} diff --git a/core-java/src/main/java/com/baeldung/fileparser/FileReaderExample.java b/core-java/src/main/java/com/baeldung/fileparser/FileReaderExample.java new file mode 100644 index 0000000000..f9dd2a9ec5 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/fileparser/FileReaderExample.java @@ -0,0 +1,31 @@ +package com.baeldung.fileparser; + +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; + +public class FileReaderExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + ArrayList result = new ArrayList<>(); + + try (FileReader f = new FileReader(filename)) { + StringBuffer sb = new StringBuffer(); + while (f.ready()) { + char c = (char) f.read(); + if (c == '\n') { + result.add(sb.toString()); + sb = new StringBuffer(); + } else { + sb.append(c); + } + } + if (sb.length() > 0) { + result.add(sb.toString()); + } + } + + return result; + } +} diff --git a/core-java/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java b/core-java/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java new file mode 100644 index 0000000000..8e74f7d386 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java @@ -0,0 +1,18 @@ +package com.baeldung.fileparser; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +public class FilesReadLinesExample { + + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { + + List result = Files.readAllLines(Paths.get(filename)); + + return (ArrayList) result; + } + +} diff --git a/file-parser/src/com/baeldung/fileparser/ScannerIntExample.java b/core-java/src/main/java/com/baeldung/fileparser/ScannerIntExample.java similarity index 53% rename from file-parser/src/com/baeldung/fileparser/ScannerIntExample.java rename to core-java/src/main/java/com/baeldung/fileparser/ScannerIntExample.java index aab7455c30..25d17af4ea 100644 --- a/file-parser/src/com/baeldung/fileparser/ScannerIntExample.java +++ b/core-java/src/main/java/com/baeldung/fileparser/ScannerIntExample.java @@ -7,17 +7,7 @@ import java.util.Scanner; public class ScannerIntExample { - private static final String FILENAME = "src/resources/num.txt"; - - public static void main(String[] args) { - try { - System.out.println(generateArrayListFromFile(FILENAME)); - } catch (IOException e) { - e.printStackTrace(); - } - } - - private static ArrayList generateArrayListFromFile(String filename) throws IOException { + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { ArrayList result = new ArrayList<>(); diff --git a/file-parser/src/com/baeldung/fileparser/ScannerStringExample.java b/core-java/src/main/java/com/baeldung/fileparser/ScannerStringExample.java similarity index 54% rename from file-parser/src/com/baeldung/fileparser/ScannerStringExample.java rename to core-java/src/main/java/com/baeldung/fileparser/ScannerStringExample.java index fc18b53609..ec213c9490 100644 --- a/file-parser/src/com/baeldung/fileparser/ScannerStringExample.java +++ b/core-java/src/main/java/com/baeldung/fileparser/ScannerStringExample.java @@ -7,17 +7,7 @@ import java.util.Scanner; public class ScannerStringExample { - private static final String FILENAME = "src/resources/txt.txt"; - - public static void main(String[] args) { - try { - System.out.println(generateArrayListFromFile(FILENAME)); - } catch (IOException e) { - e.printStackTrace(); - } - } - - private static ArrayList generateArrayListFromFile(String filename) throws IOException { + protected static ArrayList generateArrayListFromFile(String filename) throws IOException { ArrayList result = new ArrayList<>(); diff --git a/core-java/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java new file mode 100644 index 0000000000..78f900d796 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class BufferedReaderUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = BufferedReaderExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java new file mode 100644 index 0000000000..a38e58d348 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class FileReaderUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = FileReaderExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java new file mode 100644 index 0000000000..c0b742fd47 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class FilesReadAllLinesUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = FilesReadLinesExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java new file mode 100644 index 0000000000..0a398ba7c6 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class ScannerIntUnitTest { + + protected static final String NUMBER_FILENAME = "src/test/resources/sampleNumberFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetIntArrayList() throws IOException { + List numbers = ScannerIntExample.generateArrayListFromFile(NUMBER_FILENAME); + assertTrue("File does not has 2 lines", numbers.size() == 2); + } +} diff --git a/core-java/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java new file mode 100644 index 0000000000..8f9b0a56c0 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.fileparser; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +public class ScannerStringUnitTest { + + protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt"; + + @Test + public void whenParsingExistingTextFile_thenGetArrayList() throws IOException { + List lines = ScannerStringExample.generateArrayListFromFile(TEXT_FILENAME); + assertTrue("File does not has 2 lines", lines.size() == 2); + } +} diff --git a/core-java/src/test/resources/sampleNumberFile.txt b/core-java/src/test/resources/sampleNumberFile.txt new file mode 100644 index 0000000000..7787faa3c1 --- /dev/null +++ b/core-java/src/test/resources/sampleNumberFile.txt @@ -0,0 +1,2 @@ +111 +222 \ No newline at end of file diff --git a/core-java/src/test/resources/sampleTextFile.txt b/core-java/src/test/resources/sampleTextFile.txt new file mode 100644 index 0000000000..75cb50aafa --- /dev/null +++ b/core-java/src/test/resources/sampleTextFile.txt @@ -0,0 +1,2 @@ +Hello +World \ No newline at end of file diff --git a/file-parser/src/com/baeldung/fileparser/FileReaderExample.java b/file-parser/src/com/baeldung/fileparser/FileReaderExample.java deleted file mode 100644 index 1ab98973c7..0000000000 --- a/file-parser/src/com/baeldung/fileparser/FileReaderExample.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.fileparser; - -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; - -public class FileReaderExample { - - private static final String FILENAME = "src/resources/txt.txt"; - - public static void main(String[] args) { - try { - System.out.println(generateArrayListFromFile(FILENAME)); - } catch (IOException e) { - e.printStackTrace(); - } - } - - private static ArrayList generateArrayListFromFile(String filename) throws IOException { - - ArrayList result = new ArrayList<>(); - - try (FileReader f = new FileReader(filename)) { - - while (f.ready()) { - char c = (char) f.read(); - - if (c != ' ' && c != '\t' && c != '\n') { - result.add(c); - } - } - return result; - } - - } - -} diff --git a/file-parser/src/com/baeldung/fileparser/FilesReadLineExample.java b/file-parser/src/com/baeldung/fileparser/FilesReadLineExample.java deleted file mode 100644 index 7f94525c22..0000000000 --- a/file-parser/src/com/baeldung/fileparser/FilesReadLineExample.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.fileparser; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; - -public class FilesReadLineExample { - - private static final String FILENAME = "src/resources/txt.txt"; - - public static void main(String[] args) { - try { - System.out.println(generateArrayListFromFile(FILENAME)); - } catch (IOException e) { - e.printStackTrace(); - } - } - - private static ArrayList generateArrayListFromFile(String filename) throws IOException { - - List result = Files.readAllLines(Paths.get(filename)); - - return (ArrayList) result; - } - -} From 406146f959fbf4ccefc95bc786ad97d74ddb7140 Mon Sep 17 00:00:00 2001 From: RanjeetKaur17 Date: Sat, 4 Aug 2018 16:52:27 +0400 Subject: [PATCH 07/41] Removing unused file. --- .../main/java/com/baeldung/fileparser/FileConstants.java | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 core-java/src/main/java/com/baeldung/fileparser/FileConstants.java diff --git a/core-java/src/main/java/com/baeldung/fileparser/FileConstants.java b/core-java/src/main/java/com/baeldung/fileparser/FileConstants.java deleted file mode 100644 index 1d3cce79f2..0000000000 --- a/core-java/src/main/java/com/baeldung/fileparser/FileConstants.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.fileparser; - -public class FileConstants { - - protected static final String TEXT_FILENAME = "src/main/resources/sampleTextFile.txt"; - - protected static final String NNUMBER_FILENAME = "src/main/resources/sampleNumberFile.txt"; -} From 38327e77714ec3890356cf19718a96c66cae40d7 Mon Sep 17 00:00:00 2001 From: RanjeetKaur17 Date: Sat, 4 Aug 2018 16:53:38 +0400 Subject: [PATCH 08/41] Removing unused files. --- file-parser/src/resources/num.txt | 2 -- file-parser/src/resources/txt.txt | 2 -- 2 files changed, 4 deletions(-) delete mode 100644 file-parser/src/resources/num.txt delete mode 100644 file-parser/src/resources/txt.txt diff --git a/file-parser/src/resources/num.txt b/file-parser/src/resources/num.txt deleted file mode 100644 index 7787faa3c1..0000000000 --- a/file-parser/src/resources/num.txt +++ /dev/null @@ -1,2 +0,0 @@ -111 -222 \ No newline at end of file diff --git a/file-parser/src/resources/txt.txt b/file-parser/src/resources/txt.txt deleted file mode 100644 index 75cb50aafa..0000000000 --- a/file-parser/src/resources/txt.txt +++ /dev/null @@ -1,2 +0,0 @@ -Hello -World \ No newline at end of file From dccf0c3b0bbc77536666ecba3554d7c29ca1ecee Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Fri, 10 Aug 2018 17:50:13 +0400 Subject: [PATCH 09/41] bring back dependencies --- .../performance/CollectionsBenchmark.java | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java index 64cff16cd7..ff1e8d7953 100644 --- a/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java +++ b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java @@ -1,6 +1,9 @@ package com.baeldung.performance; import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.ArrayList; import java.util.HashSet; @@ -15,14 +18,14 @@ public class CollectionsBenchmark { private Set employeeSet = new HashSet<>(); private List employeeList = new ArrayList<>(); - private final long m_count = 16; + private long iterations = 10000; private Employee employee = new Employee(100L, "Harry"); - @Setup(Level.Invocation) + @Setup(Level.Trial) public void setUp() { - for (long ii = 0; ii < m_count; ii++) { + for (long ii = 0; ii < iterations; ii++) { employeeSet.add(new Employee(ii, "John")); employeeList.add(new Employee(ii, "John")); @@ -35,19 +38,26 @@ public class CollectionsBenchmark { @Benchmark @BenchmarkMode(Mode.AverageTime) - @OutputTimeUnit(TimeUnit.MINUTES) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + @Warmup(iterations = 1) public boolean testArrayList(MyState state) { return state.employeeList.contains(state.employee); } @Benchmark @BenchmarkMode(Mode.AverageTime) - @OutputTimeUnit(TimeUnit.MINUTES) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + @Warmup(iterations = 1) public boolean testHashSet(MyState state) { return state.employeeSet.contains(state.employee); } public static void main(String[] args) throws Exception { - org.openjdk.jmh.Main.main(args); + Options options = new OptionsBuilder() + .include(CollectionsBenchmark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); } } From 570e33dc1af438c6d2ee8054b7e2d4c8a62d3016 Mon Sep 17 00:00:00 2001 From: eelhazati Date: Thu, 9 Aug 2018 21:48:09 +0100 Subject: [PATCH 10/41] move sse-jaxrs module under apache-cxf module. --- apache-cxf/pom.xml | 3 +- apache-cxf/sse-jaxrs/pom.xml | 21 ++++ apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml | 62 +++++++++ .../sse/jaxrs/client/SseClientApp.java | 48 +++++++ .../jaxrs/client/SseClientBroadcastApp.java | 52 ++++++++ .../src/main/resources/logback.xml | 13 ++ apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml | 85 +++++++++++++ .../com/baeldung/sse/jaxrs/AppConfig.java | 8 ++ .../com/baeldung/sse/jaxrs/SseResource.java | 119 ++++++++++++++++++ .../java/com/baeldung/sse/jaxrs/Stock.java | 50 ++++++++ .../com/baeldung/sse/jaxrs/StockService.java | 78 ++++++++++++ .../src/main/liberty/config/server.xml | 7 ++ .../src/main/resources/META-INF/beans.xml | 6 + .../src/main/resources/logback.xml | 13 ++ .../src/main/webapp/WEB-INF/web.xml | 11 ++ .../src/main/webapp/index.html | 1 + .../src/main/webapp/sse-broadcast.html | 38 ++++++ .../sse-jaxrs-server/src/main/webapp/sse.html | 38 ++++++ core-kotlin/src/test/resources/Kotlin.out | 2 + pom.xml | 1 - 20 files changed, 654 insertions(+), 2 deletions(-) create mode 100644 apache-cxf/sse-jaxrs/pom.xml create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html create mode 100644 apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html create mode 100644 core-kotlin/src/test/resources/Kotlin.out diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml index 53d9d4054c..8918fd4450 100644 --- a/apache-cxf/pom.xml +++ b/apache-cxf/pom.xml @@ -1,5 +1,5 @@ + 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 apache-cxf @@ -17,6 +17,7 @@ cxf-spring cxf-jaxrs-implementation cxf-aegis + sse-jaxrs diff --git a/apache-cxf/sse-jaxrs/pom.xml b/apache-cxf/sse-jaxrs/pom.xml new file mode 100644 index 0000000000..d4b6c19d03 --- /dev/null +++ b/apache-cxf/sse-jaxrs/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + + sse-jaxrs + pom + + + com.baeldung + apache-cxf + 0.0.1-SNAPSHOT + + + + sse-jaxrs-server + sse-jaxrs-client + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml new file mode 100644 index 0000000000..0f5406fbc7 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + + com.baeldung + sse-jaxrs + 0.0.1-SNAPSHOT + + + sse-jaxrs-client + + + 3.2.0 + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + singleEvent + + java + + + com.baeldung.sse.jaxrs.client.SseClientApp + + + + broadcast + + java + + + com.baeldung.sse.jaxrs.client.SseClientBroadcastApp + + + + + + + + + + org.apache.cxf + cxf-rt-rs-client + ${cxf-version} + + + org.apache.cxf + cxf-rt-rs-sse + ${cxf-version} + + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java new file mode 100644 index 0000000000..5d42b3a243 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java @@ -0,0 +1,48 @@ +package com.baeldung.sse.jaxrs.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.sse.InboundSseEvent; +import javax.ws.rs.sse.SseEventSource; +import java.util.function.Consumer; + +public class SseClientApp { + + private static final String url = "http://127.0.0.1:9080/sse-jaxrs-server/sse/stock/prices"; + + public static void main(String... args) throws Exception { + + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(url); + try (SseEventSource eventSource = SseEventSource.target(target).build()) { + + eventSource.register(onEvent, onError, onComplete); + eventSource.open(); + + //Consuming events for one hour + Thread.sleep(60 * 60 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + client.close(); + System.out.println("End"); + } + + // A new event is received + private static Consumer onEvent = (inboundSseEvent) -> { + String data = inboundSseEvent.readData(); + System.out.println(data); + }; + + //Error + private static Consumer onError = (throwable) -> { + throwable.printStackTrace(); + }; + + //Connection close and there is nothing to receive + private static Runnable onComplete = () -> { + System.out.println("Done!"); + }; + +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java new file mode 100644 index 0000000000..9afc187a6d --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java @@ -0,0 +1,52 @@ +package com.baeldung.sse.jaxrs.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.sse.InboundSseEvent; +import javax.ws.rs.sse.SseEventSource; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +public class SseClientBroadcastApp { + + private static final String subscribeUrl = "http://localhost:9080/sse-jaxrs-server/sse/stock/subscribe"; + + + public static void main(String... args) throws Exception { + + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(subscribeUrl); + try (final SseEventSource eventSource = SseEventSource.target(target) + .reconnectingEvery(5, TimeUnit.SECONDS) + .build()) { + eventSource.register(onEvent, onError, onComplete); + eventSource.open(); + System.out.println("Wainting for incoming event ..."); + + //Consuming events for one hour + Thread.sleep(60 * 60 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + client.close(); + System.out.println("End"); + } + + // A new event is received + private static Consumer onEvent = (inboundSseEvent) -> { + String data = inboundSseEvent.readData(); + System.out.println(data); + }; + + //Error + private static Consumer onError = (throwable) -> { + throwable.printStackTrace(); + }; + + //Connection close and there is nothing to receive + private static Runnable onComplete = () -> { + System.out.println("Done!"); + }; + +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml new file mode 100644 index 0000000000..46572a2b75 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml @@ -0,0 +1,85 @@ + + + 4.0.0 + + + com.baeldung + sse-jaxrs + 0.0.1-SNAPSHOT + + + sse-jaxrs-server + war + + + 2.4.2 + false + 18.0.0.2 + + + + ${artifactId} + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + ${liberty-maven-plugin.version} + + + io.openliberty + openliberty-webProfile8 + ${openliberty-version} + zip + + project + true + src/main/liberty/config/server.xml + + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + + + + + + javax.ws.rs + javax.ws.rs-api + 2.1 + provided + + + javax.enterprise + cdi-api + 2.0 + provided + + + javax.json.bind + javax.json.bind-api + 1.0 + provided + + + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java new file mode 100644 index 0000000000..058d19f045 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java @@ -0,0 +1,8 @@ +package com.baeldung.sse.jaxrs; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("sse") +public class AppConfig extends Application { +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java new file mode 100644 index 0000000000..1f60168a1b --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java @@ -0,0 +1,119 @@ +package com.baeldung.sse.jaxrs; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.sse.OutboundSseEvent; +import javax.ws.rs.sse.Sse; +import javax.ws.rs.sse.SseBroadcaster; +import javax.ws.rs.sse.SseEventSink; + +@ApplicationScoped +@Path("stock") +public class SseResource { + + @Inject + private StockService stockService; + + private Sse sse; + private SseBroadcaster sseBroadcaster; + private OutboundSseEvent.Builder eventBuilder; + + @Context + public void setSse(Sse sse) { + this.sse = sse; + this.eventBuilder = sse.newEventBuilder(); + this.sseBroadcaster = sse.newBroadcaster(); + } + + @GET + @Path("prices") + @Produces("text/event-stream") + public void getStockPrices(@Context SseEventSink sseEventSink, + @HeaderParam(HttpHeaders.LAST_EVENT_ID_HEADER) @DefaultValue("-1") int lastReceivedId) { + + int lastEventId = 1; + if (lastReceivedId != -1) { + lastEventId = ++lastReceivedId; + } + boolean running = true; + while (running) { + Stock stock = stockService.getNextTransaction(lastEventId); + if (stock != null) { + OutboundSseEvent sseEvent = this.eventBuilder + .name("stock") + .id(String.valueOf(lastEventId)) + .mediaType(MediaType.APPLICATION_JSON_TYPE) + .data(Stock.class, stock) + .reconnectDelay(3000) + .comment("price change") + .build(); + sseEventSink.send(sseEvent); + lastEventId++; + } + //Simulate connection close + if (lastEventId % 5 == 0) { + sseEventSink.close(); + break; + } + + try { + //Wait 5 seconds + Thread.sleep(5 * 1000); + } catch (InterruptedException ex) { + // ... + } + //Simulatae a while boucle break + running = lastEventId <= 2000; + } + sseEventSink.close(); + } + + @GET + @Path("subscribe") + @Produces(MediaType.SERVER_SENT_EVENTS) + public void listen(@Context SseEventSink sseEventSink) { + sseEventSink.send(sse.newEvent("Welcome !")); + this.sseBroadcaster.register(sseEventSink); + sseEventSink.send(sse.newEvent("You are registred !")); + } + + @GET + @Path("publish") + public void broadcast() { + Runnable r = new Runnable() { + @Override + public void run() { + int lastEventId = 0; + boolean running = true; + while (running) { + lastEventId++; + Stock stock = stockService.getNextTransaction(lastEventId); + if (stock != null) { + OutboundSseEvent sseEvent = eventBuilder + .name("stock") + .id(String.valueOf(lastEventId)) + .mediaType(MediaType.APPLICATION_JSON_TYPE) + .data(Stock.class, stock) + .reconnectDelay(3000) + .comment("price change") + .build(); + sseBroadcaster.broadcast(sseEvent); + } + try { + //Wait 5 seconds + Thread.currentThread().sleep(5 * 1000); + } catch (InterruptedException ex) { + // ... + } + //Simulatae a while boucle break + running = lastEventId <= 2000; + } + } + }; + new Thread(r).start(); + } +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java new file mode 100644 index 0000000000..a186b32771 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java @@ -0,0 +1,50 @@ +package com.baeldung.sse.jaxrs; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +public class Stock { + private Integer id; + private String name; + private BigDecimal price; + LocalDateTime dateTime; + + public Stock(Integer id, String name, BigDecimal price, LocalDateTime dateTime) { + this.id = id; + this.name = name; + this.price = price; + this.dateTime = dateTime; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public LocalDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(LocalDateTime dateTime) { + this.dateTime = dateTime; + } +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java new file mode 100644 index 0000000000..15818ead5d --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java @@ -0,0 +1,78 @@ +package com.baeldung.sse.jaxrs; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.context.Initialized; +import javax.enterprise.event.Event; +import javax.enterprise.event.Observes; +import javax.inject.Inject; +import javax.inject.Named; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import java.util.concurrent.atomic.AtomicInteger; + +@ApplicationScoped +@Named +public class StockService { + + private static final BigDecimal UP = BigDecimal.valueOf(1.05f); + private static final BigDecimal DOWN = BigDecimal.valueOf(0.95f); + + List stockNames = Arrays.asList("GOOG", "IBM", "MS", "GOOG", "YAHO"); + List stocksDB = new ArrayList<>(); + private AtomicInteger counter = new AtomicInteger(0); + + public void init(@Observes @Initialized(ApplicationScoped.class) Object init) { + //Open price + System.out.println("@Start Init ..."); + stockNames.forEach(stockName -> { + stocksDB.add(new Stock(counter.incrementAndGet(), stockName, generateOpenPrice(), LocalDateTime.now())); + }); + + Runnable runnable = new Runnable() { + @Override + public void run() { + //Simulate Change price and put every x seconds + while (true) { + int indx = new Random().nextInt(stockNames.size()); + String stockName = stockNames.get(indx); + BigDecimal price = getLastPrice(stockName); + BigDecimal newprice = changePrice(price); + Stock stock = new Stock(counter.incrementAndGet(), stockName, newprice, LocalDateTime.now()); + stocksDB.add(stock); + + int r = new Random().nextInt(30); + try { + Thread.currentThread().sleep(r*1000); + } catch (InterruptedException ex) { + // ... + } + } + } + }; + new Thread(runnable).start(); + System.out.println("@End Init ..."); + } + + public Stock getNextTransaction(Integer lastEventId) { + return stocksDB.stream().filter(s -> s.getId().equals(lastEventId)).findFirst().orElse(null); + } + + BigDecimal generateOpenPrice() { + float min = 70; + float max = 120; + return BigDecimal.valueOf(min + new Random().nextFloat() * (max - min)).setScale(4,RoundingMode.CEILING); + } + + BigDecimal changePrice(BigDecimal price) { + return Math.random() >= 0.5 ? price.multiply(UP).setScale(4,RoundingMode.CEILING) : price.multiply(DOWN).setScale(4,RoundingMode.CEILING); + } + + private BigDecimal getLastPrice(String stockName) { + return stocksDB.stream().filter(stock -> stock.getName().equals(stockName)).findFirst().get().getPrice(); + } +} diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..9bf66d7795 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml @@ -0,0 +1,7 @@ + + + jaxrs-2.1 + cdi-2.0 + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..4f0b3cdeeb --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..b4b8121fdd --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,11 @@ + + + Hello Servlet + + + index.html + + + diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html new file mode 100644 index 0000000000..9015a7a32c --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html @@ -0,0 +1 @@ +index diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html new file mode 100644 index 0000000000..5a46e2a5d3 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html @@ -0,0 +1,38 @@ + + + + Server-Sent Event Broadcasting + + +

Stock prices :

+
+
    +
+
+ + + \ No newline at end of file diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html new file mode 100644 index 0000000000..8fddae4717 --- /dev/null +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html @@ -0,0 +1,38 @@ + + + + Server-Sent Event + + +

Stock prices :

+
+
    +
+
+ + + \ No newline at end of file diff --git a/core-kotlin/src/test/resources/Kotlin.out b/core-kotlin/src/test/resources/Kotlin.out new file mode 100644 index 0000000000..63d15d2528 --- /dev/null +++ b/core-kotlin/src/test/resources/Kotlin.out @@ -0,0 +1,2 @@ +Kotlin +Concise, Safe, Interoperable, Tool-friendly \ No newline at end of file diff --git a/pom.xml b/pom.xml index 978e27f055..db3bef7fda 100644 --- a/pom.xml +++ b/pom.xml @@ -587,7 +587,6 @@ apache-meecrowave spring-reactive-kotlin jnosql - sse-jaxrs spring-boot-angular-ecommerce From 4cd349f5337fd2b3d5d845a6c55c3bd37363e749 Mon Sep 17 00:00:00 2001 From: Kacper Date: Fri, 10 Aug 2018 21:10:15 +0200 Subject: [PATCH 11/41] Kotlin constructors (#4933) --- .../main/java/com/baeldung/constructor/Car.kt | 17 ++++++++++++ .../java/com/baeldung/constructor/Employee.kt | 3 +++ .../java/com/baeldung/constructor/Person.java | 19 ++++++++++++++ .../kotlin/com/baeldung/constructor/Person.kt | 26 +++++++++++++++++++ 4 files changed, 65 insertions(+) create mode 100644 core-kotlin/src/main/java/com/baeldung/constructor/Car.kt create mode 100644 core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt create mode 100644 core-kotlin/src/main/java/com/baeldung/constructor/Person.java create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt b/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt new file mode 100644 index 0000000000..72b8d330e8 --- /dev/null +++ b/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt @@ -0,0 +1,17 @@ +package com.baeldung.constructor + +class Car { + val id: String + val type: String + + constructor(id: String, type: String) { + this.id = id + this.type = type + } + +} + +fun main(args: Array) { + val car = Car("1", "sport") + val s= Car("2", "suv") +} \ No newline at end of file diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt b/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt new file mode 100644 index 0000000000..4483bfcf08 --- /dev/null +++ b/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt @@ -0,0 +1,3 @@ +package com.baeldung.constructor + +class Employee(name: String, val salary: Int): Person(name) \ No newline at end of file diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Person.java b/core-kotlin/src/main/java/com/baeldung/constructor/Person.java new file mode 100644 index 0000000000..57911b24ee --- /dev/null +++ b/core-kotlin/src/main/java/com/baeldung/constructor/Person.java @@ -0,0 +1,19 @@ +package com.baeldung.constructor; + +class PersonJava { + final String name; + final String surname; + final Integer age; + + public PersonJava(String name, String surname) { + this.name = name; + this.surname = surname; + this.age = null; + } + + public PersonJava(String name, String surname, Integer age) { + this.name = name; + this.surname = surname; + this.age = age; + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt b/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt new file mode 100644 index 0000000000..3779d74541 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt @@ -0,0 +1,26 @@ +package com.baeldung.constructor + +open class Person( + val name: String, + val age: Int? = null +) { + val upperCaseName: String = name.toUpperCase() + + init { + println("Hello, I'm $name") + + if (age != null && age < 0) { + throw IllegalArgumentException("Age cannot be less than zero!") + } + } + + init { + println("upperCaseName is $upperCaseName") + } + +} + +fun main(args: Array) { + val person = Person("John") + val personWithAge = Person("John", 22) +} \ No newline at end of file From d3a02b789ebaf0aa1375a97175c5e23921fe70fa Mon Sep 17 00:00:00 2001 From: Denis Date: Sat, 11 Aug 2018 00:31:45 +0200 Subject: [PATCH 12/41] BAEL-1997 state design pattern in Java (#4827) * BAEL-1997 state design pattern in Java * BAEL-1997 different example code * BAEL-1997 add additional method to the states * BAEL-1997 clean up in ReceivedState --- .../com/baeldung/state/DeliveredState.java | 25 ++++++++++++++ .../java/com/baeldung/state/OrderedState.java | 24 ++++++++++++++ .../main/java/com/baeldung/state/Package.java | 26 +++++++++++++++ .../java/com/baeldung/state/PackageState.java | 10 ++++++ .../com/baeldung/state/ReceivedState.java | 24 ++++++++++++++ .../java/com/baeldung/state/StateDemo.java | 19 +++++++++++ .../baeldung/state/StatePatternUnitTest.java | 33 +++++++++++++++++++ 7 files changed, 161 insertions(+) create mode 100644 patterns/design-patterns/src/main/java/com/baeldung/state/DeliveredState.java create mode 100644 patterns/design-patterns/src/main/java/com/baeldung/state/OrderedState.java create mode 100644 patterns/design-patterns/src/main/java/com/baeldung/state/Package.java create mode 100644 patterns/design-patterns/src/main/java/com/baeldung/state/PackageState.java create mode 100644 patterns/design-patterns/src/main/java/com/baeldung/state/ReceivedState.java create mode 100644 patterns/design-patterns/src/main/java/com/baeldung/state/StateDemo.java create mode 100644 patterns/design-patterns/src/test/java/com/baeldung/state/StatePatternUnitTest.java diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/DeliveredState.java b/patterns/design-patterns/src/main/java/com/baeldung/state/DeliveredState.java new file mode 100644 index 0000000000..9f5e4d8fc4 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/DeliveredState.java @@ -0,0 +1,25 @@ +package com.baeldung.state; + +public class DeliveredState implements PackageState { + + @Override + public void next(Package pkg) { + pkg.setState(new ReceivedState()); + } + + @Override + public void prev(Package pkg) { + pkg.setState(new OrderedState()); + } + + @Override + public void printStatus() { + System.out.println("Package delivered to post office, not received yet."); + } + + @Override + public String toString() { + return "DeliveredState{}"; + } + +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/OrderedState.java b/patterns/design-patterns/src/main/java/com/baeldung/state/OrderedState.java new file mode 100644 index 0000000000..0642c4c73c --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/OrderedState.java @@ -0,0 +1,24 @@ +package com.baeldung.state; + +public class OrderedState implements PackageState { + + @Override + public void next(Package pkg) { + pkg.setState(new DeliveredState()); + } + + @Override + public void prev(Package pkg) { + System.out.println("The package is in it's root state."); + } + + @Override + public void printStatus() { + System.out.println("Package ordered, not delivered to the office yet."); + } + + @Override + public String toString() { + return "OrderedState{}"; + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/Package.java b/patterns/design-patterns/src/main/java/com/baeldung/state/Package.java new file mode 100644 index 0000000000..f3dfbb3fa7 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/Package.java @@ -0,0 +1,26 @@ +package com.baeldung.state; + +public class Package { + + private PackageState state = new OrderedState(); + + public PackageState getState() { + return state; + } + + public void setState(PackageState state) { + this.state = state; + } + + public void previousState() { + state.prev(this); + } + + public void nextState() { + state.next(this); + } + + public void printStatus() { + state.printStatus(); + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/PackageState.java b/patterns/design-patterns/src/main/java/com/baeldung/state/PackageState.java new file mode 100644 index 0000000000..d6656c78ac --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/PackageState.java @@ -0,0 +1,10 @@ +package com.baeldung.state; + +public interface PackageState { + + void next(Package pkg); + + void prev(Package pkg); + + void printStatus(); +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/ReceivedState.java b/patterns/design-patterns/src/main/java/com/baeldung/state/ReceivedState.java new file mode 100644 index 0000000000..84136fa48e --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/ReceivedState.java @@ -0,0 +1,24 @@ +package com.baeldung.state; + +public class ReceivedState implements PackageState { + + @Override + public void next(Package pkg) { + System.out.println("This package is already received by a client."); + } + + @Override + public void prev(Package pkg) { + pkg.setState(new DeliveredState()); + } + + @Override + public void printStatus() { + System.out.println("Package was received by client."); + } + + @Override + public String toString() { + return "ReceivedState{}"; + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/state/StateDemo.java b/patterns/design-patterns/src/main/java/com/baeldung/state/StateDemo.java new file mode 100644 index 0000000000..1a63ea3ddf --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/state/StateDemo.java @@ -0,0 +1,19 @@ +package com.baeldung.state; + +public class StateDemo { + + public static void main(String[] args) { + + Package pkg = new Package(); + pkg.printStatus(); + + pkg.nextState(); + pkg.printStatus(); + + pkg.nextState(); + pkg.printStatus(); + + pkg.nextState(); + pkg.printStatus(); + } +} diff --git a/patterns/design-patterns/src/test/java/com/baeldung/state/StatePatternUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/state/StatePatternUnitTest.java new file mode 100644 index 0000000000..731974f92b --- /dev/null +++ b/patterns/design-patterns/src/test/java/com/baeldung/state/StatePatternUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.state; + +import com.baeldung.state.Package; + +import static org.junit.Assert.assertThat; +import static org.hamcrest.CoreMatchers.instanceOf; + +import org.junit.Test; + +public class StatePatternUnitTest { + + @Test + public void givenNewPackage_whenPackageReceived_thenStateReceived() { + Package pkg = new Package(); + + assertThat(pkg.getState(), instanceOf(OrderedState.class)); + pkg.nextState(); + + assertThat(pkg.getState(), instanceOf(DeliveredState.class)); + pkg.nextState(); + + assertThat(pkg.getState(), instanceOf(ReceivedState.class)); + } + + @Test + public void givenDeliveredPackage_whenPrevState_thenStateOrdered() { + Package pkg = new Package(); + pkg.setState(new DeliveredState()); + pkg.previousState(); + + assertThat(pkg.getState(), instanceOf(OrderedState.class)); + } +} From 5b9df5d901bc8768fcdcea181c3eec5e25680c9e Mon Sep 17 00:00:00 2001 From: Mher Baghinyan Date: Sat, 11 Aug 2018 17:52:08 +0400 Subject: [PATCH 13/41] Update CollectionsBenchmark.java --- .../java/com/baeldung/performance/CollectionsBenchmark.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java index ff1e8d7953..e5b7787438 100644 --- a/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java +++ b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java @@ -28,10 +28,10 @@ public class CollectionsBenchmark { for (long ii = 0; ii < iterations; ii++) { employeeSet.add(new Employee(ii, "John")); employeeList.add(new Employee(ii, "John")); - - employeeList.add(employee); - employeeSet.add(employee); } + + employeeList.add(employee); + employeeSet.add(employee); } } From 224dce952b93153bb8c96eb0c2d0a2b4885e2b69 Mon Sep 17 00:00:00 2001 From: Mher Baghinyan Date: Sat, 11 Aug 2018 18:06:21 +0400 Subject: [PATCH 14/41] Update CollectionsBenchmark.java --- .../java/com/baeldung/performance/CollectionsBenchmark.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java index e5b7787438..6d36789c2b 100644 --- a/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java +++ b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java @@ -25,9 +25,9 @@ public class CollectionsBenchmark { @Setup(Level.Trial) public void setUp() { - for (long ii = 0; ii < iterations; ii++) { - employeeSet.add(new Employee(ii, "John")); - employeeList.add(new Employee(ii, "John")); + for (long i = 0; i < iterations; i++) { + employeeSet.add(new Employee(i, "John")); + employeeList.add(new Employee(i, "John")); } employeeList.add(employee); From b23980ae2cdd4c4df61767de65798ca38fb5c424 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Sat, 11 Aug 2018 14:06:49 +0530 Subject: [PATCH 15/41] BAEL-1857 Updated to parent pom.xml --- testing-modules/parallel-tests-junit/pom.xml | 60 ++++---------------- 1 file changed, 11 insertions(+), 49 deletions(-) diff --git a/testing-modules/parallel-tests-junit/pom.xml b/testing-modules/parallel-tests-junit/pom.xml index 1a42437b1b..3fd4e695e5 100644 --- a/testing-modules/parallel-tests-junit/pom.xml +++ b/testing-modules/parallel-tests-junit/pom.xml @@ -1,50 +1,12 @@ - - 4.0.0 - - com.baeldung - parallel-tests-junit - 0.0.1-SNAPSHOT - jar - - parallel-tests-junit - http://maven.apache.org - - - UTF-8 - - - - - junit - junit - 4.12 - test - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.0 - - all - 10 - 2 - 2 - 6 - 3.5 - 5 - true - - FunctionTestSuite.class - - - - - - - + + + 4.0.0 + com.baeldung + parallel-tests-junit + 0.0.1-SNAPSHOT + pom + + math-test-functions + string-test-functions + From 87e6645b1ce67db4e01077eca021c0a4195caef0 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Sat, 11 Aug 2018 14:07:58 +0530 Subject: [PATCH 16/41] BAEL-1857 Delete FunctionTestSuite.java --- .../src/test/java/com/baeldung/FunctionTestSuite.java | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 testing-modules/parallel-tests-junit/src/test/java/com/baeldung/FunctionTestSuite.java diff --git a/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/FunctionTestSuite.java b/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/FunctionTestSuite.java deleted file mode 100644 index c7f4050b18..0000000000 --- a/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/FunctionTestSuite.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({StringFunctionTest.class, MathFunctionTest.class}) -public class FunctionTestSuite { - -} From 24ba05ce0df372e92e574c6629ce007289179fab Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Sat, 11 Aug 2018 14:08:43 +0530 Subject: [PATCH 17/41] BAEL-1857 Delete MathFunctionTest.java --- .../java/com/baeldung/MathFunctionTest.java | 29 ------------------- 1 file changed, 29 deletions(-) delete mode 100644 testing-modules/parallel-tests-junit/src/test/java/com/baeldung/MathFunctionTest.java diff --git a/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/MathFunctionTest.java b/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/MathFunctionTest.java deleted file mode 100644 index 9a609c3e93..0000000000 --- a/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/MathFunctionTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class MathFunctionTest { - - @Test - public void test_addingIntegers_returnsSum() throws InterruptedException { - assertEquals(22, Math.addExact(10, 12)); - - } - - @Test - public void test_multiplyingIntegers_returnsProduct() { - assertEquals(120, Math.multiplyExact(10, 12)); - } - - @Test - public void test_subtractingIntegers_returnsDifference() { - assertEquals(2, Math.subtractExact(12, 10)); - } - - @Test - public void test_minimumInteger() { - assertEquals(10, Math.min(10, 12)); - } -} From d78acb07a1e8d7afd034ad08dfb8d6b14e543c09 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Sat, 11 Aug 2018 14:09:16 +0530 Subject: [PATCH 18/41] BAEL-1857 Delete StringFunctionTest.java --- .../java/com/baeldung/StringFunctionTest.java | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 testing-modules/parallel-tests-junit/src/test/java/com/baeldung/StringFunctionTest.java diff --git a/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/StringFunctionTest.java b/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/StringFunctionTest.java deleted file mode 100644 index 9adfea8ff0..0000000000 --- a/testing-modules/parallel-tests-junit/src/test/java/com/baeldung/StringFunctionTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class StringFunctionTest { - - @Test - public void test_upperCase() { - assertEquals("TESTCASE", "testCase".toUpperCase()); - } - - @Test - public void test_indexOf() { - assertEquals(1, "testCase".indexOf("e")); - } -} From 2f4a12066236d0b826c3bf1dba05c259f67eee7d Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Sat, 11 Aug 2018 14:10:18 +0530 Subject: [PATCH 19/41] BAEL-1857 --- .../math-test-functions/pom.xml | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 testing-modules/parallel-tests-junit/math-test-functions/pom.xml diff --git a/testing-modules/parallel-tests-junit/math-test-functions/pom.xml b/testing-modules/parallel-tests-junit/math-test-functions/pom.xml new file mode 100644 index 0000000000..18d2b562f3 --- /dev/null +++ b/testing-modules/parallel-tests-junit/math-test-functions/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + + com.baeldung + parallel-tests-junit + 0.0.1-SNAPSHOT + + math-test-functions + math-test-functions + http://maven.apache.org + + UTF-8 + + + + junit + junit + 4.12 + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.0 + + all + 10 + 2 + 2 + 6 + 3.5 + 5 + true + + FunctionTestSuite.class + + + + + + From 876ffa765c258cb9fad6ea9701db5119da82402b Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Sat, 11 Aug 2018 14:13:04 +0530 Subject: [PATCH 20/41] BAEL-1857 --- .../src/test/java/com/baeldung/FunctionTestSuite.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/FunctionTestSuite.java diff --git a/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/FunctionTestSuite.java b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/FunctionTestSuite.java new file mode 100644 index 0000000000..4fe551b365 --- /dev/null +++ b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/FunctionTestSuite.java @@ -0,0 +1,11 @@ +package com.baeldung; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ ComparisonFunctionTest.class, ArithmeticFunctionTest.class }) +public class FunctionTestSuite { + +} From 9379e84ac8bbfa75ff4ccfcea3b44026884e0ae9 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Sat, 11 Aug 2018 14:13:55 +0530 Subject: [PATCH 21/41] BAEL-1857 --- .../com/baeldung/ComparisonFunctionTest.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ComparisonFunctionTest.java diff --git a/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ComparisonFunctionTest.java b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ComparisonFunctionTest.java new file mode 100644 index 0000000000..4f72c87279 --- /dev/null +++ b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ComparisonFunctionTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class ComparisonFunctionTest { + + @Test + public void test_findMax() { + assertEquals(20, Math.max(10, 20)); + } + + @Test + public void test_findMin() { + assertEquals(10, Math.min(10, 20)); + } + +} From 8e507cae4bd3b962cb7367285ccbb398c182fe0f Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Sat, 11 Aug 2018 14:14:41 +0530 Subject: [PATCH 22/41] BAEL-1857 --- .../com/baeldung/ArithmeticFunctionTest.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ArithmeticFunctionTest.java diff --git a/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ArithmeticFunctionTest.java b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ArithmeticFunctionTest.java new file mode 100644 index 0000000000..df0aa695fc --- /dev/null +++ b/testing-modules/parallel-tests-junit/math-test-functions/src/test/java/com/baeldung/ArithmeticFunctionTest.java @@ -0,0 +1,28 @@ +package com.baeldung; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class ArithmeticFunctionTest { + + @Test + public void test_addingIntegers_returnsSum() { + assertEquals(22, Math.addExact(10, 12)); + } + + @Test + public void test_multiplyingIntegers_returnsProduct() { + assertEquals(120, Math.multiplyExact(10, 12)); + } + + @Test + public void test_subtractingIntegers_returnsDifference() { + assertEquals(2, Math.subtractExact(12, 10)); + } + + @Test + public void test_minimumInteger() { + assertEquals(10, Math.min(10, 12)); + } +} From 7ed89c7bc8d2be5165ff38eb324443c5388e2572 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Sat, 11 Aug 2018 14:16:11 +0530 Subject: [PATCH 23/41] BAEL-1857 --- .../parallel-tests-junit/string-test-functions/pom.xml | 1 + 1 file changed, 1 insertion(+) create mode 100644 testing-modules/parallel-tests-junit/string-test-functions/pom.xml diff --git a/testing-modules/parallel-tests-junit/string-test-functions/pom.xml b/testing-modules/parallel-tests-junit/string-test-functions/pom.xml new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/testing-modules/parallel-tests-junit/string-test-functions/pom.xml @@ -0,0 +1 @@ + From ec084c3b651f98abfd221088c807a164c7b71348 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Sat, 11 Aug 2018 14:17:11 +0530 Subject: [PATCH 24/41] BAEL-1857 --- .../string-test-functions/pom.xml | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/testing-modules/parallel-tests-junit/string-test-functions/pom.xml b/testing-modules/parallel-tests-junit/string-test-functions/pom.xml index 8b13789179..af61cfce8e 100644 --- a/testing-modules/parallel-tests-junit/string-test-functions/pom.xml +++ b/testing-modules/parallel-tests-junit/string-test-functions/pom.xml @@ -1 +1,41 @@ + + + 4.0.0 + + com.baeldung + parallel-tests-junit + 0.0.1-SNAPSHOT + + string-test-functions + string-test-functions + http://maven.apache.org + + UTF-8 + + + + junit + junit + 4.12 + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.0 + + all + true + 2 + + + + + From b3579151a91b765ce51bd720c01c5ea2ec54b9b0 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Sat, 11 Aug 2018 14:18:30 +0530 Subject: [PATCH 25/41] BAEL-1857 --- .../java/com/baeldung/StringFunctionTest.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 testing-modules/parallel-tests-junit/string-test-functions/src/test/java/com/baeldung/StringFunctionTest.java diff --git a/testing-modules/parallel-tests-junit/string-test-functions/src/test/java/com/baeldung/StringFunctionTest.java b/testing-modules/parallel-tests-junit/string-test-functions/src/test/java/com/baeldung/StringFunctionTest.java new file mode 100644 index 0000000000..7f2bc5e5e7 --- /dev/null +++ b/testing-modules/parallel-tests-junit/string-test-functions/src/test/java/com/baeldung/StringFunctionTest.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class StringFunctionTest { + + @Test + public void test_upperCase() { + assertEquals("TESTCASE", "testCase".toUpperCase()); + } + + @Test + public void test_indexOf() { + assertEquals(1, "testCase".indexOf("e")); + } +} From 43bfb9722ff5ef948fd60609e2b97c19385f894a Mon Sep 17 00:00:00 2001 From: RanjeetKaur17 Date: Sun, 12 Aug 2018 00:07:20 +0400 Subject: [PATCH 26/41] Moving File Parser Samples to core-java-io --- .../main/java/com/baeldung/fileparser/BufferedReaderExample.java | 0 .../src/main/java/com/baeldung/fileparser/FileReaderExample.java | 0 .../main/java/com/baeldung/fileparser/FilesReadLinesExample.java | 0 .../src/main/java/com/baeldung/fileparser/ScannerIntExample.java | 0 .../main/java/com/baeldung/fileparser/ScannerStringExample.java | 0 .../test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java | 0 .../src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java | 0 .../java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java | 0 .../src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java | 0 .../test/java/com/baeldung/fileparser/ScannerStringUnitTest.java | 0 .../src/test/resources/sampleNumberFile.txt | 0 {core-java => core-java-io}/src/test/resources/sampleTextFile.txt | 0 12 files changed, 0 insertions(+), 0 deletions(-) rename {core-java => core-java-io}/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java (100%) rename {core-java => core-java-io}/src/main/java/com/baeldung/fileparser/FileReaderExample.java (100%) rename {core-java => core-java-io}/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java (100%) rename {core-java => core-java-io}/src/main/java/com/baeldung/fileparser/ScannerIntExample.java (100%) rename {core-java => core-java-io}/src/main/java/com/baeldung/fileparser/ScannerStringExample.java (100%) rename {core-java => core-java-io}/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java (100%) rename {core-java => core-java-io}/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java (100%) rename {core-java => core-java-io}/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java (100%) rename {core-java => core-java-io}/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java (100%) rename {core-java => core-java-io}/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java (100%) rename {core-java => core-java-io}/src/test/resources/sampleNumberFile.txt (100%) rename {core-java => core-java-io}/src/test/resources/sampleTextFile.txt (100%) diff --git a/core-java/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java rename to core-java-io/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java diff --git a/core-java/src/main/java/com/baeldung/fileparser/FileReaderExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/FileReaderExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/fileparser/FileReaderExample.java rename to core-java-io/src/main/java/com/baeldung/fileparser/FileReaderExample.java diff --git a/core-java/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java rename to core-java-io/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java diff --git a/core-java/src/main/java/com/baeldung/fileparser/ScannerIntExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerIntExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/fileparser/ScannerIntExample.java rename to core-java-io/src/main/java/com/baeldung/fileparser/ScannerIntExample.java diff --git a/core-java/src/main/java/com/baeldung/fileparser/ScannerStringExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerStringExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/fileparser/ScannerStringExample.java rename to core-java-io/src/main/java/com/baeldung/fileparser/ScannerStringExample.java diff --git a/core-java/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java rename to core-java-io/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java rename to core-java-io/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java rename to core-java-io/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java rename to core-java-io/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java rename to core-java-io/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java diff --git a/core-java/src/test/resources/sampleNumberFile.txt b/core-java-io/src/test/resources/sampleNumberFile.txt similarity index 100% rename from core-java/src/test/resources/sampleNumberFile.txt rename to core-java-io/src/test/resources/sampleNumberFile.txt diff --git a/core-java/src/test/resources/sampleTextFile.txt b/core-java-io/src/test/resources/sampleTextFile.txt similarity index 100% rename from core-java/src/test/resources/sampleTextFile.txt rename to core-java-io/src/test/resources/sampleTextFile.txt From 15c728736dcac355918360a1369ca082d6bf3d9d Mon Sep 17 00:00:00 2001 From: Marcos Lopez Gonzalez Date: Sat, 11 Aug 2018 22:13:43 +0200 Subject: [PATCH 27/41] builder helper maven plugin --- maven/pom.xml | 19 +++++++++++++++++++ .../com/baeldung/maven/plugins/Foo.java | 10 ++++++++++ .../maven/plugins/MultipleSrcFolders.java | 9 +++++++++ 3 files changed, 38 insertions(+) create mode 100644 maven/src/main/another-src/com/baeldung/maven/plugins/Foo.java create mode 100644 maven/src/main/java/com/baeldung/maven/plugins/MultipleSrcFolders.java diff --git a/maven/pom.xml b/maven/pom.xml index a409432f8b..4f91e8717c 100644 --- a/maven/pom.xml +++ b/maven/pom.xml @@ -94,6 +94,24 @@ + + org.codehaus.mojo + build-helper-maven-plugin + ${maven.build.helper.version} + + + generate-sources + + add-source + + + + src/main/another-src + + + + +
@@ -102,6 +120,7 @@ 2.21.0 1.1 3.0.0 + 3.0.0 Baeldung diff --git a/maven/src/main/another-src/com/baeldung/maven/plugins/Foo.java b/maven/src/main/another-src/com/baeldung/maven/plugins/Foo.java new file mode 100644 index 0000000000..f8a6fe9853 --- /dev/null +++ b/maven/src/main/another-src/com/baeldung/maven/plugins/Foo.java @@ -0,0 +1,10 @@ +package com.baeldung.maven.plugins; + +public class Foo { + + public static String foo() { + return "foo"; + } + +} + diff --git a/maven/src/main/java/com/baeldung/maven/plugins/MultipleSrcFolders.java b/maven/src/main/java/com/baeldung/maven/plugins/MultipleSrcFolders.java new file mode 100644 index 0000000000..d403918dd3 --- /dev/null +++ b/maven/src/main/java/com/baeldung/maven/plugins/MultipleSrcFolders.java @@ -0,0 +1,9 @@ +package com.baeldung.maven.plugins; + +public class MultipleSrcFolders { + + public static void callFoo() { + Foo.foo(); + } + +} From 99676b1a9ee000ce41b7de864a924290761414ec Mon Sep 17 00:00:00 2001 From: yuugen Date: Sun, 12 Aug 2018 04:32:05 +0530 Subject: [PATCH 28/41] Bael 2019 static vs dynamic binding (#4807) * adding the required classes for binding example * completed test class for AnimalActivityUnitTest static functions * changes to example so that they don't seem to be a replica of https://stackoverflow.com/questions/19017258/static-vs-dynamic-binding-in-java * refactoring and removing unnecessary file * revert changes to RegexUnitTest --- .../java/com/baeldung/binding/Animal.java | 23 +++++ .../com/baeldung/binding/AnimalActivity.java | 43 +++++++++ .../main/java/com/baeldung/binding/Cat.java | 18 ++++ .../binding/AnimalActivityUnitTest.java | 95 +++++++++++++++++++ .../com/baeldung/binding/AnimalUnitTest.java | 86 +++++++++++++++++ .../com/baeldung/binding/CatUnitTest.java | 62 ++++++++++++ 6 files changed, 327 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/binding/Animal.java create mode 100644 core-java/src/main/java/com/baeldung/binding/AnimalActivity.java create mode 100644 core-java/src/main/java/com/baeldung/binding/Cat.java create mode 100644 core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/binding/CatUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/binding/Animal.java b/core-java/src/main/java/com/baeldung/binding/Animal.java new file mode 100644 index 0000000000..12eaa2a7a3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/binding/Animal.java @@ -0,0 +1,23 @@ +package com.baeldung.binding; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by madhumita.g on 25-07-2018. + */ +public class Animal { + + final static Logger logger = LoggerFactory.getLogger(Animal.class); + + public void makeNoise() { + logger.info("generic animal noise"); + } + + public void makeNoise(Integer repetitions) { + while(repetitions != 0) { + logger.info("generic animal noise countdown " + repetitions); + repetitions -= 1; + } + } +} diff --git a/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java b/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java new file mode 100644 index 0000000000..1bd36123e3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java @@ -0,0 +1,43 @@ +package com.baeldung.binding; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by madhumita.g on 25-07-2018. + */ +public class AnimalActivity { + + final static Logger logger = LoggerFactory.getLogger(AnimalActivity.class); + + + public static void sleep(Animal animal) { + logger.info("Animal is sleeping"); + } + + public static void sleep(Cat cat) { + logger.info("Cat is sleeping"); + } + + public static void main(String[] args) { + + Animal animal = new Animal(); + + //calling methods of animal object + animal.makeNoise(); + + animal.makeNoise(3); + + + //assigning a dog object to reference of type Animal + Animal catAnimal = new Cat(); + + catAnimal.makeNoise(); + + // calling static function + AnimalActivity.sleep(catAnimal); + + return; + + } +} diff --git a/core-java/src/main/java/com/baeldung/binding/Cat.java b/core-java/src/main/java/com/baeldung/binding/Cat.java new file mode 100644 index 0000000000..bbe740e412 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/binding/Cat.java @@ -0,0 +1,18 @@ +package com.baeldung.binding; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by madhumita.g on 25-07-2018. + */ +public class Cat extends Animal { + + final static Logger logger = LoggerFactory.getLogger(Cat.class); + + public void makeNoise() { + + logger.info("meow"); + } + +} diff --git a/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java b/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java new file mode 100644 index 0000000000..41c67ff389 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java @@ -0,0 +1,95 @@ +package com.baeldung.binding; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.verify; + +/** + *https://gist.github.com/bloodredsun/a041de13e57bf3c6c040 + */ +@RunWith(MockitoJUnitRunner.class) + +public class AnimalActivityUnitTest { + + @Mock + private Appender mockAppender; + @Captor + private ArgumentCaptor captorLoggingEvent; + + @Before + public void setup() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.addAppender(mockAppender); + } + + @After + public void teardown() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.detachAppender(mockAppender); + } + + @Test + public void givenAnimalReference__whenRefersAnimalObject_shouldCallFunctionWithAnimalParam() { + + Animal animal = new Animal(); + + AnimalActivity.sleep(animal); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("Animal is sleeping")); + } + + @Test + public void givenDogReference__whenRefersCatObject_shouldCallFunctionWithAnimalParam() { + + Cat cat = new Cat(); + + AnimalActivity.sleep(cat); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("Cat is sleeping")); + } + + @Test + public void givenAnimaReference__whenRefersDogObject_shouldCallFunctionWithAnimalParam() { + + Animal cat = new Cat(); + + AnimalActivity.sleep(cat); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("Animal is sleeping")); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java new file mode 100644 index 0000000000..238990f2b4 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java @@ -0,0 +1,86 @@ +package com.baeldung.binding; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.verify; + +/** + * Created by madhumita.g on 01-08-2018. + */ + +@RunWith(MockitoJUnitRunner.class) +public class AnimalUnitTest { + @Mock + private Appender mockAppender; + @Captor + private ArgumentCaptor captorLoggingEvent; + + @Before + public void setup() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.addAppender(mockAppender); + } + + @After + public void teardown() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.detachAppender(mockAppender); + } + + @Test + public void whenCalledWithoutParameters_shouldCallFunctionMakeNoiseWithoutParameters() { + + Animal animal = new Animal(); + + animal.makeNoise(); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("generic animal noise")); + } + + @Test + public void whenCalledWithParameters_shouldCallFunctionMakeNoiseWithParameters() { + + Animal animal = new Animal(); + + int testValue = 3; + animal.makeNoise(testValue); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + while (testValue != 0) { + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("generic animal noise countdown 3\n" + + "generic animal noise countdown 2\n" + + "generic animal noise countdown 1\n")); + + testValue-=1; + + } + } + +} diff --git a/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java b/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java new file mode 100644 index 0000000000..76ccfb7719 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.binding; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.verify; + +/** + * Created by madhumita.g on 01-08-2018. + */ +@RunWith(MockitoJUnitRunner.class) +public class CatUnitTest { + + @Mock + private Appender mockAppender; + + @Captor + private ArgumentCaptor captorLoggingEvent; + + @Before + public void setup() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.addAppender(mockAppender); + } + + @After + public void teardown() { + final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + logger.detachAppender(mockAppender); + } + + @Test + public void makeNoiseTest() { + + Cat cat = new Cat(); + + cat.makeNoise(); + + verify(mockAppender).doAppend(captorLoggingEvent.capture()); + + final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + + assertThat(loggingEvent.getLevel(), is(Level.INFO)); + + assertThat(loggingEvent.getFormattedMessage(), + is("meow")); + + } +} From 534d5749ccaff172e5890627f4329f480031cc72 Mon Sep 17 00:00:00 2001 From: Dhrubajyoti Bhattacharjee Date: Sun, 12 Aug 2018 10:49:43 +0530 Subject: [PATCH 29/41] BAEL-1983 Initialize hashmap (#4949) * BAEL-1983 Initialize hashmap * BAEL-1983 Initialize hashmap --- .../guava/GuavaMapInitializeUnitTest.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java b/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java new file mode 100644 index 0000000000..69a7505316 --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java @@ -0,0 +1,30 @@ +package org.baeldung.guava; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.*; + +import java.util.Map; +import org.junit.Test; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; + +public class GuavaMapInitializeUnitTest { + + @Test + public void givenKeyValuesShoudInitializeMap() { + Map articles = ImmutableMap.of("Title", "My New Article", "Title2", "Second Article"); + + assertThat(articles.get("Title"), equalTo("My New Article")); + assertThat(articles.get("Title2"), equalTo("Second Article")); + + } + + + @Test + public void givenKeyValuesShouldCreateMutableMap() { + Map articles = Maps.newHashMap(ImmutableMap.of("Title", "My New Article", "Title2", "Second Article")); + + assertThat(articles.get("Title"), equalTo("My New Article")); + assertThat(articles.get("Title2"), equalTo("Second Article")); + } +} From 8bcc305853240caa87ea7c9a8fe5ba9f931d48f9 Mon Sep 17 00:00:00 2001 From: Mher Baghinyan Date: Mon, 13 Aug 2018 17:12:48 +0400 Subject: [PATCH 30/41] Update CollectionsBenchmark.java --- .../com/baeldung/performance/CollectionsBenchmark.java | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java index 6d36789c2b..921e1608ea 100644 --- a/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java +++ b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java @@ -11,6 +11,9 @@ import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 5) public class CollectionsBenchmark { @State(Scope.Thread) @@ -35,19 +38,12 @@ public class CollectionsBenchmark { } } - @Benchmark - @BenchmarkMode(Mode.AverageTime) - @OutputTimeUnit(TimeUnit.NANOSECONDS) - @Warmup(iterations = 1) public boolean testArrayList(MyState state) { return state.employeeList.contains(state.employee); } @Benchmark - @BenchmarkMode(Mode.AverageTime) - @OutputTimeUnit(TimeUnit.NANOSECONDS) - @Warmup(iterations = 1) public boolean testHashSet(MyState state) { return state.employeeSet.contains(state.employee); } From 5eea4fc6a6cc4ace02389e8267c469323eba4246 Mon Sep 17 00:00:00 2001 From: cmlavila Date: Mon, 13 Aug 2018 20:02:06 -0300 Subject: [PATCH 31/41] BAEL-2037 - Code for mini-article (#4923) * BAEL-2037 - Code for mini-article * BAEL-2037 - Fixes after editors review * Fixing dependencies * Change File Reader * Formatting * Fix imports * Rename test class --- json/pom.xml | 14 +++ .../baeldung/jsonpointer/JsonPointerCrud.java | 95 +++++++++++++++++++ .../jsonpointer/JsonPointerCrudUnitTest.java | 59 ++++++++++++ json/src/test/resources/address.json | 4 + json/src/test/resources/books.json | 7 ++ 5 files changed, 179 insertions(+) create mode 100644 json/src/main/java/com/baeldung/jsonpointer/JsonPointerCrud.java create mode 100644 json/src/test/java/com/baeldung/jsonpointer/JsonPointerCrudUnitTest.java create mode 100644 json/src/test/resources/address.json create mode 100644 json/src/test/resources/books.json diff --git a/json/pom.xml b/json/pom.xml index c55e833b40..fa3fcafa65 100644 --- a/json/pom.xml +++ b/json/pom.xml @@ -33,6 +33,20 @@ json 20171018
+ + + junit + junit + 4.12 + test + + + + org.glassfish + javax.json + 1.1.2 + + diff --git a/json/src/main/java/com/baeldung/jsonpointer/JsonPointerCrud.java b/json/src/main/java/com/baeldung/jsonpointer/JsonPointerCrud.java new file mode 100644 index 0000000000..4398aa7867 --- /dev/null +++ b/json/src/main/java/com/baeldung/jsonpointer/JsonPointerCrud.java @@ -0,0 +1,95 @@ +package com.baeldung.jsonpointer; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Paths; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonPointer; +import javax.json.JsonReader; +import javax.json.JsonString; +import javax.json.JsonStructure; + +public class JsonPointerCrud { + + private JsonStructure jsonStructure = null; + + public JsonPointerCrud(String fileName) throws IOException { + + try (JsonReader reader = Json.createReader(Files.newBufferedReader(Paths.get(fileName)))) { + jsonStructure = reader.read(); + } catch (FileNotFoundException e) { + System.out.println("Error to open json file: " + e.getMessage()); + } + + } + + public JsonPointerCrud(InputStream stream) { + + JsonReader reader = Json.createReader(stream); + jsonStructure = reader.read(); + reader.close(); + + } + + public JsonStructure insert(String key, String value) { + + JsonPointer jsonPointer = Json.createPointer("/" + key); + JsonString jsonValue = Json.createValue(value); + jsonStructure = jsonPointer.add(jsonStructure, jsonValue); + + return jsonStructure; + + } + + public JsonStructure update(String key, String newValue) { + + JsonPointer jsonPointer = Json.createPointer("/" + key); + JsonString jsonNewValue = Json.createValue(newValue); + jsonStructure = jsonPointer.replace(jsonStructure, jsonNewValue); + + return jsonStructure; + } + + public JsonStructure delete(String key) { + + JsonPointer jsonPointer = Json.createPointer("/" + key); + jsonPointer.getValue(jsonStructure); + jsonStructure = jsonPointer.remove(jsonStructure); + + return jsonStructure; + + } + + public String fetchValueFromKey(String key) { + JsonPointer jsonPointer = Json.createPointer("/" + key); + JsonString jsonString = (JsonString) jsonPointer.getValue(jsonStructure); + + return jsonString.getString(); + } + + public String fetchListValues(String key) { + JsonPointer jsonPointer = Json.createPointer("/" + key); + JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure); + + return jsonObject.toString(); + } + + public String fetchFullJSON() { + JsonPointer jsonPointer = Json.createPointer(""); + JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure); + + return jsonObject.toString(); + + } + + public boolean check(String key) { + JsonPointer jsonPointer = Json.createPointer("/" + key); + boolean found = jsonPointer.containsValue(jsonStructure); + + return found; + } +} diff --git a/json/src/test/java/com/baeldung/jsonpointer/JsonPointerCrudUnitTest.java b/json/src/test/java/com/baeldung/jsonpointer/JsonPointerCrudUnitTest.java new file mode 100644 index 0000000000..c1553db325 --- /dev/null +++ b/json/src/test/java/com/baeldung/jsonpointer/JsonPointerCrudUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.jsonpointer; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class JsonPointerCrudUnitTest { + + @Test + public void testJsonPointerCrudForAddress() { + + JsonPointerCrud jsonPointerCrud = new JsonPointerCrud(JsonPointerCrudUnitTest.class.getResourceAsStream("/address.json")); + + assertFalse(jsonPointerCrud.check("city")); + + // insert a value + jsonPointerCrud.insert("city", "Rio de Janeiro"); + + assertTrue(jsonPointerCrud.check("city")); + + // fetch full json + String fullJSON = jsonPointerCrud.fetchFullJSON(); + + assertTrue(fullJSON.contains("name")); + + assertTrue(fullJSON.contains("city")); + + // fetch value + String cityName = jsonPointerCrud.fetchValueFromKey("city"); + + assertEquals(cityName, "Rio de Janeiro"); + + // update value + jsonPointerCrud.update("city", "Sao Paulo"); + + // fetch value + cityName = jsonPointerCrud.fetchValueFromKey("city"); + + assertEquals(cityName, "Sao Paulo"); + + // delete + jsonPointerCrud.delete("city"); + + assertFalse(jsonPointerCrud.check("city")); + + } + + @Test + public void testJsonPointerCrudForBooks() { + + JsonPointerCrud jsonPointerCrud = new JsonPointerCrud(JsonPointerCrudUnitTest.class.getResourceAsStream("/books.json")); + + // fetch value + String book = jsonPointerCrud.fetchListValues("books/1"); + + assertEquals(book, "{\"title\":\"Title 2\",\"author\":\"John Doe\"}"); + + } +} \ No newline at end of file diff --git a/json/src/test/resources/address.json b/json/src/test/resources/address.json new file mode 100644 index 0000000000..599fcae12b --- /dev/null +++ b/json/src/test/resources/address.json @@ -0,0 +1,4 @@ +{ + "name": "Customer 01", + "street name": "Street 01" +} \ No newline at end of file diff --git a/json/src/test/resources/books.json b/json/src/test/resources/books.json new file mode 100644 index 0000000000..0defc3de98 --- /dev/null +++ b/json/src/test/resources/books.json @@ -0,0 +1,7 @@ +{ + "library": "My Personal Library", + "books": [ + { "title":"Title 1", "author":"Jane Doe" }, + { "title":"Title 2", "author":"John Doe" } + ] +} \ No newline at end of file From 74e3e7ff95078b5e8ed6bac245faf55424b45799 Mon Sep 17 00:00:00 2001 From: Juan Moreno Date: Mon, 13 Aug 2018 20:33:36 -0300 Subject: [PATCH 32/41] Kotlin Nested and Inner Classes Code SampleCode Issue: BAEL-1759 --- core-kotlin/pom.xml | 48 ++++++------ .../kotlin/com/baeldung/nested/Computer.kt | 75 +++++++++++++++++++ .../com/baeldung/nested/ComputerUnitTest.kt | 28 +++++++ 3 files changed, 127 insertions(+), 24 deletions(-) create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index afa7d8a963..a86359c02f 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -106,22 +106,22 @@ klaxon ${klaxon.version} - - io.ktor - ktor-server-netty - ${ktor.io.version} - - - io.ktor - ktor-gson - ${ktor.io.version} - - - ch.qos.logback - logback-classic - 1.2.1 - test - + + io.ktor + ktor-server-netty + ${ktor.io.version} + + + io.ktor + ktor-gson + ${ktor.io.version} + + + ch.qos.logback + logback-classic + 1.2.1 + test + @@ -166,13 +166,13 @@ ${java.version} - default-compile none - default-testCompile @@ -224,10 +224,10 @@ UTF-8 - 1.2.51 - 1.2.51 - 1.2.51 - 1.2.51 + 1.2.60 + 1.2.60 + 1.2.60 + 1.2.60 0.22.5 0.9.2 1.5.0 @@ -235,9 +235,9 @@ 3.0.4 0.1.0 3.6.1 - 1.0.0 + 1.1.1 5.2.0 3.10.0 - + \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt b/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt new file mode 100644 index 0000000000..ee01c06646 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt @@ -0,0 +1,75 @@ +package com.baeldung.nested + +import org.slf4j.Logger +import org.slf4j.LoggerFactory + +class Computer(val model: String) { + + companion object { + const val originCountry = "China" + fun getBuiltDate(): String { + return "2018-05-23" + } + + val log: Logger = LoggerFactory.getLogger(Computer::class.java) + } + + //Nested class + class MotherBoard(val manufacturer: String) { + fun getInfo() = "Made by $manufacturer installed in $originCountry - ${getBuiltDate()}" + } + + //Inner class + inner class HardDisk(val sizeInGb: Int) { + fun getInfo() = "Installed on ${this@Computer} with $sizeInGb GB" + } + + interface Switcher { + fun on(): String + } + + interface Protector { + fun smart() + } + + fun powerOn(): String { + //Local class + var defaultColor = "Blue" + + class Led(val color: String) { + fun blink(): String { + return "blinking $color" + } + + fun changeDefaultPowerOnColor() { + defaultColor = "Violet" + } + } + + val powerLed = Led("Green") + log.debug("defaultColor is $defaultColor") + powerLed.changeDefaultPowerOnColor() + log.debug("defaultColor changed inside Led class to $defaultColor") + //Anonymous object + val powerSwitch = object : Switcher, Protector { + override fun on(): String { + return powerLed.blink() + } + + override fun smart() { + log.debug("Smart protection is implemented") + } + + fun changeDefaultPowerOnColor() { + defaultColor = "Yellow" + } + } + powerSwitch.changeDefaultPowerOnColor() + log.debug("defaultColor changed inside powerSwitch anonymous object to $defaultColor") + return powerSwitch.on() + } + + override fun toString(): String { + return "Computer(model=$model)" + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt new file mode 100644 index 0000000000..7882d85b3c --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt @@ -0,0 +1,28 @@ +package com.baeldung.nested + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class ComputerUnitTest { + + @Test + fun givenComputer_whenPowerOn_thenBlink() { + val computer = Computer("Desktop") + + assertThat(computer.powerOn()).isEqualTo("blinking Green") + } + + @Test + fun givenMotherboard_whenGetInfo_thenGetInstalledAndBuiltDetails() { + val motherBoard = Computer.MotherBoard("MotherBoard Inc.") + + assertThat(motherBoard.getInfo()).isEqualTo("Made by MotherBoard Inc. installed in China - 2018-05-23") + } + + @Test + fun givenHardDisk_whenGetInfo_thenGetComputerModelAndDiskSizeInGb() { + val hardDisk = Computer("Desktop").HardDisk(1000) + + assertThat(hardDisk.getInfo()).isEqualTo("Installed on Computer(model=Desktop) with 1000 GB") + } +} \ No newline at end of file From 924a3dc9cc73927d2965e1b55fac4dc02f2cbfa0 Mon Sep 17 00:00:00 2001 From: daoire Date: Tue, 14 Aug 2018 07:25:11 +0100 Subject: [PATCH 33/41] Java Faker Tests (#4922) * Java Faker Tests * Rename tests * Rename Test Class * Remove files from sub module --- testing-modules/java-faker/pom.xml | 29 ----- .../test/java/com/baeldung/JavaFakerTest.java | 115 ----------------- testing-modules/testing/pom.xml | 5 + .../baeldung/javafaker/JavaFakerUnitTest.java | 121 ++++++++++++++++++ 4 files changed, 126 insertions(+), 144 deletions(-) delete mode 100644 testing-modules/java-faker/pom.xml delete mode 100644 testing-modules/java-faker/src/test/java/com/baeldung/JavaFakerTest.java create mode 100644 testing-modules/testing/src/test/java/com/baeldung/javafaker/JavaFakerUnitTest.java diff --git a/testing-modules/java-faker/pom.xml b/testing-modules/java-faker/pom.xml deleted file mode 100644 index 4ac5368e24..0000000000 --- a/testing-modules/java-faker/pom.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - 4.0.0 - - com.baeldung - java-faker - 1.0-SNAPSHOT - - - - com.github.javafaker - javafaker - 0.15 - - - - - junit - junit - 4.12 - test - - - - - - diff --git a/testing-modules/java-faker/src/test/java/com/baeldung/JavaFakerTest.java b/testing-modules/java-faker/src/test/java/com/baeldung/JavaFakerTest.java deleted file mode 100644 index 8d89fa0ab2..0000000000 --- a/testing-modules/java-faker/src/test/java/com/baeldung/JavaFakerTest.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.baeldung; - -import com.github.javafaker.Faker; -import com.github.javafaker.service.FakeValuesService; -import com.github.javafaker.service.FakerIDN; -import com.github.javafaker.service.LocaleDoesNotExistException; -import com.github.javafaker.service.RandomService; -import javafx.scene.Parent; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import java.util.Locale; -import java.util.Random; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -public class JavaFakerTest { - - private Faker faker; - - @Before - public void setUp() throws Exception { - faker = new Faker(); - } - - @Test - public void givenJavaFaker_whenAddressObjectCalled_checkValidAddressInfoGiven() throws Exception { - - Faker faker = new Faker(); - - String streetName = faker.address().streetName(); - String number = faker.address().buildingNumber(); - String city = faker.address().city(); - String country = faker.address().country(); - - System.out.println(String.format("%s\n%s\n%s\n%s", - number, - streetName, - city, - country)); - - } - - @Test - public void givenJavaFakersWithSameSeed_whenNameCalled_CheckSameName() throws Exception { - - Faker faker1 = new Faker(new Random(24)); - Faker faker2 = new Faker(new Random(24)); - - assertEquals(faker1.name().firstName(), faker2.name().firstName()); - } - - @Test - public void givenJavaFakersWithDifferentLocals_checkZipCodesMatchRegex() throws Exception { - - Faker ukFaker = new Faker(new Locale("en-GB")); - Faker usFaker = new Faker(new Locale("en-US")); - - System.out.println(String.format("American zipcode: %s", usFaker.address().zipCode())); - System.out.println(String.format("British postcode: %s", ukFaker.address().zipCode())); - - Pattern ukPattern = Pattern.compile("([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\\s?[0-9][A-Za-z]{2})"); - Matcher ukMatcher = ukPattern.matcher(ukFaker.address().zipCode()); - - assertTrue(ukMatcher.find()); - - Matcher usMatcher = Pattern.compile("^\\d{5}(?:[-\\s]\\d{4})?$").matcher(usFaker.address().zipCode()); - - assertTrue(usMatcher.find()); - - } - - @Test - public void givenJavaFakerService_testFakersCreated() throws Exception { - - RandomService randomService = new RandomService(); - - System.out.println(randomService.nextBoolean()); - System.out.println(randomService.nextDouble()); - - Faker faker = new Faker(new Random(randomService.nextLong())); - - System.out.println(faker.address().city()); - - } - - @Test - public void testFakeValuesService() throws Exception { - - FakeValuesService fakeValuesService = new FakeValuesService(new Locale("en-GB"), new RandomService()); - - String email = fakeValuesService.bothify("????##@gmail.com"); - Matcher emailMatcher = Pattern.compile("\\w{4}\\d{2}@gmail.com").matcher(email); - assertTrue(emailMatcher.find()); - - String alphaNumericString = fakeValuesService.regexify("[a-z1-9]{10}"); - Matcher alphaNumericMatcher = Pattern.compile("[a-z1-9]{10}").matcher(alphaNumericString); - assertTrue(alphaNumericMatcher.find()); - - } - - - @Test(expected = LocaleDoesNotExistException.class) - public void givenWrongLocale_whenFakerIsInitialised_testLocaleDoesNotExistExceptionIsThrown() throws Exception { - - Faker wrongLocaleFaker = new Faker(new Locale("en-seaWorld")); - - } -} diff --git a/testing-modules/testing/pom.xml b/testing-modules/testing/pom.xml index 7b2fe76d0f..2e783b2116 100644 --- a/testing-modules/testing/pom.xml +++ b/testing-modules/testing/pom.xml @@ -88,6 +88,11 @@ javalite-common ${javalite.version} + + com.github.javafaker + javafaker + 0.15 + diff --git a/testing-modules/testing/src/test/java/com/baeldung/javafaker/JavaFakerUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/javafaker/JavaFakerUnitTest.java new file mode 100644 index 0000000000..7a3b9771fb --- /dev/null +++ b/testing-modules/testing/src/test/java/com/baeldung/javafaker/JavaFakerUnitTest.java @@ -0,0 +1,121 @@ +package com.baeldung.javafaker; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Locale; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Before; +import org.junit.Test; + +import com.github.javafaker.Faker; +import com.github.javafaker.service.FakeValuesService; +import com.github.javafaker.service.LocaleDoesNotExistException; +import com.github.javafaker.service.RandomService; + +public class JavaFakerUnitTest { + + private Faker faker; + + @Before + public void setUp() throws Exception { + faker = new Faker(); + } + + @Test + public void givenJavaFaker_whenAddressObjectCalled_checkValidAddressInfoGiven() throws Exception { + + Faker faker = new Faker(); + + String streetName = faker.address() + .streetName(); + String number = faker.address() + .buildingNumber(); + String city = faker.address() + .city(); + String country = faker.address() + .country(); + + System.out.println(String.format("%s\n%s\n%s\n%s", number, streetName, city, country)); + + } + + @Test + public void givenJavaFakersWithSameSeed_whenNameCalled_CheckSameName() throws Exception { + + Faker faker1 = new Faker(new Random(24)); + Faker faker2 = new Faker(new Random(24)); + + assertEquals(faker1.name() + .firstName(), + faker2.name() + .firstName()); + } + + @Test + public void givenJavaFakersWithDifferentLocals_checkZipCodesMatchRegex() throws Exception { + + Faker ukFaker = new Faker(new Locale("en-GB")); + Faker usFaker = new Faker(new Locale("en-US")); + + System.out.println(String.format("American zipcode: %s", usFaker.address() + .zipCode())); + System.out.println(String.format("British postcode: %s", ukFaker.address() + .zipCode())); + + Pattern ukPattern = Pattern.compile("([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\\s?[0-9][A-Za-z]{2})"); + Matcher ukMatcher = ukPattern.matcher(ukFaker.address() + .zipCode()); + + assertTrue(ukMatcher.find()); + + Matcher usMatcher = Pattern.compile("^\\d{5}(?:[-\\s]\\d{4})?$") + .matcher(usFaker.address() + .zipCode()); + + assertTrue(usMatcher.find()); + + } + + @Test + public void givenJavaFakerService_testFakersCreated() throws Exception { + + RandomService randomService = new RandomService(); + + System.out.println(randomService.nextBoolean()); + System.out.println(randomService.nextDouble()); + + Faker faker = new Faker(new Random(randomService.nextLong())); + + System.out.println(faker.address() + .city()); + + } + + @Test + public void testFakeValuesService() throws Exception { + + FakeValuesService fakeValuesService = new FakeValuesService(new Locale("en-GB"), new RandomService()); + + String email = fakeValuesService.bothify("????##@gmail.com"); + Matcher emailMatcher = Pattern.compile("\\w{4}\\d{2}@gmail.com") + .matcher(email); + assertTrue(emailMatcher.find()); + + String alphaNumericString = fakeValuesService.regexify("[a-z1-9]{10}"); + Matcher alphaNumericMatcher = Pattern.compile("[a-z1-9]{10}") + .matcher(alphaNumericString); + assertTrue(alphaNumericMatcher.find()); + + } + + @Test(expected = LocaleDoesNotExistException.class) + public void givenWrongLocale_whenFakerIsInitialised_testLocaleDoesNotExistExceptionIsThrown() throws Exception { + + Faker wrongLocaleFaker = new Faker(new Locale("en-seaWorld")); + + } +} \ No newline at end of file From 0b9bb44781f1e79f67646a6e49595459655ef271 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Dupire?= Date: Tue, 14 Aug 2018 08:26:57 +0200 Subject: [PATCH 34/41] [BAEL-2020] Differences between final, finally and finalize in Java (#4848) * [BAEL-2020] Examples code * [BAEL-2020] Moving classes into 'keywords' package --- .../keywords/finalize/FinalizeObject.java | 18 ++++++++++++ .../baeldung/keywords/finalkeyword/Child.java | 15 ++++++++++ .../keywords/finalkeyword/GrandChild.java | 5 ++++ .../keywords/finalkeyword/Parent.java | 23 +++++++++++++++ .../finallykeyword/FinallyExample.java | 29 +++++++++++++++++++ 5 files changed, 90 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java create mode 100644 core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java create mode 100644 core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java create mode 100644 core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java create mode 100644 core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java diff --git a/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java b/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java new file mode 100644 index 0000000000..af0449c0da --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java @@ -0,0 +1,18 @@ +package com.baeldung.keywords.finalize; + +public class FinalizeObject { + + @Override + protected void finalize() throws Throwable { + System.out.println("Execute finalize method"); + super.finalize(); + } + + public static void main(String[] args) throws Exception { + FinalizeObject object = new FinalizeObject(); + object = null; + System.gc(); + Thread.sleep(1000); + } + +} diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java new file mode 100644 index 0000000000..8615c78652 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java @@ -0,0 +1,15 @@ +package com.baeldung.keywords.finalkeyword; + +public final class Child extends Parent { + + @Override + void method1(int arg1, final int arg2) { + // OK + } + +/* @Override + void method2() { + // Compilation error + }*/ + +} diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java new file mode 100644 index 0000000000..1530c5037f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java @@ -0,0 +1,5 @@ +package com.baeldung.keywords.finalkeyword; + +/*public class GrandChild extends Child { + // Compilation error +}*/ diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java new file mode 100644 index 0000000000..5cd2996e7a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java @@ -0,0 +1,23 @@ +package com.baeldung.keywords.finalkeyword; + +public class Parent { + + int field1 = 1; + final int field2 = 2; + + Parent() { + field1 = 2; // OK +// field2 = 3; // Compilation error + } + + void method1(int arg1, final int arg2) { + arg1 = 2; // OK +// arg2 = 3; // Compilation error + } + + final void method2() { + final int localVar = 2; // OK +// localVar = 3; // Compilation error + } + +} diff --git a/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java b/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java new file mode 100644 index 0000000000..3c0aee3196 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java @@ -0,0 +1,29 @@ +package com.baeldung.keywords.finallykeyword; + +public class FinallyExample { + + public static void main(String args[]) throws Exception { + try { + System.out.println("Execute try block"); + throw new Exception(); + } catch (Exception e) { + System.out.println("Execute catch block"); + } finally { + System.out.println("Execute finally block"); + } + + try { + System.out.println("Execute try block"); + } finally { + System.out.println("Execute finally block"); + } + + try { + System.out.println("Execute try block"); + throw new Exception(); + } finally { + System.out.println("Execute finally block"); + } + } + +} From ce8d193f47a2c1f3e664898cc1b41eadb653e969 Mon Sep 17 00:00:00 2001 From: Vizsoro Date: Tue, 14 Aug 2018 09:43:43 +0200 Subject: [PATCH 35/41] simplifying exception test (#4962) * simplifying exception test * simplifying subclass initialization --- .../ListInitializationUnitTest.java | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java b/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java index bc012dae6b..b484eecef7 100644 --- a/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java @@ -9,28 +9,15 @@ import java.util.stream.Stream; import lombok.extern.java.Log; import org.junit.Assert; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; @Log public class ListInitializationUnitTest { - @Rule - public ExpectedException exception = ExpectedException.none(); - @Test public void givenAnonymousInnerClass_thenInitialiseList() { List cities = new ArrayList() { - // Inside declaration of the subclass - - // You can have multiple initializer block { - log.info("Inside the first initializer block."); - } - - { - log.info("Inside the second initializer block."); add("New York"); add("Rio"); add("Tokyo"); @@ -47,11 +34,10 @@ public class ListInitializationUnitTest { Assert.assertTrue(list.contains("foo")); } - @Test + @Test(expected = UnsupportedOperationException.class) public void givenArraysAsList_whenAdd_thenUnsupportedException() { List list = Arrays.asList("foo", "bar"); - exception.expect(UnsupportedOperationException.class); list.add("baz"); } From f55e3796d98e6e239bf637be7a3561885e3bc1cb Mon Sep 17 00:00:00 2001 From: Felipe Santiago Corro Date: Tue, 14 Aug 2018 07:24:28 -0300 Subject: [PATCH 36/41] optimizing regex expressions (#4961) --- .../optmization/OptimizedMatcher.java | 6 + .../optmization/OptimizedMatcherUnitTest.java | 109 ++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java create mode 100644 core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java new file mode 100644 index 0000000000..ccae942dcc --- /dev/null +++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java @@ -0,0 +1,6 @@ +package com.baeldung.regexp.datepattern.optmization; + +public class OptimizedMatcher { + + +} diff --git a/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java new file mode 100644 index 0000000000..f21a755b01 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java @@ -0,0 +1,109 @@ +package com.baeldung.regexp.optmization; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.Assert.assertTrue; + +public class OptimizedMatcherUnitTest { + + private long time; + private long mstimePreCompiled; + private long mstimeNotPreCompiled; + + private String action; + + private List items; + + @Before + public void setup() { + Random random = new Random(); + items = new ArrayList(); + long average = 0; + + for (int i = 0; i < 100000; ++i) { + StringBuilder s = new StringBuilder(); + int characters = random.nextInt(7) + 1; + for (int k = 0; k < characters; ++ k) { + char c = (char)(random.nextInt('Z' - 'A') + 'A'); + int rep = random.nextInt(95) + 5; + for (int j = 0; j < rep; ++ j) + s.append(c); + average += rep; + } + items.add(s.toString()); + } + + average /= 100000; + System.out.println("generated data, average length: " + average); + } + + + @Test + public void givenANotPreCompiledAndAPreCompiledPatternA_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() { + + testPatterns("A*"); + assertTrue(mstimePreCompiled < mstimeNotPreCompiled); + } + + @Test + public void givenANotPreCompiledAndAPreCompiledPatternABC_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() { + + testPatterns("A*B*C*"); + assertTrue(mstimePreCompiled < mstimeNotPreCompiled); + } + + @Test + public void givenANotPreCompiledAndAPreCompiledPatternECWF_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() { + + testPatterns("E*C*W*F*"); + assertTrue(mstimePreCompiled < mstimeNotPreCompiled); + } + + private void testPatterns(String regex) { + time = System.nanoTime(); + int matched = 0; + int unmatched = 0; + + for (String item : this.items) { + if (item.matches(regex)) { + ++matched; + } + else { + ++unmatched; + } + } + + this.action = "uncompiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched; + + this.mstimeNotPreCompiled = (System.nanoTime() - time) / 1000000; + System.out.println(this.action + ": " + mstimeNotPreCompiled + "ms"); + + time = System.nanoTime(); + + Matcher matcher = Pattern.compile(regex).matcher(""); + matched = 0; + unmatched = 0; + + for (String item : this.items) { + if (matcher.reset(item).matches()) { + ++matched; + } + else { + ++unmatched; + } + } + + this.action = "compiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched; + + this.mstimePreCompiled = (System.nanoTime() - time) / 1000000; + System.out.println(this.action + ": " + mstimePreCompiled + "ms"); + } +} From 7c940234868c6be44e5a433a12c37d37d3e39fa2 Mon Sep 17 00:00:00 2001 From: Doha2012 Date: Tue, 14 Aug 2018 20:50:33 +0000 Subject: [PATCH 37/41] fix eclipse profiles (#4966) --- eclipse/formatter.xml | 292 ------------------------------------------ 1 file changed, 292 deletions(-) diff --git a/eclipse/formatter.xml b/eclipse/formatter.xml index 808f65cda9..6887946a4c 100644 --- a/eclipse/formatter.xml +++ b/eclipse/formatter.xml @@ -1,297 +1,5 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - From 3b64d8ef4ed0cb8201de94a75ba2675ecb93d9b1 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Wed, 15 Aug 2018 14:14:50 +0530 Subject: [PATCH 38/41] BAEL-8219 Fix tests for core-java, maven and core-java-io projects -Test fixes --- .../file/FilenameFilterManualTest.java | 2 +- .../people.json | 0 .../students.json | 0 .../teachers.xml | 0 .../workers.xml | 0 .../exceptionhandling/Exceptions.java | 16 +- .../com/baeldung/binding/AnimalUnitTest.java | 17 +- maven/pom.xml | 266 ++++++++++-------- 8 files changed, 158 insertions(+), 143 deletions(-) rename core-java-io/src/test/resources/{testFolder => fileNameFilterManualTestFolder}/people.json (100%) rename core-java-io/src/test/resources/{testFolder => fileNameFilterManualTestFolder}/students.json (100%) rename core-java-io/src/test/resources/{testFolder => fileNameFilterManualTestFolder}/teachers.xml (100%) rename core-java-io/src/test/resources/{testFolder => fileNameFilterManualTestFolder}/workers.xml (100%) diff --git a/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java b/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java index 47a7973b34..f9a2ce972d 100644 --- a/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java +++ b/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java @@ -18,7 +18,7 @@ public class FilenameFilterManualTest { @BeforeClass public static void setupClass() { directory = new File(FilenameFilterManualTest.class.getClassLoader() - .getResource("testFolder") + .getResource("fileNameFilterManualTestFolder") .getFile()); } diff --git a/core-java-io/src/test/resources/testFolder/people.json b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/people.json similarity index 100% rename from core-java-io/src/test/resources/testFolder/people.json rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/people.json diff --git a/core-java-io/src/test/resources/testFolder/students.json b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/students.json similarity index 100% rename from core-java-io/src/test/resources/testFolder/students.json rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/students.json diff --git a/core-java-io/src/test/resources/testFolder/teachers.xml b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/teachers.xml similarity index 100% rename from core-java-io/src/test/resources/testFolder/teachers.xml rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/teachers.xml diff --git a/core-java-io/src/test/resources/testFolder/workers.xml b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/workers.xml similarity index 100% rename from core-java-io/src/test/resources/testFolder/workers.xml rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/workers.xml diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java b/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java index eb8b733f82..48f4b5c02b 100644 --- a/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java +++ b/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java @@ -25,11 +25,7 @@ public class Exceptions { } public List loadAllPlayers(String playersFile) throws IOException{ - try { - throw new IOException(); - } catch(IOException ex) { - throw new IllegalStateException(); - } + throw new IOException(); } public int getPlayerScoreThrows(String playerFile) throws FileNotFoundException { @@ -163,14 +159,8 @@ public class Exceptions { } } - public void throwAsGotoAntiPattern() { - try { - // bunch of code - throw new MyException(); - // second bunch of code - } catch ( MyException e ) { - // third bunch of code - } + public void throwAsGotoAntiPattern() throws MyException { + throw new MyException(); } public int getPlayerScoreSwallowingExceptionAntiPattern(String playerFile) { diff --git a/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java index 238990f2b4..a34640b58a 100644 --- a/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java +++ b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java @@ -16,8 +16,11 @@ import org.slf4j.LoggerFactory; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import java.util.List; + /** * Created by madhumita.g on 01-08-2018. */ @@ -66,20 +69,18 @@ public class AnimalUnitTest { int testValue = 3; animal.makeNoise(testValue); - verify(mockAppender).doAppend(captorLoggingEvent.capture()); + verify(mockAppender,times(3)).doAppend(captorLoggingEvent.capture()); - final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + final List loggingEvents = captorLoggingEvent.getAllValues(); - while (testValue != 0) { + for(LoggingEvent loggingEvent : loggingEvents) + { assertThat(loggingEvent.getLevel(), is(Level.INFO)); assertThat(loggingEvent.getFormattedMessage(), - is("generic animal noise countdown 3\n" - + "generic animal noise countdown 2\n" - + "generic animal noise countdown 1\n")); - - testValue-=1; + is("generic animal noise countdown "+testValue)); + testValue--; } } diff --git a/maven/pom.xml b/maven/pom.xml index 4f91e8717c..a24b6b16bd 100644 --- a/maven/pom.xml +++ b/maven/pom.xml @@ -1,127 +1,151 @@ - 4.0.0 - com.baeldung - maven - 0.0.1-SNAPSHOT + 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 + maven + 0.0.1-SNAPSHOT - - parent-modules - com.baeldung - 1.0.0-SNAPSHOT - + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + - - - - maven-resources-plugin - ${maven.resources.version} - - output-resources - - - input-resources - - *.png - - true - - - - - - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - -Xlint:unchecked - - - - - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - DataTest.java - - - TestFail.java - DataCheck.java - - true - - - - maven-failsafe-plugin - ${maven.failsafe.version} - - - - integration-test - verify - - - - - - - - - maven-verifier-plugin - ${maven.verifier.version} - - input-resources/verifications.xml - - - - - verify - - - - - - maven-clean-plugin - ${maven.clean.version} - - - - output-resources - - - - - - org.codehaus.mojo - build-helper-maven-plugin - ${maven.build.helper.version} - - - generate-sources - - add-source - - - - src/main/another-src - - - - - - - + + + + maven-resources-plugin + ${maven.resources.version} + + output-resources + + + input-resources + + *.png + + true + + + + + + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + -Xlint:unchecked + + + + + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + DataTest.java + + + TestFail.java + DataCheck.java + + true + + + + maven-failsafe-plugin + ${maven.failsafe.version} + + + + integration-test + verify + + + + + + + + + maven-verifier-plugin + ${maven.verifier.version} + + input-resources/verifications.xml + + + + + verify + + + + + + maven-clean-plugin + ${maven.clean.version} + + + + output-resources + + + + + + org.codehaus.mojo + build-helper-maven-plugin + ${maven.build.helper.version} + + + generate-sources + + add-source + + + + src/main/another-src + + + + + + + - - 3.0.2 - 2.21.0 - 1.1 - 3.0.0 - 3.0.0 - Baeldung - + + + default + + + + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + DataTest.java + + + TestFail.java + DataCheck.java + + true + + + + + + + + + 3.0.2 + 2.21.0 + 1.1 + 3.0.0 + 3.0.0 + Baeldung + \ No newline at end of file From a966b54d4284c0e401cea620bab35de84050d9a4 Mon Sep 17 00:00:00 2001 From: Siben Nayak Date: Wed, 15 Aug 2018 14:19:00 +0530 Subject: [PATCH 39/41] [BAEL-2032] Operate on an item in a Stream then remove it (#4955) * [BAEL-2032] Operate on an item in a Stream then remove it * [BAEL-2032] Refactored unit test * [BAEL-2032] Added a new test for filter and used logger --- .../StreamOperateAndRemoveUnitTest.java | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java b/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java new file mode 100644 index 0000000000..202fe00017 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java @@ -0,0 +1,78 @@ +package com.baeldung.collection; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class StreamOperateAndRemoveUnitTest { + + private List itemList; + + @Before + public void setup() { + + itemList = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + itemList.add(new Item(i)); + } + } + + @Test + public void givenAListOf10Items_whenFilteredForQualifiedItems_thenFilteredListContains5Items() { + + final List filteredList = itemList.stream().filter(item -> item.isQualified()) + .collect(Collectors.toList()); + + Assert.assertEquals(5, filteredList.size()); + } + + @Test + public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() { + + itemList.stream().filter(item -> item.isQualified()).forEach(item -> item.operate()); + itemList.removeIf(item -> item.isQualified()); + + Assert.assertEquals(5, itemList.size()); + } + + @Test + public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveAll_thenListContains5Items() { + + final List operatedList = new ArrayList<>(); + itemList.stream().filter(item -> item.isQualified()).forEach(item -> { + item.operate(); + operatedList.add(item); + }); + itemList.removeAll(operatedList); + + Assert.assertEquals(5, itemList.size()); + } + + class Item { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + private final int value; + + public Item(final int value) { + + this.value = value; + } + + public boolean isQualified() { + + return value % 2 == 0; + } + + public void operate() { + + logger.info("Even Number: " + this.value); + } + } +} \ No newline at end of file From 96e1728d7fa39d072f0f05b8e01339da1c34aa1a Mon Sep 17 00:00:00 2001 From: rozagerardo Date: Wed, 15 Aug 2018 09:13:50 -0300 Subject: [PATCH 40/41] geroza/BAEL-395-Archaius_With_Spring_Cloud_Introduction (#4968) * * added examples for archaius introduction, with basic configuration, extra configurations, adn setting up an additional config source * * fixed indentation in XML files --- spring-cloud/pom.xml | 1 + spring-cloud/spring-cloud-archaius/README.md | 14 ++++ .../additional-sources-simple/pom.xml | 24 ++++++ .../AdditionalSourcesSimpleApplication.java | 13 ++++ .../ApplicationPropertiesConfigurations.java | 21 ++++++ .../ConfigPropertiesController.java | 37 ++++++++++ .../src/main/resources/application.properties | 3 + .../src/main/resources/config.properties | 2 + .../main/resources/other-config.properties | 2 + .../ArchaiusAdditionalSourcesLiveTest.java | 54 ++++++++++++++ .../basic-config/pom.xml | 24 ++++++ .../basic/BasicArchaiusApplication.java | 13 ++++ .../ConfigPropertiesController.java | 70 ++++++++++++++++++ .../src/main/resources/application.properties | 3 + .../src/main/resources/config.properties | 4 + .../src/main/resources/other.properties | 2 + ...aiusBasicConfigurationIntegrationTest.java | 45 +++++++++++ .../ArchaiusBasicConfigurationLiveTest.java | 74 +++++++++++++++++++ .../src/test/resources/config.properties | 3 + .../extra-configs/pom.xml | 43 +++++++++++ .../extraconfigs/ExtraConfigsApplication.java | 16 ++++ .../ConfigPropertiesController.java | 60 +++++++++++++++ .../src/main/resources/application.properties | 3 + .../other-config-dir/extra.properties | 2 + .../src/main/resources/other.properties | 2 + .../ArchaiusExtraConfigsLiveTest.java | 54 ++++++++++++++ spring-cloud/spring-cloud-archaius/pom.xml | 64 ++++++++++++++++ 27 files changed, 653 insertions(+) create mode 100644 spring-cloud/spring-cloud-archaius/README.md create mode 100644 spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml create mode 100644 spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java create mode 100644 spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java create mode 100644 spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java create mode 100644 spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties create mode 100644 spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties create mode 100644 spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties create mode 100644 spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java create mode 100644 spring-cloud/spring-cloud-archaius/basic-config/pom.xml create mode 100644 spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/BasicArchaiusApplication.java create mode 100644 spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/controller/ConfigPropertiesController.java create mode 100644 spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/application.properties create mode 100644 spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/config.properties create mode 100644 spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/other.properties create mode 100644 spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationIntegrationTest.java create mode 100644 spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationLiveTest.java create mode 100644 spring-cloud/spring-cloud-archaius/basic-config/src/test/resources/config.properties create mode 100644 spring-cloud/spring-cloud-archaius/extra-configs/pom.xml create mode 100644 spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/ExtraConfigsApplication.java create mode 100644 spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/controllers/ConfigPropertiesController.java create mode 100644 spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/application.properties create mode 100644 spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other-config-dir/extra.properties create mode 100644 spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other.properties create mode 100644 spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/spring/cloud/archaius/extraconfigs/ArchaiusExtraConfigsLiveTest.java create mode 100644 spring-cloud/spring-cloud-archaius/pom.xml diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 373a12da9e..1fdab4213c 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -31,6 +31,7 @@ spring-cloud-zuul-eureka-integration spring-cloud-contract spring-cloud-kubernetes + spring-cloud-archaius diff --git a/spring-cloud/spring-cloud-archaius/README.md b/spring-cloud/spring-cloud-archaius/README.md new file mode 100644 index 0000000000..9de26352e1 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/README.md @@ -0,0 +1,14 @@ +# Spring Cloud Archaius + +#### Basic Config +This service has the basic, out-of-the-box Spring Cloud Netflix Archaius configuration. + +#### Extra Configs +This service customizes some properties supported by Archaius. + +These properties are set up on the main method, since Archaius uses System properties, but they could be added as command line arguments when launching the app. + +#### Additional Sources +In this service we create a new AbstractConfiguration bean, setting up a new Configuration Properties source. + +These properties have precedence over all the other properties in the Archaius Composite Configuration. \ No newline at end of file diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml b/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml new file mode 100644 index 0000000000..1ae6d543fb --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + additional-sources-simple + 1.0.0-SNAPSHOT + jar + additional-sources-simple + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java new file mode 100644 index 0000000000..e1a1d106cf --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.archaius.additionalsources; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AdditionalSourcesSimpleApplication { + + public static void main(String[] args) { + SpringApplication.run(AdditionalSourcesSimpleApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java new file mode 100644 index 0000000000..f2d8ca2638 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.cloud.archaius.additionalsources.config; + +import org.apache.commons.configuration.AbstractConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.netflix.config.DynamicConfiguration; +import com.netflix.config.FixedDelayPollingScheduler; +import com.netflix.config.PolledConfigurationSource; +import com.netflix.config.sources.URLConfigurationSource; + +@Configuration +public class ApplicationPropertiesConfigurations { + + @Bean + public AbstractConfiguration addApplicationPropertiesSource() { + PolledConfigurationSource source = new URLConfigurationSource("classpath:other-config.properties"); + return new DynamicConfiguration(source, new FixedDelayPollingScheduler()); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..304369a036 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java @@ -0,0 +1,37 @@ +package com.baeldung.spring.cloud.archaius.additionalsources.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + private DynamicStringProperty propertyFourWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.four", "not found!"); + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + properties.put(propertyFourWithDynamic.getName(), propertyFourWithDynamic.get()); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties new file mode 100644 index 0000000000..bf55e89a27 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8082 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties new file mode 100644 index 0000000000..b104c0c488 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:config.properties +baeldung.archaius.properties.three=three FROM:config.properties diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties new file mode 100644 index 0000000000..00fe8ff2aa --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:other-config.properties +baeldung.archaius.properties.four=four FROM:other-config.properties diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java new file mode 100644 index 0000000000..f3a345d869 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java @@ -0,0 +1,54 @@ +package com.baeldung.spring.cloud.archaius.additionalsources; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusAdditionalSourcesLiveTest { + + private static final String BASE_URL = "http://localhost:8082"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:other-config.properties"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:config.properties"); + map.put("baeldung.archaius.properties.four", "four FROM:other-config.properties"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/pom.xml b/spring-cloud/spring-cloud-archaius/basic-config/pom.xml new file mode 100644 index 0000000000..b5b091712d --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + basic-config + 1.0.0-SNAPSHOT + jar + basic-config + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/BasicArchaiusApplication.java b/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/BasicArchaiusApplication.java new file mode 100644 index 0000000000..e6e578eed3 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/BasicArchaiusApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.archaius.basic; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BasicArchaiusApplication { + + public static void main(String[] args) { + SpringApplication.run(BasicArchaiusApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/controller/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/controller/ConfigPropertiesController.java new file mode 100644 index 0000000000..46b8f345f6 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/controller/ConfigPropertiesController.java @@ -0,0 +1,70 @@ +package com.baeldung.spring.cloud.archaius.basic.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicIntProperty; +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + @Value("${baeldung.archaius.properties.one:not found!}") + private String propertyOneWithValue; + + @Value("${baeldung.archaius.properties.two:not found!}") + private String propertyTwoWithValue; + + @Value("${baeldung.archaius.properties.three:not found!}") + private String propertyThreeWithValue; + + @Value("${baeldung.archaius.properties.four:not found!}") + private String propertyFourWithValue; + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + private DynamicStringProperty propertyFourWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.four", "not found!"); + + private DynamicIntProperty intPropertyWithDynamic = DynamicPropertyFactory.getInstance() + .getIntProperty("baeldung.archaius.properties.int", 0); + + @GetMapping("/properties-from-value") + public Map getPropertiesFromValue() { + Map properties = new HashMap<>(); + properties.put("baeldung.archaius.properties.one", propertyOneWithValue); + properties.put("baeldung.archaius.properties.two", propertyTwoWithValue); + properties.put("baeldung.archaius.properties.three", propertyThreeWithValue); + properties.put("baeldung.archaius.properties.four", propertyFourWithValue); + return properties; + } + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get()); + properties.put(propertyTwoWithDynamic.getName(), propertyTwoWithDynamic.get()); + properties.put(propertyThreeWithDynamic.getName(), propertyThreeWithDynamic.get()); + properties.put(propertyFourWithDynamic.getName(), propertyFourWithDynamic.get()); + return properties; + } + + @GetMapping("/int-property") + public Map getIntPropertyFromDynamic() { + Map properties = new HashMap<>(); + properties.put(intPropertyWithDynamic.getName(), intPropertyWithDynamic.get()); + return properties; + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/application.properties new file mode 100644 index 0000000000..1a35a22197 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8080 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties \ No newline at end of file diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/config.properties b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/config.properties new file mode 100644 index 0000000000..86ae575d20 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/config.properties @@ -0,0 +1,4 @@ +baeldung.archaius.properties.one=one FROM:config.properties +baeldung.archaius.properties.three=three FROM:config.properties + +baeldung.archaius.properties.int=1 diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/other.properties b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/other.properties new file mode 100644 index 0000000000..26796b7341 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/main/resources/other.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:other.properties +baeldung.archaius.properties.four=four FROM:other.properties diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationIntegrationTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationIntegrationTest.java new file mode 100644 index 0000000000..2948606c0b --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationIntegrationTest.java @@ -0,0 +1,45 @@ +package com.baeldung.spring.cloud.archaius.basic; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collections; + +import org.junit.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.cloud.context.environment.EnvironmentChangeEvent; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RunWith(JUnitPlatform.class) +@ExtendWith(SpringExtension.class) +@SpringBootTest +public class ArchaiusBasicConfigurationIntegrationTest { + + @Autowired + ConfigurableApplicationContext context; + + private DynamicStringProperty testPropertyWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.test.properties.one", "not found!"); + + @Test + public void givenIntialPropertyValue_whenPropertyChanges_thenArchaiusRetrievesNewValue() { + String initialValue = testPropertyWithDynamic.get(); + + TestPropertyValues.of("baeldung.archaius.test.properties.one=new-value") + .applyTo(context); + context.publishEvent(new EnvironmentChangeEvent(Collections.singleton("baeldung.archaius.test.properties.one"))); + String finalValue = testPropertyWithDynamic.get(); + + assertThat(initialValue).isEqualTo("test-one"); + assertThat(finalValue).isEqualTo("new-value"); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationLiveTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationLiveTest.java new file mode 100644 index 0000000000..70d43df60d --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationLiveTest.java @@ -0,0 +1,74 @@ +package com.baeldung.spring.cloud.archaius.basic; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusBasicConfigurationLiveTest { + + private static final String BASE_URL = "http://localhost:8080"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:application.properties"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:config.properties"); + map.put("baeldung.archaius.properties.four", "not found!"); + return map; + } + + private static final String VALUE_PROPERTIES_URL = "/properties-from-value"; + private static final Map EXPECTED_VALUE_PROPERTIES = createExpectedValueProperties(); + + private static Map createExpectedValueProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:application.properties"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "not found!"); + map.put("baeldung.archaius.properties.four", "not found!"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenDefaultConfigurationSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestSpringVisibleProperties_thenEndpointDoesntRetrieveArchaiusProperties() { + Map initialResponse = this.exchangeAsMap(BASE_URL + VALUE_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_VALUE_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/resources/config.properties b/spring-cloud/spring-cloud-archaius/basic-config/src/test/resources/config.properties new file mode 100644 index 0000000000..1ceb5d1161 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/resources/config.properties @@ -0,0 +1,3 @@ +baeldung.archaius.test.properties.one=test-one +baeldung.archaius.test.properties.two=test-two +baeldung.archaius.test.properties.int=1 diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/pom.xml b/spring-cloud/spring-cloud-archaius/extra-configs/pom.xml new file mode 100644 index 0000000000..2f3f2b084a --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + extra-configs + 1.0.0-SNAPSHOT + jar + extra-configs + + + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-netflix-archaius + + + + + + + org.springframework.cloud + spring-cloud-netflix + ${spring-cloud-dependencies.version} + pom + import + + + + + 2.0.1.RELEASE + + diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/ExtraConfigsApplication.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/ExtraConfigsApplication.java new file mode 100644 index 0000000000..4747d875db --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/ExtraConfigsApplication.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.archaius.extraconfigs; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ExtraConfigsApplication { + + public static void main(String[] args) { + // System properties can be set as command line arguments too + System.setProperty("archaius.configurationSource.additionalUrls", "classpath:other-config-dir/extra.properties"); + System.setProperty("archaius.configurationSource.defaultFileName", "other.properties"); + SpringApplication.run(ExtraConfigsApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/controllers/ConfigPropertiesController.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/controllers/ConfigPropertiesController.java new file mode 100644 index 0000000000..382c6b3a2c --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/controllers/ConfigPropertiesController.java @@ -0,0 +1,60 @@ +package com.baeldung.spring.cloud.archaius.extraconfigs.controllers; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.netflix.config.DynamicPropertyFactory; +import com.netflix.config.DynamicStringProperty; + +@RestController +public class ConfigPropertiesController { + + @Value("${baeldung.archaius.properties.one:not found!}") + private String propertyOneWithValue; + + @Value("${baeldung.archaius.properties.two:not found!}") + private String propertyTwoWithValue; + + @Value("${baeldung.archaius.properties.three:not found!}") + private String propertyThreeWithValue; + + @Value("${baeldung.archaius.properties.four:not found!}") + private String propertyFourWithValue; + + private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.one", "not found!"); + + private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.two", "not found!"); + + private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.three", "not found!"); + + private DynamicStringProperty propertyFourWithDynamic = DynamicPropertyFactory.getInstance() + .getStringProperty("baeldung.archaius.properties.four", "not found!"); + + @GetMapping("/properties-from-value") + public Map getPropertiesFromValue() { + Map properties = new HashMap<>(); + properties.put("baeldung.archaius.properties.one", propertyOneWithValue); + properties.put("baeldung.archaius.properties.two", propertyTwoWithValue); + properties.put("baeldung.archaius.properties.three", propertyThreeWithValue); + properties.put("baeldung.archaius.properties.four", propertyFourWithValue); + return properties; + } + + @GetMapping("/properties-from-dynamic") + public Map getPropertiesFromDynamic() { + Map properties = new HashMap<>(); + properties.put("baeldung.archaius.properties.one", propertyOneWithDynamic.get()); + properties.put("baeldung.archaius.properties.two", propertyTwoWithDynamic.get()); + properties.put("baeldung.archaius.properties.three", propertyThreeWithDynamic.get()); + properties.put("baeldung.archaius.properties.four", propertyFourWithDynamic.get()); + return properties; + } + +} diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/application.properties b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/application.properties new file mode 100644 index 0000000000..1e36b134d4 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8081 +baeldung.archaius.properties.one=one FROM:application.properties +baeldung.archaius.properties.two=two FROM:application.properties diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other-config-dir/extra.properties b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other-config-dir/extra.properties new file mode 100644 index 0000000000..ea99914cc1 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other-config-dir/extra.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:extra.properties +baeldung.archaius.properties.three=three FROM:extra.properties diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other.properties b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other.properties new file mode 100644 index 0000000000..26796b7341 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/main/resources/other.properties @@ -0,0 +1,2 @@ +baeldung.archaius.properties.one=one FROM:other.properties +baeldung.archaius.properties.four=four FROM:other.properties diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/spring/cloud/archaius/extraconfigs/ArchaiusExtraConfigsLiveTest.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/spring/cloud/archaius/extraconfigs/ArchaiusExtraConfigsLiveTest.java new file mode 100644 index 0000000000..232ca73352 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/spring/cloud/archaius/extraconfigs/ArchaiusExtraConfigsLiveTest.java @@ -0,0 +1,54 @@ +package com.baeldung.spring.cloud.archaius.extraconfigs; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ArchaiusExtraConfigsLiveTest { + + private static final String BASE_URL = "http://localhost:8081"; + + private static final String DYNAMIC_PROPERTIES_URL = "/properties-from-dynamic"; + private static final Map EXPECTED_ARCHAIUS_PROPERTIES = createExpectedArchaiusProperties(); + + private static Map createExpectedArchaiusProperties() { + Map map = new HashMap<>(); + map.put("baeldung.archaius.properties.one", "one FROM:application.properties"); + map.put("baeldung.archaius.properties.two", "two FROM:application.properties"); + map.put("baeldung.archaius.properties.three", "three FROM:extra.properties"); + map.put("baeldung.archaius.properties.four", "four FROM:other.properties"); + return map; + } + + @Autowired + ConfigurableApplicationContext context; + + @Autowired + private TestRestTemplate template; + + private Map exchangeAsMap(String uri, ParameterizedTypeReference> responseType) { + return template.exchange(uri, HttpMethod.GET, null, responseType) + .getBody(); + } + + @Test + public void givenNonDefaultConfigurationFilesSetup_whenRequestProperties_thenEndpointRetrievesValuesInFiles() { + Map initialResponse = this.exchangeAsMap(BASE_URL + DYNAMIC_PROPERTIES_URL, new ParameterizedTypeReference>() { + }); + + assertThat(initialResponse).containsAllEntriesOf(EXPECTED_ARCHAIUS_PROPERTIES); + } +} diff --git a/spring-cloud/spring-cloud-archaius/pom.xml b/spring-cloud/spring-cloud-archaius/pom.xml new file mode 100644 index 0000000000..cd102f86cd --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/pom.xml @@ -0,0 +1,64 @@ + + + 4.0.0 + com.baeldung.spring.cloud + spring-cloud-archaius + 1.0.0-SNAPSHOT + spring-cloud-archaius + Spring Cloud Archaius Pom parent + pom + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + .. + + + + basic-config + additional-sources-simple + extra-configs + + + + + org.springframework.cloud + spring-cloud-starter-netflix-archaius + + + org.springframework.boot + spring-boot-starter-test + + + org.assertj + assertj-core + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + + + + org.springframework.cloud + spring-cloud-netflix + ${spring-cloud-dependencies.version} + pom + import + + + + + + 2.0.1.RELEASE + 1.2.0 + + From 3f2271f51b8a9852c240fafbddaf028c0e76fc08 Mon Sep 17 00:00:00 2001 From: bungrudi <30967151+bungrudi@users.noreply.github.com> Date: Wed, 15 Aug 2018 20:23:19 +0700 Subject: [PATCH 41/41] BAEL-2043: An Intro to Hibernate Entity Lifecycle (#4960) * "An Intro to Hibernate Entity Lifecycle" "An Intro to Hibernate Entity Lifecycle" by Rudi * Revision from Predrag's feedback * Another revision from Predrag's feedback * Another feedback. --- .../lifecycle/DirtyDataInspector.java | 26 +++ .../hibernate/lifecycle/FootballPlayer.java | 35 ++++ .../lifecycle/HibernateLifecycleUtil.java | 96 ++++++++++ .../HibernateInterceptorUnitTest.java | 1 - .../lifecycle/HibernateLifecycleUnitTest.java | 164 ++++++++++++++++++ .../resources/hibernate-lifecycle.properties | 9 + .../src/test/resources/lifecycle-init.sql | 25 +++ 7 files changed, 355 insertions(+), 1 deletion(-) create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java create mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java create mode 100644 hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java create mode 100644 hibernate5/src/test/resources/hibernate-lifecycle.properties create mode 100644 hibernate5/src/test/resources/lifecycle-init.sql diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java new file mode 100644 index 0000000000..4e00be2b5c --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java @@ -0,0 +1,26 @@ +package com.baeldung.hibernate.lifecycle; + +import org.hibernate.EmptyInterceptor; +import org.hibernate.type.Type; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class DirtyDataInspector extends EmptyInterceptor { + private static final ArrayList dirtyEntities = new ArrayList<>(); + + @Override + public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { + dirtyEntities.add((FootballPlayer) entity); + return true; + } + + public static List getDirtyEntities() { + return dirtyEntities; + } + + public static void clearDirtyEntitites() { + dirtyEntities.clear(); + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java new file mode 100644 index 0000000000..49799a5292 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java @@ -0,0 +1,35 @@ +package com.baeldung.hibernate.lifecycle; + +import javax.persistence.*; + +@Entity +@Table(name = "Football_Player") +public class FootballPlayer { + @Id + @GeneratedValue + private long id; + + @Column + private String name; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "FootballPlayer{" + "id=" + id + ", name='" + name + '\'' + '}'; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java new file mode 100644 index 0000000000..a06685fb9c --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java @@ -0,0 +1,96 @@ +package com.baeldung.hibernate.lifecycle; + +import org.h2.tools.RunScript; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.SessionFactoryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.engine.spi.EntityEntry; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.service.ServiceRegistry; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; + +public class HibernateLifecycleUtil { + private static SessionFactory sessionFactory; + private static Connection connection; + + public static void init() throws Exception { + Properties hbConfigProp = getHibernateProperties(); + Class.forName(hbConfigProp.getProperty("hibernate.connection.driver_class")); + connection = DriverManager.getConnection(hbConfigProp.getProperty("hibernate.connection.url"), hbConfigProp.getProperty("hibernate.connection.username"), hbConfigProp.getProperty("hibernate.connection.password")); + + try (InputStream h2InitStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lifecycle-init.sql"); + InputStreamReader h2InitReader = new InputStreamReader(h2InitStream)) { + RunScript.execute(connection, h2InitReader); + } + + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(new DirtyDataInspector()).build(); + } + + public static void tearDown() throws Exception { + sessionFactory.close(); + connection.close(); + } + + public static SessionFactory getSessionFactory() { + return sessionFactory; + } + + private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(FootballPlayer.class); + + Metadata metadata = metadataSources.buildMetadata(); + return metadata.getSessionFactoryBuilder(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getHibernateProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties).build(); + } + + private static Properties getHibernateProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate-lifecycle.properties"); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } + + public static List getManagedEntities(Session session) { + Map.Entry[] entries = ((SessionImplementor) session).getPersistenceContext().reentrantSafeEntityEntries(); + return Arrays.stream(entries).map(e -> e.getValue()).collect(Collectors.toList()); + } + + public static Transaction startTransaction(Session s) { + Transaction tx = s.getTransaction(); + tx.begin(); + return tx; + } + + public static int queryCount(String query) throws Exception { + try (ResultSet rs = connection.createStatement().executeQuery(query)) { + rs.next(); + return rs.getInt(1); + } + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java index 0049f3a6bd..e18e989905 100644 --- a/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java +++ b/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java @@ -58,5 +58,4 @@ public class HibernateInterceptorUnitTest { transaction.commit(); session.close(); } - } diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java new file mode 100644 index 0000000000..e682b46481 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java @@ -0,0 +1,164 @@ +package com.baeldung.hibernate.lifecycle; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.engine.spi.Status; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static com.baeldung.hibernate.lifecycle.DirtyDataInspector.getDirtyEntities; +import static com.baeldung.hibernate.lifecycle.HibernateLifecycleUtil.*; +import static org.assertj.core.api.Assertions.assertThat; + +public class HibernateLifecycleUnitTest { + + @BeforeClass + public static void setup() throws Exception { + HibernateLifecycleUtil.init(); + + } + + @AfterClass + public static void tearDown() throws Exception { + HibernateLifecycleUtil.tearDown(); + } + + @Before + public void beforeMethod() { + DirtyDataInspector.clearDirtyEntitites(); + } + + @Test + public void whenEntityLoaded_thenEntityManaged() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + assertThat(getManagedEntities(session)).isEmpty(); + + List players = session.createQuery("from FootballPlayer").getResultList(); + assertThat(getManagedEntities(session)).size().isEqualTo(3); + + assertThat(getDirtyEntities()).isEmpty(); + + FootballPlayer gigiBuffon = players.stream().filter(p -> p.getId() == 3).findFirst().get(); + + gigiBuffon.setName("Gianluigi Buffon"); + transaction.commit(); + + assertThat(getDirtyEntities()).size().isEqualTo(1); + assertThat(getDirtyEntities().get(0).getId()).isEqualTo(3); + assertThat(getDirtyEntities().get(0).getName()).isEqualTo("Gianluigi Buffon"); + } + } + + @Test + public void whenDetached_thenNotTracked() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer cr7 = session.get(FootballPlayer.class, 1L); + assertThat(getManagedEntities(session)).size().isEqualTo(1); + assertThat(getManagedEntities(session).get(0).getId()).isEqualTo(cr7.getId()); + + session.evict(cr7); + assertThat(getManagedEntities(session)).size().isEqualTo(0); + + cr7.setName("CR7"); + transaction.commit(); + + assertThat(getDirtyEntities()).isEmpty(); + } + } + + @Test + public void whenReattached_thenTrackedAgain() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer messi = session.get(FootballPlayer.class, 2L); + + session.evict(messi); + messi.setName("Leo Messi"); + transaction.commit(); + assertThat(getDirtyEntities()).isEmpty(); + + transaction = startTransaction(session); + session.update(messi); + transaction.commit(); + assertThat(getDirtyEntities()).size().isEqualTo(1); + assertThat(getDirtyEntities().get(0).getName()).isEqualTo("Leo Messi"); + } + } + + @Test + public void givenNewEntityWithID_whenReattached_thenManaged() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer gigi = new FootballPlayer(); + gigi.setId(3); + gigi.setName("Gigi the Legend"); + + session.update(gigi); + assertThat(getManagedEntities(session)).size().isEqualTo(1); + + transaction.commit(); + assertThat(getDirtyEntities()).size().isEqualTo(1); + } + } + + @Test + public void givenTransientEntity_whenSave_thenManaged() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer neymar = new FootballPlayer(); + neymar.setName("Neymar"); + + session.save(neymar); + assertThat(getManagedEntities(session)).size().isEqualTo(1); + assertThat(neymar.getId()).isNotNull(); + + int count = queryCount("select count(*) from Football_Player where name='Neymar'"); + assertThat(count).isEqualTo(0); + + transaction.commit(); + + count = queryCount("select count(*) from Football_Player where name='Neymar'"); + assertThat(count).isEqualTo(1); + + transaction = startTransaction(session); + session.delete(neymar); + transaction.commit(); + } + } + + @Test() + public void whenDelete_thenMarkDeleted() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer neymar = new FootballPlayer(); + neymar.setName("Neymar"); + + session.save(neymar); + transaction.commit(); + + transaction = startTransaction(session); + session.delete(neymar); + assertThat(getManagedEntities(session).get(0).getStatus()).isEqualTo(Status.DELETED); + transaction.commit(); + } + } +} diff --git a/hibernate5/src/test/resources/hibernate-lifecycle.properties b/hibernate5/src/test/resources/hibernate-lifecycle.properties new file mode 100644 index 0000000000..d043b624f2 --- /dev/null +++ b/hibernate5/src/test/resources/hibernate-lifecycle.properties @@ -0,0 +1,9 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:lifecycledb;DB_CLOSE_DELAY=-1; +hibernate.connection.username=sa +hibernate.connection.password= +hibernate.connection.autocommit=true + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=validate \ No newline at end of file diff --git a/hibernate5/src/test/resources/lifecycle-init.sql b/hibernate5/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/hibernate5/src/test/resources/lifecycle-init.sql @@ -0,0 +1,25 @@ +create sequence hibernate_sequence start with 1 increment by 1; + +create table Football_Player ( + id bigint not null, + name varchar(255), + primary key (id) +); + +insert into + Football_Player + (name, id) + values + ('Cristiano Ronaldo', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Lionel Messi', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Gigi Buffon', next value for hibernate_sequence); \ No newline at end of file