From 238e75eec9e79dd09a269d6b921f76169247b3c0 Mon Sep 17 00:00:00 2001 From: Joel Juarez Date: Sun, 19 May 2019 22:03:12 +0200 Subject: [PATCH 01/44] added parent module for spring boot 2.2 added module for spring boot 2.2 added example for lazy initialization in spring boot 2.2 --- parent-boot-2-2/README.md | 2 + parent-boot-2-2/pom.xml | 91 +++++++++++++++++++ spring-boot-2-2/pom.xml | 45 +++++++++ .../lazyinitialization/Application.java | 32 +++++++ .../lazyinitialization/services/Writer.java | 16 ++++ .../src/main/resources/application.yml | 3 + 6 files changed, 189 insertions(+) create mode 100644 parent-boot-2-2/README.md create mode 100644 parent-boot-2-2/pom.xml create mode 100644 spring-boot-2-2/pom.xml create mode 100644 spring-boot-2-2/src/main/java/com/baeldung/lazyinitialization/Application.java create mode 100644 spring-boot-2-2/src/main/java/com/baeldung/lazyinitialization/services/Writer.java create mode 100644 spring-boot-2-2/src/main/resources/application.yml diff --git a/parent-boot-2-2/README.md b/parent-boot-2-2/README.md new file mode 100644 index 0000000000..d2bd6d660b --- /dev/null +++ b/parent-boot-2-2/README.md @@ -0,0 +1,2 @@ + +This is a parent module for all projects using Spring Boot 2.2. diff --git a/parent-boot-2-2/pom.xml b/parent-boot-2-2/pom.xml new file mode 100644 index 0000000000..59611c9044 --- /dev/null +++ b/parent-boot-2-2/pom.xml @@ -0,0 +1,91 @@ + + 4.0.0 + parent-boot-2-2 + 0.0.1-SNAPSHOT + parent-boot-2-2 + pom + Parent for all Spring Boot 2.2 modules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + io.rest-assured + rest-assured + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + ${start-class} + + + + + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + + thin-jar + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.springframework.boot.experimental + spring-boot-thin-layout + ${thin.version} + + + + + + + + + + 3.1.0 + + 1.0.21.RELEASE + 2.2.0.M3 + + diff --git a/spring-boot-2-2/pom.xml b/spring-boot-2-2/pom.xml new file mode 100644 index 0000000000..4390e29b60 --- /dev/null +++ b/spring-boot-2-2/pom.xml @@ -0,0 +1,45 @@ + + 4.0.0 + spring-boot-2-2 + spring-boot-2-2 + war + This is simple boot application for Spring boot 2.2 + + + parent-boot-2-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2-2 + + + + + org.springframework.boot + spring-boot-starter + + + + + spring-boot-2-2 + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-war-plugin + + + + + + + com.baeldung.lazyinitialization.Application + + \ No newline at end of file diff --git a/spring-boot-2-2/src/main/java/com/baeldung/lazyinitialization/Application.java b/spring-boot-2-2/src/main/java/com/baeldung/lazyinitialization/Application.java new file mode 100644 index 0000000000..195b260399 --- /dev/null +++ b/spring-boot-2-2/src/main/java/com/baeldung/lazyinitialization/Application.java @@ -0,0 +1,32 @@ +package com.baeldung.lazyinitialization; + +import com.baeldung.lazyinitialization.services.Writer; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class Application { + + @Bean("writer1") + public Writer getWriter1() { + return new Writer("Writer 1"); + } + + @Bean("writer2") + public Writer getWriter2() { + return new Writer("Writer 2"); + } + + public static void main(String[] args) { + ApplicationContext ctx = SpringApplication.run(Application.class, args); + System.out.println("Application context initialized!!!"); + + Writer writer1 = ctx.getBean("writer1", Writer.class); + writer1.write("First message"); + + Writer writer2 = ctx.getBean("writer2", Writer.class); + writer2.write("Second message"); + } +} diff --git a/spring-boot-2-2/src/main/java/com/baeldung/lazyinitialization/services/Writer.java b/spring-boot-2-2/src/main/java/com/baeldung/lazyinitialization/services/Writer.java new file mode 100644 index 0000000000..7c67fb7ea4 --- /dev/null +++ b/spring-boot-2-2/src/main/java/com/baeldung/lazyinitialization/services/Writer.java @@ -0,0 +1,16 @@ +package com.baeldung.lazyinitialization.services; + +public class Writer { + + private final String writerId; + + public Writer(String writerId) { + this.writerId = writerId; + System.out.println(writerId + " initialized!!!"); + } + + public void write(String message) { + System.out.println(writerId + ": " + message); + } + +} diff --git a/spring-boot-2-2/src/main/resources/application.yml b/spring-boot-2-2/src/main/resources/application.yml new file mode 100644 index 0000000000..25f03eed56 --- /dev/null +++ b/spring-boot-2-2/src/main/resources/application.yml @@ -0,0 +1,3 @@ +spring: + main: + lazy-initialization: true \ No newline at end of file From dfeadea6ae73c7cbed66f1bc1c5c0a42e1d39817 Mon Sep 17 00:00:00 2001 From: Joel Juarez Date: Mon, 3 Jun 2019 00:36:37 +0200 Subject: [PATCH 02/44] CHANGED: name of module for Spring Boot 2.2 --- {parent-boot-2-2 => parent-boot-performance}/README.md | 1 - {parent-boot-2-2 => parent-boot-performance}/pom.xml | 4 ++-- {spring-boot-2-2 => spring-boot-performance}/pom.xml | 10 +++++----- .../com/baeldung/lazyinitialization/Application.java | 0 .../baeldung/lazyinitialization/services/Writer.java | 0 .../src/main/resources/application.yml | 0 6 files changed, 7 insertions(+), 8 deletions(-) rename {parent-boot-2-2 => parent-boot-performance}/README.md (98%) rename {parent-boot-2-2 => parent-boot-performance}/pom.xml (97%) rename {spring-boot-2-2 => spring-boot-performance}/pom.xml (82%) rename {spring-boot-2-2 => spring-boot-performance}/src/main/java/com/baeldung/lazyinitialization/Application.java (100%) rename {spring-boot-2-2 => spring-boot-performance}/src/main/java/com/baeldung/lazyinitialization/services/Writer.java (100%) rename {spring-boot-2-2 => spring-boot-performance}/src/main/resources/application.yml (100%) diff --git a/parent-boot-2-2/README.md b/parent-boot-performance/README.md similarity index 98% rename from parent-boot-2-2/README.md rename to parent-boot-performance/README.md index d2bd6d660b..963176a5e3 100644 --- a/parent-boot-2-2/README.md +++ b/parent-boot-performance/README.md @@ -1,2 +1 @@ - This is a parent module for all projects using Spring Boot 2.2. diff --git a/parent-boot-2-2/pom.xml b/parent-boot-performance/pom.xml similarity index 97% rename from parent-boot-2-2/pom.xml rename to parent-boot-performance/pom.xml index 59611c9044..c7a0263716 100644 --- a/parent-boot-2-2/pom.xml +++ b/parent-boot-performance/pom.xml @@ -1,9 +1,9 @@ 4.0.0 - parent-boot-2-2 + parent-boot-performance 0.0.1-SNAPSHOT - parent-boot-2-2 + parent-boot-performance pom Parent for all Spring Boot 2.2 modules diff --git a/spring-boot-2-2/pom.xml b/spring-boot-performance/pom.xml similarity index 82% rename from spring-boot-2-2/pom.xml rename to spring-boot-performance/pom.xml index 4390e29b60..cb2dba359e 100644 --- a/spring-boot-2-2/pom.xml +++ b/spring-boot-performance/pom.xml @@ -2,16 +2,16 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-boot-2-2 - spring-boot-2-2 + spring-boot-performance + spring-boot-performance war This is simple boot application for Spring boot 2.2 - parent-boot-2-2 + parent-boot-performance com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2-2 + ../parent-boot-performance @@ -22,7 +22,7 @@ - spring-boot-2-2 + spring-boot-performance src/main/resources diff --git a/spring-boot-2-2/src/main/java/com/baeldung/lazyinitialization/Application.java b/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/Application.java similarity index 100% rename from spring-boot-2-2/src/main/java/com/baeldung/lazyinitialization/Application.java rename to spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/Application.java diff --git a/spring-boot-2-2/src/main/java/com/baeldung/lazyinitialization/services/Writer.java b/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/services/Writer.java similarity index 100% rename from spring-boot-2-2/src/main/java/com/baeldung/lazyinitialization/services/Writer.java rename to spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/services/Writer.java diff --git a/spring-boot-2-2/src/main/resources/application.yml b/spring-boot-performance/src/main/resources/application.yml similarity index 100% rename from spring-boot-2-2/src/main/resources/application.yml rename to spring-boot-performance/src/main/resources/application.yml From 4633c51b175b8b16cc51522c1f59abe152965b6e Mon Sep 17 00:00:00 2001 From: Erhan KARAKAYA Date: Wed, 5 Jun 2019 01:44:57 +0300 Subject: [PATCH 03/44] Added code sample for autoservice --- autovalue/pom.xml | 7 +++++++ .../autoservice/BingTranslateServiceProvider.java | 11 +++++++++++ .../autoservice/GoogleTranslateServiceProvider.java | 11 +++++++++++ .../com/baeldung/autoservice/TranslateService.java | 8 ++++++++ 4 files changed, 37 insertions(+) create mode 100644 autovalue/src/main/java/com/baeldung/autoservice/BingTranslateServiceProvider.java create mode 100644 autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslateServiceProvider.java create mode 100644 autovalue/src/main/java/com/baeldung/autoservice/TranslateService.java diff --git a/autovalue/pom.xml b/autovalue/pom.xml index 3ec2d26b35..a10e8ef055 100644 --- a/autovalue/pom.xml +++ b/autovalue/pom.xml @@ -29,6 +29,12 @@ + + com.google.auto.service + auto-service + ${auto-service.version} + true + com.google.inject @@ -40,6 +46,7 @@ 1.3 1.0-beta5 + 1.0-rc5 4.2.0 diff --git a/autovalue/src/main/java/com/baeldung/autoservice/BingTranslateServiceProvider.java b/autovalue/src/main/java/com/baeldung/autoservice/BingTranslateServiceProvider.java new file mode 100644 index 0000000000..93ab8f4fe4 --- /dev/null +++ b/autovalue/src/main/java/com/baeldung/autoservice/BingTranslateServiceProvider.java @@ -0,0 +1,11 @@ +package com.baeldung.autoservice; + +import java.util.Locale; + +@AutoService(TranslateService.class) +public class BingTranslateServiceProvider implements TranslateService { + + public String translate(String message, Locale from, Locale to) { + return "translated by Bing"; + } +} diff --git a/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslateServiceProvider.java b/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslateServiceProvider.java new file mode 100644 index 0000000000..07772e2afe --- /dev/null +++ b/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslateServiceProvider.java @@ -0,0 +1,11 @@ +package com.baeldung.autoservice; + +import java.util.Locale; + +@AutoService(TranslateService.class) +public class GoogleTranslateServiceProvider implements TranslateService { + + public String translate(String message, Locale from, Locale to) { + return "translated by Google"; + } +} diff --git a/autovalue/src/main/java/com/baeldung/autoservice/TranslateService.java b/autovalue/src/main/java/com/baeldung/autoservice/TranslateService.java new file mode 100644 index 0000000000..6d68f6aca3 --- /dev/null +++ b/autovalue/src/main/java/com/baeldung/autoservice/TranslateService.java @@ -0,0 +1,8 @@ +package com.baeldung.autoservice; + +import java.util.Locale; + +public interface TranslateService { + + String translate(String message, Locale from, Locale to); +} From de469b49409ac2e615b00762d5d9c551fa3e813f Mon Sep 17 00:00:00 2001 From: Erhan KARAKAYA Date: Wed, 5 Jun 2019 02:00:53 +0300 Subject: [PATCH 04/44] Added missing imports --- .../com/baeldung/autoservice/BingTranslateServiceProvider.java | 2 ++ .../baeldung/autoservice/GoogleTranslateServiceProvider.java | 2 ++ 2 files changed, 4 insertions(+) diff --git a/autovalue/src/main/java/com/baeldung/autoservice/BingTranslateServiceProvider.java b/autovalue/src/main/java/com/baeldung/autoservice/BingTranslateServiceProvider.java index 93ab8f4fe4..00f21a943e 100644 --- a/autovalue/src/main/java/com/baeldung/autoservice/BingTranslateServiceProvider.java +++ b/autovalue/src/main/java/com/baeldung/autoservice/BingTranslateServiceProvider.java @@ -1,5 +1,7 @@ package com.baeldung.autoservice; +import com.google.auto.service.AutoService; + import java.util.Locale; @AutoService(TranslateService.class) diff --git a/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslateServiceProvider.java b/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslateServiceProvider.java index 07772e2afe..786d9bd443 100644 --- a/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslateServiceProvider.java +++ b/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslateServiceProvider.java @@ -1,5 +1,7 @@ package com.baeldung.autoservice; +import com.google.auto.service.AutoService; + import java.util.Locale; @AutoService(TranslateService.class) From 2449c8117a6ddc87b76043cbd6a1ec10d1073329 Mon Sep 17 00:00:00 2001 From: Andrew Shcherbakov Date: Wed, 12 Jun 2019 07:18:14 +0200 Subject: [PATCH 05/44] Create a package for the article code --- .../main/java/com/baeldung/folding/Main.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/folding/Main.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/Main.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/Main.java new file mode 100644 index 0000000000..47ae11c80c --- /dev/null +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/Main.java @@ -0,0 +1,21 @@ +package com.baeldung.folding; + +import java.util.stream.IntStream; + +public class Main { + public static void main(String... arg) { + final String key = "Java language"; + + toAsciiCodes(key).forEach(c -> System.out.println(c)); + // toAsciiCodes(key).reduce(new ArrayList(), (accum, i) -> i); + // List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + // numbers.stream() + // .reduce(new ArrayList(), (k, v) -> new ArrayList()); + // System.out.println(result); + } + + public static IntStream toAsciiCodes(String key) { + return key.chars(); + } + +} From 2e383281a85ea2bbb0c5da0e71cf97e3707a8b1d Mon Sep 17 00:00:00 2001 From: Joel Juarez Date: Wed, 12 Jun 2019 23:14:04 +0200 Subject: [PATCH 06/44] Changed description for spring-boot-performance module --- parent-boot-performance/README.md | 2 +- parent-boot-performance/pom.xml | 2 +- spring-boot-performance/pom.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/parent-boot-performance/README.md b/parent-boot-performance/README.md index 963176a5e3..4ac49c9070 100644 --- a/parent-boot-performance/README.md +++ b/parent-boot-performance/README.md @@ -1 +1 @@ -This is a parent module for all projects using Spring Boot 2.2. +This is a parent module for projects taht want to take advantage of the performance improvements introduced in Spring Boot from version 2.2. diff --git a/parent-boot-performance/pom.xml b/parent-boot-performance/pom.xml index c7a0263716..49cea2ad30 100644 --- a/parent-boot-performance/pom.xml +++ b/parent-boot-performance/pom.xml @@ -5,7 +5,7 @@ 0.0.1-SNAPSHOT parent-boot-performance pom - Parent for all Spring Boot 2.2 modules + Parent for all modules taht want to take advantage of the performance improvements introduced in Spring Boot from version 2.2 com.baeldung diff --git a/spring-boot-performance/pom.xml b/spring-boot-performance/pom.xml index cb2dba359e..8f4c08002d 100644 --- a/spring-boot-performance/pom.xml +++ b/spring-boot-performance/pom.xml @@ -5,7 +5,7 @@ spring-boot-performance spring-boot-performance war - This is simple boot application for Spring boot 2.2 + This is a simple Spring Boot application taking advantage of the performance improvements introduced from version 2.2 parent-boot-performance From 20e1e2583122597b5f3b439c02eba0d14cffd974 Mon Sep 17 00:00:00 2001 From: Joel Juarez Date: Wed, 12 Jun 2019 23:20:32 +0200 Subject: [PATCH 07/44] Changed description for spring-boot-performance module --- parent-boot-performance/README.md | 4 +++- parent-boot-performance/pom.xml | 2 +- spring-boot-performance/pom.xml | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/parent-boot-performance/README.md b/parent-boot-performance/README.md index 4ac49c9070..e8eb056fe3 100644 --- a/parent-boot-performance/README.md +++ b/parent-boot-performance/README.md @@ -1 +1,3 @@ -This is a parent module for projects taht want to take advantage of the performance improvements introduced in Spring Boot from version 2.2. +This is a parent module for projects taht want to take advantage of the latests Spring Boot improvements/features. + +Current version: Spring Boot 2.2 diff --git a/parent-boot-performance/pom.xml b/parent-boot-performance/pom.xml index 49cea2ad30..078f002968 100644 --- a/parent-boot-performance/pom.xml +++ b/parent-boot-performance/pom.xml @@ -5,7 +5,7 @@ 0.0.1-SNAPSHOT parent-boot-performance pom - Parent for all modules taht want to take advantage of the performance improvements introduced in Spring Boot from version 2.2 + Parent for all modules taht want to take advantage of the latests Spring Boot improvements/features. Current version: 2.2 com.baeldung diff --git a/spring-boot-performance/pom.xml b/spring-boot-performance/pom.xml index 8f4c08002d..5368377d36 100644 --- a/spring-boot-performance/pom.xml +++ b/spring-boot-performance/pom.xml @@ -5,7 +5,7 @@ spring-boot-performance spring-boot-performance war - This is a simple Spring Boot application taking advantage of the performance improvements introduced from version 2.2 + This is a simple Spring Boot application taking advantage of the latests Spring Boot improvements/features. Current version: 2.2 parent-boot-performance From d6bd06ddd99127b7dba6c13fcb24f288681b1020 Mon Sep 17 00:00:00 2001 From: Joel Juarez Date: Wed, 12 Jun 2019 23:23:21 +0200 Subject: [PATCH 08/44] fixed typos --- parent-boot-performance/README.md | 2 +- parent-boot-performance/pom.xml | 2 +- spring-boot-performance/pom.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/parent-boot-performance/README.md b/parent-boot-performance/README.md index e8eb056fe3..10775d9b00 100644 --- a/parent-boot-performance/README.md +++ b/parent-boot-performance/README.md @@ -1,3 +1,3 @@ -This is a parent module for projects taht want to take advantage of the latests Spring Boot improvements/features. +This is a parent module for projects taht want to take advantage of the latest Spring Boot improvements/features. Current version: Spring Boot 2.2 diff --git a/parent-boot-performance/pom.xml b/parent-boot-performance/pom.xml index 078f002968..0d39f0bb92 100644 --- a/parent-boot-performance/pom.xml +++ b/parent-boot-performance/pom.xml @@ -5,7 +5,7 @@ 0.0.1-SNAPSHOT parent-boot-performance pom - Parent for all modules taht want to take advantage of the latests Spring Boot improvements/features. Current version: 2.2 + Parent for all modules taht want to take advantage of the latest Spring Boot improvements/features. Current version: 2.2 com.baeldung diff --git a/spring-boot-performance/pom.xml b/spring-boot-performance/pom.xml index 5368377d36..207cd06f9b 100644 --- a/spring-boot-performance/pom.xml +++ b/spring-boot-performance/pom.xml @@ -5,7 +5,7 @@ spring-boot-performance spring-boot-performance war - This is a simple Spring Boot application taking advantage of the latests Spring Boot improvements/features. Current version: 2.2 + This is a simple Spring Boot application taking advantage of the latest Spring Boot improvements/features. Current version: 2.2 parent-boot-performance From 0ce2c744b367405985f6ff3c39ee21bdcb12c92f Mon Sep 17 00:00:00 2001 From: Joel Juarez Date: Wed, 12 Jun 2019 23:25:09 +0200 Subject: [PATCH 09/44] fixed typos --- parent-boot-performance/README.md | 2 +- parent-boot-performance/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/parent-boot-performance/README.md b/parent-boot-performance/README.md index 10775d9b00..24abd27048 100644 --- a/parent-boot-performance/README.md +++ b/parent-boot-performance/README.md @@ -1,3 +1,3 @@ -This is a parent module for projects taht want to take advantage of the latest Spring Boot improvements/features. +This is a parent module for projects that want to take advantage of the latest Spring Boot improvements/features. Current version: Spring Boot 2.2 diff --git a/parent-boot-performance/pom.xml b/parent-boot-performance/pom.xml index 0d39f0bb92..62a1689b7f 100644 --- a/parent-boot-performance/pom.xml +++ b/parent-boot-performance/pom.xml @@ -5,7 +5,7 @@ 0.0.1-SNAPSHOT parent-boot-performance pom - Parent for all modules taht want to take advantage of the latest Spring Boot improvements/features. Current version: 2.2 + Parent for all modules that want to take advantage of the latest Spring Boot improvements/features. Current version: 2.2 com.baeldung From 11a41d5036b2512635ef59c93c8f0c2d980d4df6 Mon Sep 17 00:00:00 2001 From: glopez Date: Thu, 13 Jun 2019 22:53:57 -0300 Subject: [PATCH 10/44] BAEL-2804 JPA Query Parameters Usage This is the code behind JPA Query Parameters Usage tutorial. Within these examples you can find the way to use named and positional query parameters either using plain jpql or criteria queries. --- persistence-modules/java-jpa/pom.xml | 57 ++++++++++++ .../baeldung/jpa/queryparams/Employee.java | 80 +++++++++++++++++ .../main/resources/META-INF/persistence.xml | 22 +++++ .../queryparams/JPAQueryParamsUnitTest.java | 90 +++++++++++++++++++ .../src/test/resources/employees2.sql | 2 + 5 files changed, 251 insertions(+) create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/queryparams/Employee.java create mode 100644 persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java create mode 100644 persistence-modules/java-jpa/src/test/resources/employees2.sql diff --git a/persistence-modules/java-jpa/pom.xml b/persistence-modules/java-jpa/pom.xml index f23040fbdc..51cc401332 100644 --- a/persistence-modules/java-jpa/pom.xml +++ b/persistence-modules/java-jpa/pom.xml @@ -19,6 +19,11 @@ hibernate-core ${hibernate.version} + + org.hibernate + hibernate-jpamodelgen + ${hibernate.version} + com.h2database h2 @@ -47,6 +52,58 @@ + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + -proc:none + + + + org.bsc.maven + maven-processor-plugin + 3.3.3 + + + process + + process + + generate-sources + + target/metamodel + + org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + generate-sources + + add-source + + + + target/metamodel + + + + + + + 5.4.0.Final 2.7.4-RC1 diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/queryparams/Employee.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/queryparams/Employee.java new file mode 100644 index 0000000000..e8f4a10156 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/queryparams/Employee.java @@ -0,0 +1,80 @@ +package com.baeldung.jpa.queryparams; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + + +@Entity +@Table(name = "employees") +public class Employee { + + /** + * + */ + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "employee_number", unique = true) + private String empNumber; + + @Column(name = "employee_name") + private String name; + + @Column(name = "employee_age") + private int age; + + public Employee() { + super(); + } + + public Employee(Long id, String empNumber) { + super(); + this.id = id; + this.empNumber = empNumber; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmpNumber() { + return empNumber; + } + + public void setEmpNumber(String empNumber) { + this.empNumber = empNumber; + } + + public static long getSerialversionuid() { + return serialVersionUID; + } + +} diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml index 1f16bee3ba..6a236f0840 100644 --- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml @@ -224,4 +224,26 @@ value="products_jpa.sql" /> + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.queryparams.Employee + true + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java new file mode 100644 index 0000000000..151a06a278 --- /dev/null +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java @@ -0,0 +1,90 @@ +package com.baeldung.jpa.queryparams; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.ParameterExpression; +import javax.persistence.criteria.Root; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * JPAQueryParamsTest class tests. + * + * @author gmlopez.mackinnon@gmail.com + */ +public class JPAQueryParamsUnitTest { + + private static EntityManager entityManager; + + @BeforeClass + public static void setup() { + EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-h2-queryparams"); + entityManager = factory.createEntityManager(); + } + + @Test + public void givenEmpNumber_whenUsingPositionalParameter_thenReturnExpectedEmployee() { + TypedQuery query = entityManager.createQuery( + "SELECT e FROM Employee e WHERE e.empNumber = ?0" , Employee.class); + String empNumber = "A123"; + Employee employee = query.setParameter(0, empNumber).getSingleResult(); + Assert.assertNotNull("Employee not found", employee); + } + + @Test + public void givenEmpNumber_whenUsingNamedParameter_thenReturnExpectedEmployee() { + TypedQuery query = entityManager.createQuery( + "SELECT e FROM Employee e WHERE e.empNumber = :number" , Employee.class); + String empNumber = "A123"; + Employee employee = query.setParameter("number", empNumber).getSingleResult(); + Assert.assertNotNull("Employee not found", employee); + } + + @Test + public void givenEmpNumber_whenUsingTwoNamedParameters_thenReturnExpectedEmployees() { + TypedQuery query = entityManager.createQuery( + "SELECT e FROM Employee e WHERE e.name = :name AND e.age = :empAge" , Employee.class); + String empName = "John Doe"; + int empAge = 55; + List employees = query + .setParameter("name", empName) + .setParameter("empAge", empAge) + .getResultList(); + Assert.assertNotNull("Employees not found!", employees); + Assert.assertTrue("Employees not found!", !employees.isEmpty()); + } + + @Test + public void givenEmpNumber_whenUsingCriteriaQuery_thenReturnExpectedEmployee() { + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + + CriteriaQuery cQuery = cb.createQuery(Employee.class); + Root c = cQuery.from(Employee.class); + ParameterExpression paramEmpNumber = cb.parameter(String.class); + cQuery.select(c).where(cb.equal(c.get(Employee_.empNumber), paramEmpNumber)); + + TypedQuery query = entityManager.createQuery(cQuery); + String empNumber = "A123"; + query.setParameter(paramEmpNumber, empNumber); + Employee employee = query.getSingleResult(); + Assert.assertNotNull("Employee not found!", employee); + } + + @Test + public void givenEmpNumber_whenUsingLiteral_thenReturnExpectedEmployee() { + String empNumber = "A123"; + TypedQuery query = entityManager.createQuery( + "SELECT e FROM Employee e WHERE e.empNumber = '" + empNumber + "'", Employee.class); + Employee employee = query.getSingleResult(); + Assert.assertNotNull("Employee not found!", employee); + } + +} diff --git a/persistence-modules/java-jpa/src/test/resources/employees2.sql b/persistence-modules/java-jpa/src/test/resources/employees2.sql new file mode 100644 index 0000000000..d3ae46f6a0 --- /dev/null +++ b/persistence-modules/java-jpa/src/test/resources/employees2.sql @@ -0,0 +1,2 @@ +INSERT INTO employees (employee_number, employee_name, employee_age) VALUES ('111', 'John Doe', 55); +INSERT INTO employees (employee_number, employee_name, employee_age) VALUES ('A123', 'John Doe Junior', 25); \ No newline at end of file From 97c1f79f32ebf9fff60efacc41a92ee4dff976be Mon Sep 17 00:00:00 2001 From: Andrew Shcherbakov Date: Sat, 15 Jun 2019 11:20:32 +0200 Subject: [PATCH 11/44] Implement illustration for the folding technique --- .../com/baeldung/folding/FoldingHash.java | 77 +++++++++++++++++++ .../baeldung/folding/FoldingHashUnitTest.java | 57 ++++++++++++++ 2 files changed, 134 insertions(+) create mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/folding/FoldingHash.java create mode 100644 core-java-modules/core-java-security/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/FoldingHash.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/FoldingHash.java new file mode 100644 index 0000000000..a04513ed55 --- /dev/null +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/FoldingHash.java @@ -0,0 +1,77 @@ +package com.baeldung.folding; + +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +/** + * Calculate a hash value for the strings using the folding technique. + * + * The implementation serves only to the illustration purposes and is far + * from being the most efficient. + * + * @author veontomo + * + */ +public class FoldingHash { + + /** + * Calculate the hash value of a given string + * @param str + * @param groupSize + * @param maxValue + * @return + */ + public int hash(String str, int groupSize, int maxValue) { + final int[] codes = this.toAsciiCodes(str); + return IntStream.range(0, str.length()) + .filter(i -> i % groupSize == 0) + .mapToObj(i -> extract(codes, i, groupSize)) + .map(block -> concatenate(block)) + .reduce(0, (a, b) -> (a + b) % maxValue); + } + + /** + * Returns a new array of given length whose elements are take from + * the original one starting from the offset. + * + * If the original array has not enough elements, the returning array will contain + * element from the offset till the end of the original array. + * + * @param numbers + * @param offset + * @param length + * @return + */ + public int[] extract(int[] numbers, int offset, int length) { + final int defect = numbers.length - (offset + length); + final int s = defect < 0 ? length + defect : length; + int[] result = new int[s]; + for (int index = 0; index < s; index++) { + result[index] = numbers[index + offset]; + } + return result; + } + + /** + * Concatenate the numbers into a single number. + * Assume that the procedure does not suffer from the overflow. + * @param numbers + * @return + */ + public int concatenate(int[] numbers) { + final String merged = IntStream.of(numbers) + .mapToObj(number -> "" + number) + .collect(Collectors.joining()); + return Integer.parseInt(merged, 10); + } + + /** + * Convert the string into its characters' ascii codes. + * @param str + * @return + */ + private int[] toAsciiCodes(String str) { + return str.chars() + .toArray(); + } +} diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java new file mode 100644 index 0000000000..b8e9adf435 --- /dev/null +++ b/core-java-modules/core-java-security/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.folding; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class FoldingHashUnitTest { + + @Test + public void givenStringJavaLanguage_whenSize2Capacity100000_then48933() throws Exception { + final FoldingHash hasher = new FoldingHash(); + final int value = hasher.hash("Java language", 2, 100_000); + assertEquals(value, 48933); + } + + + @Test + public void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception { + final FoldingHash hasher = new FoldingHash(); + final int java = hasher.hash("Java language", 2, 100_000); + final int vaja = hasher.hash("vaJa language", 2, 100_000); + assertTrue(java == vaja); + } + + + @Test + public void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception { + final FoldingHash hasher = new FoldingHash(); + final int[] value = hasher.extract(new int[] {5}, 0, 2); + assertArrayEquals(new int[] {5}, value); + } + + @Test + public void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception { + final FoldingHash hasher = new FoldingHash(); + final int[] value = hasher.extract(new int[] {1, 2, 3, 4, 5}, 0, 3); + assertArrayEquals(new int[] {1, 2, 3}, value); + } + + @Test + public void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception { + final FoldingHash hasher = new FoldingHash(); + final int[] value = hasher.extract(new int[] {1, 2, 3, 4, 5}, 1, 2); + assertArrayEquals(new int[] {2, 3}, value); + } + + @Test + public void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception { + final FoldingHash hasher = new FoldingHash(); + final int[] value = hasher.extract(new int[] {1, 2, 3, 4, 5}, 2, 2000); + assertArrayEquals(new int[] {3, 4, 5}, value); + } + + +} From 41502a75076abe89de6ca331fbc66209812a38d5 Mon Sep 17 00:00:00 2001 From: Andrew Shcherbakov Date: Sat, 15 Jun 2019 11:31:19 +0200 Subject: [PATCH 12/44] Clean the main method of the folding technique code snippet --- .../com/baeldung/folding/FoldingHash.java | 2 +- .../main/java/com/baeldung/folding/Main.java | 24 ++++++++----------- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/FoldingHash.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/FoldingHash.java index a04513ed55..3cb0d55ca7 100644 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/FoldingHash.java +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/FoldingHash.java @@ -9,7 +9,7 @@ import java.util.stream.IntStream; * The implementation serves only to the illustration purposes and is far * from being the most efficient. * - * @author veontomo + * @author A.Shcherbakov * */ public class FoldingHash { diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/Main.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/Main.java index 47ae11c80c..dec5b4850a 100644 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/Main.java +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/Main.java @@ -1,21 +1,17 @@ package com.baeldung.folding; -import java.util.stream.IntStream; - +/** + * Code snippet for article "A Guide to the Folding Technique". + * + * @author A.Shcherbakov + * + */ public class Main { public static void main(String... arg) { - final String key = "Java language"; - - toAsciiCodes(key).forEach(c -> System.out.println(c)); - // toAsciiCodes(key).reduce(new ArrayList(), (accum, i) -> i); - // List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - // numbers.stream() - // .reduce(new ArrayList(), (k, v) -> new ArrayList()); - // System.out.println(result); - } - - public static IntStream toAsciiCodes(String key) { - return key.chars(); + FoldingHash hasher = new FoldingHash(); + final String str = "Java language"; + System.out.println(hasher.hash(str, 2, 100_000)); + System.out.println(hasher.hash(str, 3, 1_000)); } } From 56984861789f4c2d194a41ac3e7aa55f13539ecb Mon Sep 17 00:00:00 2001 From: Andrew Shcherbakov Date: Sat, 15 Jun 2019 19:40:15 +0200 Subject: [PATCH 13/44] Add Javadoc to method arguments and format the code --- .../com/baeldung/folding/FoldingHash.java | 25 ++++++++--------- .../main/java/com/baeldung/folding/Main.java | 2 +- .../baeldung/folding/FoldingHashUnitTest.java | 27 +++++++++---------- 3 files changed, 26 insertions(+), 28 deletions(-) diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/FoldingHash.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/FoldingHash.java index 3cb0d55ca7..0ea128c1d9 100644 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/FoldingHash.java +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/FoldingHash.java @@ -15,11 +15,12 @@ import java.util.stream.IntStream; public class FoldingHash { /** - * Calculate the hash value of a given string - * @param str - * @param groupSize - * @param maxValue - * @return + * Calculate the hash value of a given string. + * + * @param str Assume it is not null + * @param groupSize the group size in the folding technique + * @param maxValue defines a max value that the hash may acquire (exclusive) + * @return integer value from 0 (inclusive) to maxValue (exclusive) */ public int hash(String str, int groupSize, int maxValue) { final int[] codes = this.toAsciiCodes(str); @@ -37,9 +38,9 @@ public class FoldingHash { * If the original array has not enough elements, the returning array will contain * element from the offset till the end of the original array. * - * @param numbers - * @param offset - * @param length + * @param numbers original array. Assume it is not null. + * @param offset index of the element to start from. Assume it is less than the size of the array + * @param length max size of the resulting array * @return */ public int[] extract(int[] numbers, int offset, int length) { @@ -53,9 +54,9 @@ public class FoldingHash { } /** - * Concatenate the numbers into a single number. + * Concatenate the numbers into a single number as if they were strings. * Assume that the procedure does not suffer from the overflow. - * @param numbers + * @param numbers integers to concatenate * @return */ public int concatenate(int[] numbers) { @@ -66,8 +67,8 @@ public class FoldingHash { } /** - * Convert the string into its characters' ascii codes. - * @param str + * Convert the string into its characters' ASCII codes. + * @param str input string * @return */ private int[] toAsciiCodes(String str) { diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/Main.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/Main.java index dec5b4850a..3b055a0dbe 100644 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/Main.java +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/Main.java @@ -7,11 +7,11 @@ package com.baeldung.folding; * */ public class Main { + public static void main(String... arg) { FoldingHash hasher = new FoldingHash(); final String str = "Java language"; System.out.println(hasher.hash(str, 2, 100_000)); System.out.println(hasher.hash(str, 3, 1_000)); } - } diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java index b8e9adf435..43e33d8378 100644 --- a/core-java-modules/core-java-security/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java +++ b/core-java-modules/core-java-security/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java @@ -14,44 +14,41 @@ public class FoldingHashUnitTest { final int value = hasher.hash("Java language", 2, 100_000); assertEquals(value, 48933); } - - + @Test public void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception { final FoldingHash hasher = new FoldingHash(); final int java = hasher.hash("Java language", 2, 100_000); final int vaja = hasher.hash("vaJa language", 2, 100_000); assertTrue(java == vaja); - } - + } @Test public void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception { final FoldingHash hasher = new FoldingHash(); - final int[] value = hasher.extract(new int[] {5}, 0, 2); - assertArrayEquals(new int[] {5}, value); + final int[] value = hasher.extract(new int[] { 5 }, 0, 2); + assertArrayEquals(new int[] { 5 }, value); } - + @Test public void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception { final FoldingHash hasher = new FoldingHash(); - final int[] value = hasher.extract(new int[] {1, 2, 3, 4, 5}, 0, 3); - assertArrayEquals(new int[] {1, 2, 3}, value); + final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 0, 3); + assertArrayEquals(new int[] { 1, 2, 3 }, value); } @Test public void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception { final FoldingHash hasher = new FoldingHash(); - final int[] value = hasher.extract(new int[] {1, 2, 3, 4, 5}, 1, 2); - assertArrayEquals(new int[] {2, 3}, value); + final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 1, 2); + assertArrayEquals(new int[] { 2, 3 }, value); } @Test public void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception { final FoldingHash hasher = new FoldingHash(); - final int[] value = hasher.extract(new int[] {1, 2, 3, 4, 5}, 2, 2000); - assertArrayEquals(new int[] {3, 4, 5}, value); + final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 2, 2000); + assertArrayEquals(new int[] { 3, 4, 5 }, value); } - - + } From 6aec4a6e0f5c92e1becc0a0d26d88b3ad57aeaa1 Mon Sep 17 00:00:00 2001 From: glopez Date: Sun, 16 Jun 2019 00:37:44 -0300 Subject: [PATCH 14/44] BAEL-2804 JPA Query Parameters Usage This is the code behind the JPA Query Parameters Usage tutorial. Within these examples you can find the way to use named and positional query parameters either using plain JPQL or criteria queries. --- .../queryparams/JPAQueryParamsUnitTest.java | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java index 151a06a278..fcac6415c9 100644 --- a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java @@ -1,5 +1,7 @@ package com.baeldung.jpa.queryparams; +import java.util.Arrays; +import java.util.Collections; import java.util.List; import javax.persistence.EntityManager; @@ -33,12 +35,22 @@ public class JPAQueryParamsUnitTest { @Test public void givenEmpNumber_whenUsingPositionalParameter_thenReturnExpectedEmployee() { TypedQuery query = entityManager.createQuery( - "SELECT e FROM Employee e WHERE e.empNumber = ?0" , Employee.class); + "SELECT e FROM Employee e WHERE e.empNumber = ?1" , Employee.class); String empNumber = "A123"; Employee employee = query.setParameter(0, empNumber).getSingleResult(); Assert.assertNotNull("Employee not found", employee); } + @Test + public void givenEmpNumberList_whenUsingPositionalParameter_thenReturnExpectedEmployee() { + TypedQuery query = entityManager.createQuery( + "SELECT e FROM Employee e WHERE e.empNumber IN (?1)" , Employee.class); + List empNumbers = Arrays.asList("A123", "A124"); + List employees = query.setParameter(1, empNumbers).getResultList(); + Assert.assertNotNull("Employees not found", employees); + Assert.assertFalse("Employees not found", employees.isEmpty()); + } + @Test public void givenEmpNumber_whenUsingNamedParameter_thenReturnExpectedEmployee() { TypedQuery query = entityManager.createQuery( @@ -49,7 +61,17 @@ public class JPAQueryParamsUnitTest { } @Test - public void givenEmpNumber_whenUsingTwoNamedParameters_thenReturnExpectedEmployees() { + public void givenEmpNumberList_whenUsingNamedParameter_thenReturnExpectedEmployee() { + TypedQuery query = entityManager.createQuery( + "SELECT e FROM Employee e WHERE e.empNumber IN (:numbers)" , Employee.class); + List empNumbers = Arrays.asList("A123", "A124"); + List employees = query.setParameter("numbers", empNumbers).getResultList(); + Assert.assertNotNull("Employees not found", employees); + Assert.assertFalse("Employees not found", employees.isEmpty()); + } + + @Test + public void givenEmpNameAndEmpAge_whenUsingTwoNamedParameters_thenReturnExpectedEmployees() { TypedQuery query = entityManager.createQuery( "SELECT e FROM Employee e WHERE e.name = :name AND e.age = :empAge" , Employee.class); String empName = "John Doe"; From 1d52e33e2db33e9a1450f3dbd246cfa315810cab Mon Sep 17 00:00:00 2001 From: Erhan KARAKAYA Date: Sun, 16 Jun 2019 09:31:29 +0300 Subject: [PATCH 15/44] Added tests & renamed classes --- ...va => BingTranslationServiceProvider.java} | 4 +-- ... => GoogleTranslationServiceProvider.java} | 4 +-- ...teService.java => TranslationService.java} | 2 +- .../TranslationServiceUnitTest.java | 34 +++++++++++++++++++ 4 files changed, 39 insertions(+), 5 deletions(-) rename autovalue/src/main/java/com/baeldung/autoservice/{BingTranslateServiceProvider.java => BingTranslationServiceProvider.java} (65%) rename autovalue/src/main/java/com/baeldung/autoservice/{GoogleTranslateServiceProvider.java => GoogleTranslationServiceProvider.java} (65%) rename autovalue/src/main/java/com/baeldung/autoservice/{TranslateService.java => TranslationService.java} (76%) create mode 100644 autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java diff --git a/autovalue/src/main/java/com/baeldung/autoservice/BingTranslateServiceProvider.java b/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java similarity index 65% rename from autovalue/src/main/java/com/baeldung/autoservice/BingTranslateServiceProvider.java rename to autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java index 00f21a943e..74666b2f7d 100644 --- a/autovalue/src/main/java/com/baeldung/autoservice/BingTranslateServiceProvider.java +++ b/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java @@ -4,8 +4,8 @@ import com.google.auto.service.AutoService; import java.util.Locale; -@AutoService(TranslateService.class) -public class BingTranslateServiceProvider implements TranslateService { +@AutoService(TranslationService.class) +public class BingTranslationServiceProvider implements TranslationService { public String translate(String message, Locale from, Locale to) { return "translated by Bing"; diff --git a/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslateServiceProvider.java b/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java similarity index 65% rename from autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslateServiceProvider.java rename to autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java index 786d9bd443..68889472bf 100644 --- a/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslateServiceProvider.java +++ b/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java @@ -4,8 +4,8 @@ import com.google.auto.service.AutoService; import java.util.Locale; -@AutoService(TranslateService.class) -public class GoogleTranslateServiceProvider implements TranslateService { +@AutoService(TranslationService.class) +public class GoogleTranslationServiceProvider implements TranslationService { public String translate(String message, Locale from, Locale to) { return "translated by Google"; diff --git a/autovalue/src/main/java/com/baeldung/autoservice/TranslateService.java b/autovalue/src/main/java/com/baeldung/autoservice/TranslationService.java similarity index 76% rename from autovalue/src/main/java/com/baeldung/autoservice/TranslateService.java rename to autovalue/src/main/java/com/baeldung/autoservice/TranslationService.java index 6d68f6aca3..cfcff4015c 100644 --- a/autovalue/src/main/java/com/baeldung/autoservice/TranslateService.java +++ b/autovalue/src/main/java/com/baeldung/autoservice/TranslationService.java @@ -2,7 +2,7 @@ package com.baeldung.autoservice; import java.util.Locale; -public interface TranslateService { +public interface TranslationService { String translate(String message, Locale from, Locale to); } diff --git a/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java b/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java new file mode 100644 index 0000000000..f167dad6bd --- /dev/null +++ b/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.autoservice; + +import com.baeldung.autoservice.TranslationService; +import org.junit.Test; + +import java.util.ServiceLoader; +import java.util.stream.StreamSupport; + +import static org.junit.Assert.assertEquals; + +public class TranslationServiceUnitTest { + + @Test + public void whenServiceLoaderLoads_thenLoadsAllProviders() { + + ServiceLoader loader = ServiceLoader.load(TranslationService.class); + long count = StreamSupport.stream(loader.spliterator(), false).count(); + assertEquals(2, count); + } + + @Test + public void whenServiceLoaderLoadsGoogleService_thenGoogleIsLoaded() { + + ServiceLoader loader = ServiceLoader.load(TranslationService.class); + + TranslationService googleService = StreamSupport.stream(loader.spliterator(), false) + .filter(p -> p.getClass().getSimpleName().equals("GoogleTranslationServiceProvider")) + .findFirst() + .get(); + + assertEquals("translated by Google", googleService.translate("message", null, null)); + + } +} \ No newline at end of file From f69f95d13d2a4a6b095e351ca1ea872d54b0a809 Mon Sep 17 00:00:00 2001 From: Joel Juarez Date: Sun, 16 Jun 2019 23:23:36 +0200 Subject: [PATCH 16/44] fixed styles in pom.xml --- parent-boot-performance/README.md | 4 +-- parent-boot-performance/pom.xml | 54 +++++++++++++++---------------- spring-boot-performance/pom.xml | 12 +++---- 3 files changed, 34 insertions(+), 36 deletions(-) diff --git a/parent-boot-performance/README.md b/parent-boot-performance/README.md index 24abd27048..fce9e101da 100644 --- a/parent-boot-performance/README.md +++ b/parent-boot-performance/README.md @@ -1,3 +1 @@ -This is a parent module for projects that want to take advantage of the latest Spring Boot improvements/features. - -Current version: Spring Boot 2.2 +This is a parent module for projects that want to take advantage of the latest Spring Boot improvements/features. \ No newline at end of file diff --git a/parent-boot-performance/pom.xml b/parent-boot-performance/pom.xml index 62a1689b7f..b1c6854eae 100644 --- a/parent-boot-performance/pom.xml +++ b/parent-boot-performance/pom.xml @@ -3,7 +3,7 @@ 4.0.0 parent-boot-performance 0.0.1-SNAPSHOT - parent-boot-performance + parent-boot-performance pom Parent for all modules that want to take advantage of the latest Spring Boot improvements/features. Current version: 2.2 @@ -13,7 +13,14 @@ 1.0.0-SNAPSHOT - + + 3.1.0 + + 1.0.21.RELEASE + 2.2.0.M3 + + + org.springframework.boot @@ -36,30 +43,30 @@ - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - ${start-class} - - - - - - - - + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + ${start-class} + + + + + + + + spring-milestones Spring Milestones https://repo.spring.io/milestone - + thin-jar @@ -81,11 +88,4 @@ - - - 3.1.0 - - 1.0.21.RELEASE - 2.2.0.M3 - diff --git a/spring-boot-performance/pom.xml b/spring-boot-performance/pom.xml index 207cd06f9b..bbee7493cc 100644 --- a/spring-boot-performance/pom.xml +++ b/spring-boot-performance/pom.xml @@ -14,7 +14,12 @@ ../parent-boot-performance - + + + com.baeldung.lazyinitialization.Application + + + org.springframework.boot spring-boot-starter @@ -37,9 +42,4 @@ - - - - com.baeldung.lazyinitialization.Application - \ No newline at end of file From 44dfb1a07679d768d8a067d2b58c4545d437a64a Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Mon, 17 Jun 2019 00:00:29 +0100 Subject: [PATCH 17/44] BAEL-2934 IntStreams conversions (cherry picked from commit 11abb325ecb2f299c318d82952e7718bab03510c) --- .../IntStreamsConversionsUnitTest.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 java-streams/src/test/java/com/baeldung/intstreams/conversion/IntStreamsConversionsUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/intstreams/conversion/IntStreamsConversionsUnitTest.java b/java-streams/src/test/java/com/baeldung/intstreams/conversion/IntStreamsConversionsUnitTest.java new file mode 100644 index 0000000000..88579cd97c --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/intstreams/conversion/IntStreamsConversionsUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.intstreams.conversion; + +import org.junit.Test; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import static org.assertj.core.api.Assertions.assertThat; + +public class IntStreamsConversionsUnitTest { + + @Test + public void intStreamToArray() { + int[] first50EvenNumbers = IntStream.iterate(0, i -> i + 2) + .limit(50) + .toArray(); + + assertThat(first50EvenNumbers).hasSize(50); + assertThat(first50EvenNumbers[2]).isEqualTo(4); + } + + @Test + public void intStreamToList() { + List first50IntegerNumbers = IntStream.range(0, 50) + .boxed() + .collect(Collectors.toList()); + + assertThat(first50IntegerNumbers).hasSize(50); + assertThat(first50IntegerNumbers.get(2)).isEqualTo(2); + } + + @Test + public void intStreamToString() { + String first3numbers = IntStream.range(0, 3) + .mapToObj(String::valueOf) + .collect(Collectors.joining(", ", "[", "]")); + + assertThat(first3numbers).isEqualTo("[0, 1, 2]"); + } +} From 07adfc9e7037774c0fb0c7a26768b8b17df1d2df Mon Sep 17 00:00:00 2001 From: glopez Date: Mon, 17 Jun 2019 07:42:48 -0300 Subject: [PATCH 18/44] BAEL-2804 JPA Query Parameters Usage Fix givenEmpNumber_whenUsingPositionalParameter_thenReturnExpectedEmployee test case after adjustemnts. --- .../com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java index fcac6415c9..97f82f7914 100644 --- a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java @@ -37,7 +37,7 @@ public class JPAQueryParamsUnitTest { TypedQuery query = entityManager.createQuery( "SELECT e FROM Employee e WHERE e.empNumber = ?1" , Employee.class); String empNumber = "A123"; - Employee employee = query.setParameter(0, empNumber).getSingleResult(); + Employee employee = query.setParameter(1, empNumber).getSingleResult(); Assert.assertNotNull("Employee not found", employee); } From 2826baee3b6395a1c84729c470da5f18de37ba7b Mon Sep 17 00:00:00 2001 From: Erhan Karakaya Date: Mon, 17 Jun 2019 14:52:29 +0300 Subject: [PATCH 19/44] Changed sample impls & refactored test --- .../BingTranslationServiceProvider.java | 4 ++- .../GoogleTranslationServiceProvider.java | 4 ++- .../TranslationServiceUnitTest.java | 29 +++++++++++-------- 3 files changed, 23 insertions(+), 14 deletions(-) diff --git a/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java b/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java index 74666b2f7d..0aed76b834 100644 --- a/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java +++ b/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java @@ -8,6 +8,8 @@ import java.util.Locale; public class BingTranslationServiceProvider implements TranslationService { public String translate(String message, Locale from, Locale to) { - return "translated by Bing"; + + // implementation details + return message + " (translated by Bing)"; } } diff --git a/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java b/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java index 68889472bf..eb5d191a26 100644 --- a/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java +++ b/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java @@ -8,6 +8,8 @@ import java.util.Locale; public class GoogleTranslationServiceProvider implements TranslationService { public String translate(String message, Locale from, Locale to) { - return "translated by Google"; + + // implementation details + return message + " (translated by Google)"; } } diff --git a/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java b/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java index f167dad6bd..2f39a306c2 100644 --- a/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java +++ b/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java @@ -9,26 +9,31 @@ import java.util.stream.StreamSupport; import static org.junit.Assert.assertEquals; public class TranslationServiceUnitTest { + + private ServiceLoader loader; + + @Before + public void setUp() { + + loader = ServiceLoader.load(TranslationService.class); + } @Test public void whenServiceLoaderLoads_thenLoadsAllProviders() { - ServiceLoader loader = ServiceLoader.load(TranslationService.class); - long count = StreamSupport.stream(loader.spliterator(), false).count(); - assertEquals(2, count); + long count = StreamSupport.stream(loader.spliterator(), false).count(); + assertEquals(2, count); } @Test public void whenServiceLoaderLoadsGoogleService_thenGoogleIsLoaded() { - ServiceLoader loader = ServiceLoader.load(TranslationService.class); - - TranslationService googleService = StreamSupport.stream(loader.spliterator(), false) - .filter(p -> p.getClass().getSimpleName().equals("GoogleTranslationServiceProvider")) - .findFirst() - .get(); - - assertEquals("translated by Google", googleService.translate("message", null, null)); - + TranslationService googleService = StreamSupport.stream(loader.spliterator(), false) + .filter(p -> p.getClass().getSimpleName().equals("GoogleTranslationServiceProvider")) + .findFirst() + .get(); + + String message = "message"; + assertEquals(message + " (translated by Google)", googleService.translate(message, null, null)); } } \ No newline at end of file From ac850bbc0b39ee45b3b93010e02c3d7ba0b9aa0b Mon Sep 17 00:00:00 2001 From: Erhan Karakaya Date: Mon, 17 Jun 2019 14:57:45 +0300 Subject: [PATCH 20/44] Fixed typos --- .../baeldung/autoservice/BingTranslationServiceProvider.java | 2 +- .../baeldung/autoservice/GoogleTranslationServiceProvider.java | 2 +- .../com/baeldung/autoservice/TranslationServiceUnitTest.java | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java b/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java index 0aed76b834..8ef4d6a45e 100644 --- a/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java +++ b/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java @@ -9,7 +9,7 @@ public class BingTranslationServiceProvider implements TranslationService { public String translate(String message, Locale from, Locale to) { - // implementation details + // implementation details return message + " (translated by Bing)"; } } diff --git a/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java b/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java index eb5d191a26..3d6d1edc9f 100644 --- a/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java +++ b/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java @@ -9,7 +9,7 @@ public class GoogleTranslationServiceProvider implements TranslationService { public String translate(String message, Locale from, Locale to) { - // implementation details + // implementation details return message + " (translated by Google)"; } } diff --git a/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java b/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java index 2f39a306c2..2d7c8d7b6d 100644 --- a/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java +++ b/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.autoservice; import com.baeldung.autoservice.TranslationService; +import org.junit.Before; import org.junit.Test; import java.util.ServiceLoader; From 7c21f2e2794cb133c3620515e05a93fa147a22a7 Mon Sep 17 00:00:00 2001 From: antmordel Date: Tue, 18 Jun 2019 08:25:42 +0200 Subject: [PATCH 21/44] Added IntStream.of constructor --- .../intstreams/conversion/IntStreamsConversionsUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java-streams/src/test/java/com/baeldung/intstreams/conversion/IntStreamsConversionsUnitTest.java b/java-streams/src/test/java/com/baeldung/intstreams/conversion/IntStreamsConversionsUnitTest.java index 88579cd97c..6cd773e634 100644 --- a/java-streams/src/test/java/com/baeldung/intstreams/conversion/IntStreamsConversionsUnitTest.java +++ b/java-streams/src/test/java/com/baeldung/intstreams/conversion/IntStreamsConversionsUnitTest.java @@ -31,7 +31,7 @@ public class IntStreamsConversionsUnitTest { @Test public void intStreamToString() { - String first3numbers = IntStream.range(0, 3) + String first3numbers = IntStream.of(0, 1, 2) .mapToObj(String::valueOf) .collect(Collectors.joining(", ", "[", "]")); From 9edcaa30d5b7619cf1dd649c5601208f3363fb03 Mon Sep 17 00:00:00 2001 From: Andrew Shcherbakov Date: Tue, 18 Jun 2019 21:22:13 +0200 Subject: [PATCH 22/44] Move the code into algorithms-miscellaneous-3 --- .../src/main/java/com/baeldung/folding/FoldingHash.java | 0 .../src/main/java/com/baeldung/folding/Main.java | 0 .../src/test/java/com/baeldung/folding/FoldingHashUnitTest.java | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {core-java-modules/core-java-security => algorithms-miscellaneous-3}/src/main/java/com/baeldung/folding/FoldingHash.java (100%) rename {core-java-modules/core-java-security => algorithms-miscellaneous-3}/src/main/java/com/baeldung/folding/Main.java (100%) rename {core-java-modules/core-java-security => algorithms-miscellaneous-3}/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java (100%) diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/FoldingHash.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/folding/FoldingHash.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/folding/FoldingHash.java rename to algorithms-miscellaneous-3/src/main/java/com/baeldung/folding/FoldingHash.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/folding/Main.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/folding/Main.java similarity index 100% rename from core-java-modules/core-java-security/src/main/java/com/baeldung/folding/Main.java rename to algorithms-miscellaneous-3/src/main/java/com/baeldung/folding/Main.java diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java similarity index 100% rename from core-java-modules/core-java-security/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java rename to algorithms-miscellaneous-3/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java From 548890541cf2e44ef5ecd1a382e0591689c86d25 Mon Sep 17 00:00:00 2001 From: cscib Date: Tue, 18 Jun 2019 22:35:04 +0200 Subject: [PATCH 23/44] Bael 2434 (#6635) * BAEL-2434 * BAEL-2434 * Minor alterations to reflect changes in the article * Fixing Spel expression and removing extra code that is not referenced anymore in the article * Moved the files from spring-core to spring-static-resources. Renamed ResourceUtil to ResourceReader. * Changes due to change of article outline. * Changes due to change of article outline. * Removing Converter from article --- spring-static-resources/pom.xml | 10 ++++ .../LoadResourceConfig.java | 15 +++++ .../loadresourceasstring/ResourceReader.java | 30 ++++++++++ .../src/main/resources/resource.txt | 1 + .../LoadResourceAsStringIntegrationTest.java | 57 +++++++++++++++++++ 5 files changed, 113 insertions(+) create mode 100644 spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/LoadResourceConfig.java create mode 100644 spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/ResourceReader.java create mode 100644 spring-static-resources/src/main/resources/resource.txt create mode 100644 spring-static-resources/src/test/java/com/baeldung/loadresourceasstring/LoadResourceAsStringIntegrationTest.java diff --git a/spring-static-resources/pom.xml b/spring-static-resources/pom.xml index f01e807919..84519a37c1 100644 --- a/spring-static-resources/pom.xml +++ b/spring-static-resources/pom.xml @@ -140,6 +140,13 @@ handlebars ${handlebars.version} + + + + commons-io + commons-io + ${commons.io.version} + org.springframework @@ -208,6 +215,9 @@ 1.5.1 + + + 2.5 \ No newline at end of file diff --git a/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/LoadResourceConfig.java b/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/LoadResourceConfig.java new file mode 100644 index 0000000000..32b9ba84d0 --- /dev/null +++ b/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/LoadResourceConfig.java @@ -0,0 +1,15 @@ +package com.baeldung.loadresourceasstring; + + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class LoadResourceConfig { + + @Bean + public String resourceString() { + return ResourceReader.readFileToString("resource.txt"); + } + +} diff --git a/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/ResourceReader.java b/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/ResourceReader.java new file mode 100644 index 0000000000..7bc1babe91 --- /dev/null +++ b/spring-static-resources/src/main/java/com/baeldung/loadresourceasstring/ResourceReader.java @@ -0,0 +1,30 @@ +package com.baeldung.loadresourceasstring; + +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.util.FileCopyUtils; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.UncheckedIOException; + +import static java.nio.charset.StandardCharsets.UTF_8; + + +public class ResourceReader { + + public static String readFileToString(String path) { + ResourceLoader resourceLoader = new DefaultResourceLoader(); + Resource resource = resourceLoader.getResource(path); + return asString(resource); + } + + public static String asString(Resource resource) { + try (Reader reader = new InputStreamReader(resource.getInputStream(), UTF_8)) { + return FileCopyUtils.copyToString(reader); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/spring-static-resources/src/main/resources/resource.txt b/spring-static-resources/src/main/resources/resource.txt new file mode 100644 index 0000000000..e78cfa90c2 --- /dev/null +++ b/spring-static-resources/src/main/resources/resource.txt @@ -0,0 +1 @@ +This is a resource text file. This file will be loaded as a resource and use its contents as a string. \ No newline at end of file diff --git a/spring-static-resources/src/test/java/com/baeldung/loadresourceasstring/LoadResourceAsStringIntegrationTest.java b/spring-static-resources/src/test/java/com/baeldung/loadresourceasstring/LoadResourceAsStringIntegrationTest.java new file mode 100644 index 0000000000..c16c1a9720 --- /dev/null +++ b/spring-static-resources/src/test/java/com/baeldung/loadresourceasstring/LoadResourceAsStringIntegrationTest.java @@ -0,0 +1,57 @@ +package com.baeldung.loadresourceasstring; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.convert.converter.Converter; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.util.FileCopyUtils; + +import java.io.InputStreamReader; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = LoadResourceConfig.class) +public class LoadResourceAsStringIntegrationTest { + + private static final String EXPECTED_RESOURCE_VALUE = "This is a resource text file. This file will be loaded as a " + "resource and use its contents as a string."; + + @Value("#{T(com.baeldung.loadresourceasstring.ResourceReader).readFileToString('classpath:resource.txt')}") + private String resourceStringUsingSpel; + + @Autowired + @Qualifier("resourceString") + private String resourceString; + + @Autowired + private ResourceLoader resourceLoader; + + @Test + public void givenUsingResourceLoadAndFileCopyUtils_whenConvertingAResourceToAString_thenCorrect() { + Resource resource = resourceLoader.getResource("classpath:resource.txt"); + assertEquals(EXPECTED_RESOURCE_VALUE, ResourceReader.asString(resource)); + } + + @Test + public void givenUsingResourceStringBean_whenConvertingAResourceToAString_thenCorrect() { + assertEquals(EXPECTED_RESOURCE_VALUE, resourceString); + } + + @Test + public void givenUsingSpel_whenConvertingAResourceToAString_thenCorrect() { + assertEquals(EXPECTED_RESOURCE_VALUE, resourceStringUsingSpel); + } + + + + +} From c253f224bcb48fefcf726c00d895106304367856 Mon Sep 17 00:00:00 2001 From: Balaji Sivakumar <20585178+balaji13us@users.noreply.github.com> Date: Wed, 19 Jun 2019 10:13:19 +0530 Subject: [PATCH 24/44] BAEL-3022 - Converting Iterator to List (#7109) * BAEL-3022 - Converting Iterator to List * BAEL-3022 - Converting Iterator to List. Removed Service Class and moved logic to Junit class * BAEL-3022 - Converting Iterator to List Code Formatting. --- .../ConvertIteratorToListServiceUnitTest.java | 100 ++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java new file mode 100644 index 0000000000..4d6cba7d27 --- /dev/null +++ b/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java @@ -0,0 +1,100 @@ +package com.baeldung.convertiteratortolist; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import org.apache.commons.collections4.IteratorUtils; +import org.junit.Before; +import org.junit.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; + +public class ConvertIteratorToListServiceUnitTest { + + Iterator iterator; + + @Before + public void setUp() throws Exception { + iterator = Arrays.asList(1, 2, 3) + .iterator(); + } + + @Test + public void givenAnIterator_whenConvertIteratorToListUsingWhileLoop_thenReturnAList() { + + List actualList = new ArrayList(); + + // Convert Iterator to List using while loop dsf + while (iterator.hasNext()) { + actualList.add(iterator.next()); + } + + assertThat(actualList, hasSize(3)); + assertThat(actualList, containsInAnyOrder(1, 2, 3)); + } + + @Test + public void givenAnIterator_whenConvertIteratorToListAfterJava8_thenReturnAList() { + List actualList = new ArrayList(); + + // Convert Iterator to List using Java 8 + iterator.forEachRemaining(actualList::add); + + assertThat(actualList, hasSize(3)); + assertThat(actualList, containsInAnyOrder(1, 2, 3)); + } + + @Test + public void givenAnIterator_whenConvertIteratorToListJava8Stream_thenReturnAList() { + + // Convert iterator to iterable + Iterable iterable = () -> iterator; + + // Extract List from stream + List actualList = StreamSupport + .stream(iterable.spliterator(), false) + .collect(Collectors.toList()); + + assertThat(actualList, hasSize(3)); + assertThat(actualList, containsInAnyOrder(1, 2, 3)); + } + + @Test + public void givenAnIterator_whenConvertIteratorToImmutableListWithGuava_thenReturnAList() { + + // Convert Iterator to an Immutable list using Guava library in Java + List actualList = ImmutableList.copyOf(iterator); + + assertThat(actualList, hasSize(3)); + assertThat(actualList, containsInAnyOrder(1, 2, 3)); + } + + @Test + public void givenAnIterator_whenConvertIteratorToMutableListWithGuava_thenReturnAList() { + + // Convert Iterator to a mutable list using Guava library in Java + List actualList = Lists.newArrayList(iterator); + + assertThat(actualList, hasSize(3)); + assertThat(actualList, containsInAnyOrder(1, 2, 3)); + } + + @Test + public void givenAnIterator_whenConvertIteratorToMutableListWithApacheCommons_thenReturnAList() { + + // Convert Iterator to a mutable list using Apache Commons library in Java + List actualList = IteratorUtils.toList(iterator); + + assertThat(actualList, hasSize(3)); + assertThat(actualList, containsInAnyOrder(1, 2, 3)); + } +} From 0b13fdf96cff9d01d644fdcc547e388caefea05b Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Wed, 19 Jun 2019 10:54:19 +0300 Subject: [PATCH 25/44] BAEL-773 - Ratpack with Groovy (#6985) * BAEL-773 - Ratpack with Groovy * BAEL-773 - Ratpack with Groovy - PR review changes * BAEL-773 - Ratpack with Groovy - PR review changes * Typo corrected * SQLs capitalised --- ratpack/build.gradle | 2 + ratpack/pom.xml | 13 +++- .../main/groovy/com/baeldung/Ratpack.groovy | 76 +++++++++++++++++++ .../com/baeldung/RatpackGroovyApp.groovy | 12 +++ .../groovy/com/baeldung/model/User.groovy | 9 +++ ratpack/src/main/resources/User.sql | 10 +++ .../com/baeldung/RatpackGroovySpec.groovy | 46 +++++++++++ 7 files changed, 167 insertions(+), 1 deletion(-) create mode 100644 ratpack/src/main/groovy/com/baeldung/Ratpack.groovy create mode 100644 ratpack/src/main/groovy/com/baeldung/RatpackGroovyApp.groovy create mode 100644 ratpack/src/main/groovy/com/baeldung/model/User.groovy create mode 100644 ratpack/src/main/resources/User.sql create mode 100644 ratpack/src/test/groovy/com/baeldung/RatpackGroovySpec.groovy diff --git a/ratpack/build.gradle b/ratpack/build.gradle index 25af3ddb51..c997b4e697 100644 --- a/ratpack/build.gradle +++ b/ratpack/build.gradle @@ -14,6 +14,8 @@ if (!JavaVersion.current().java8Compatible) { apply plugin: "io.ratpack.ratpack-java" apply plugin: 'java' +apply plugin: 'groovy' +apply plugin: 'io.ratpack.ratpack-groovy' repositories { jcenter() diff --git a/ratpack/pom.xml b/ratpack/pom.xml index 7c145eff91..0df313c05e 100644 --- a/ratpack/pom.xml +++ b/ratpack/pom.xml @@ -26,11 +26,21 @@ ratpack-core ${ratpack.version} + + org.codehaus.groovy + groovy-sql + ${groovy.sql.version} + io.ratpack ratpack-hikari ${ratpack.version} + + io.ratpack + ratpack-groovy-test + ${ratpack.test.latest.version} + io.ratpack ratpack-hystrix @@ -91,6 +101,7 @@ 4.5.3 4.4.6 1.5.12 + 2.4.15 + 1.6.1 - diff --git a/ratpack/src/main/groovy/com/baeldung/Ratpack.groovy b/ratpack/src/main/groovy/com/baeldung/Ratpack.groovy new file mode 100644 index 0000000000..4d8814b627 --- /dev/null +++ b/ratpack/src/main/groovy/com/baeldung/Ratpack.groovy @@ -0,0 +1,76 @@ +package com.baeldung; + +@Grab('io.ratpack:ratpack-groovy:1.6.1') +import static ratpack.groovy.Groovy.ratpack + +import com.baeldung.model.User +import com.google.common.reflect.TypeToken +import ratpack.exec.Promise +import ratpack.handling.Context +import ratpack.jackson.Jackson +import groovy.sql.Sql +import java.sql.Connection +import java.sql.PreparedStatement +import java.sql.ResultSet +import ratpack.hikari.HikariModule +import javax.sql.DataSource; + +ratpack { + serverConfig { port(5050) } + bindings { + module(HikariModule) { config -> + config.dataSourceClassName = 'org.h2.jdbcx.JdbcDataSource' + config.addDataSourceProperty('URL', "jdbc:h2:mem:devDB;INIT=RUNSCRIPT FROM 'classpath:/User.sql'") + } + } + + handlers { + + get { render 'Hello World from Ratpack with Groovy!!' } + + get("greet/:name") { Context ctx -> + render "Hello " + ctx.getPathTokens().get("name") + "!!!" + } + + get("data") { + render Jackson.json([title: "Mr", name: "Norman", country: "USA"]) + } + + post("user") { + Promise user = parse(Jackson.fromJson(User)) + user.then { u -> render u.name } + } + + get('fetchUserName/:id') { Context ctx -> + Connection connection = ctx.get(DataSource.class).getConnection() + PreparedStatement queryStatement = connection.prepareStatement("SELECT NAME FROM USER WHERE ID=?") + queryStatement.setInt(1, Integer.parseInt(ctx.getPathTokens().get("id"))) + ResultSet resultSet = queryStatement.executeQuery() + resultSet.next() + render resultSet.getString(1) + } + + get('fetchUsers') { + def db = [url:'jdbc:h2:mem:devDB'] + def sql = Sql.newInstance(db.url, db.user, db.password) + def users = sql.rows("SELECT * FROM USER"); + render(Jackson.json(users)) + } + + post('addUser') { + parse(Jackson.fromJson(User)) + .then { u -> + def db = [url:'jdbc:h2:mem:devDB'] + Sql sql = Sql.newInstance(db.url, db.user, db.password) + sql.executeInsert("INSERT INTO USER VALUES (?,?,?,?)", [ + u.id, + u.title, + u.name, + u.country + ]) + render "User $u.name inserted" + } + } + } +} + diff --git a/ratpack/src/main/groovy/com/baeldung/RatpackGroovyApp.groovy b/ratpack/src/main/groovy/com/baeldung/RatpackGroovyApp.groovy new file mode 100644 index 0000000000..95ada25e60 --- /dev/null +++ b/ratpack/src/main/groovy/com/baeldung/RatpackGroovyApp.groovy @@ -0,0 +1,12 @@ +package com.baeldung; + +public class RatpackGroovyApp { + + public static void main(String[] args) { + File file = new File("src/main/groovy/com/baeldung/Ratpack.groovy"); + def shell = new GroovyShell() + shell.evaluate(file) + } + +} + diff --git a/ratpack/src/main/groovy/com/baeldung/model/User.groovy b/ratpack/src/main/groovy/com/baeldung/model/User.groovy new file mode 100644 index 0000000000..0fe4c6c367 --- /dev/null +++ b/ratpack/src/main/groovy/com/baeldung/model/User.groovy @@ -0,0 +1,9 @@ +package com.baeldung.model + +class User { + + long id + String title + String name + String country +} diff --git a/ratpack/src/main/resources/User.sql b/ratpack/src/main/resources/User.sql new file mode 100644 index 0000000000..a3e2242283 --- /dev/null +++ b/ratpack/src/main/resources/User.sql @@ -0,0 +1,10 @@ +DROP TABLE IF EXISTS USER; +CREATE TABLE USER ( + ID BIGINT AUTO_INCREMENT PRIMARY KEY, + TITLE VARCHAR(255), + NAME VARCHAR(255), + COUNTRY VARCHAR(255) +); + +INSERT INTO USER VALUES(1,'Mr','Norman Potter', 'USA'); +INSERT INTO USER VALUES(2,'Miss','Ketty Smith', 'FRANCE'); \ No newline at end of file diff --git a/ratpack/src/test/groovy/com/baeldung/RatpackGroovySpec.groovy b/ratpack/src/test/groovy/com/baeldung/RatpackGroovySpec.groovy new file mode 100644 index 0000000000..726d703a06 --- /dev/null +++ b/ratpack/src/test/groovy/com/baeldung/RatpackGroovySpec.groovy @@ -0,0 +1,46 @@ +package com.baeldung; + +import ratpack.groovy.Groovy +import ratpack.groovy.test.GroovyRatpackMainApplicationUnderTest; +import ratpack.test.http.TestHttpClient; +import ratpack.test.ServerBackedApplicationUnderTest; +import org.junit.Test; +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 +import ratpack.test.MainClassApplicationUnderTest + +class RatpackGroovySpec { + + ServerBackedApplicationUnderTest ratpackGroovyApp = new MainClassApplicationUnderTest(RatpackGroovyApp.class) + @Delegate TestHttpClient client = TestHttpClient.testHttpClient(ratpackGroovyApp) + + @Test + void "test if app is started"() { + when: + get("") + + then: + assert response.statusCode == 200 + assert response.body.text == "Hello World from Ratpack with Groovy!!" + } + + @Test + void "test greet with name"() { + when: + get("greet/Lewis") + + then: + assert response.statusCode == 200 + assert response.body.text == "Hello Lewis!!!" + } + + @Test + void "test fetchUsers"() { + when: + get("fetchUsers") + + then: + assert response.statusCode == 200 + assert response.body.text == '[{"ID":1,"TITLE":"Mr","NAME":"Norman Potter","COUNTRY":"USA"},{"ID":2,"TITLE":"Miss","NAME":"Ketty Smith","COUNTRY":"FRANCE"}]' + } +} From 17191d02b22b8c668ee983a2c50836b7766a533c Mon Sep 17 00:00:00 2001 From: Marcos Lopez Gonzalez Date: Wed, 19 Jun 2019 13:40:25 +0200 Subject: [PATCH 26/44] BAEL-2977 - skip vs limit in streams --- .../baeldung/stream/SkipLimitComparison.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/stream/SkipLimitComparison.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/stream/SkipLimitComparison.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/stream/SkipLimitComparison.java new file mode 100644 index 0000000000..65f12ada45 --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/stream/SkipLimitComparison.java @@ -0,0 +1,46 @@ +package com.baeldung.stream; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class SkipLimitComparison { + + public static void main(String[] args) { + skipExample(); + limitExample(); + limitInfiniteStreamExample(); + getEvenNumbers(10, 10).stream() + .forEach(System.out::println); + } + + public static void skipExample() { + Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + .filter(i -> i % 2 == 0) + .skip(2) + .forEach(i -> System.out.print(i + " ")); + } + + public static void limitExample() { + Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + .filter(i -> i % 2 == 0) + .limit(2) + .forEach(i -> System.out.print(i + " ")); + } + + public static void limitInfiniteStreamExample() { + Stream.iterate(0, i -> i + 1) + .filter(i -> i % 2 == 0) + .limit(10) + .forEach(System.out::println); + } + + private static List getEvenNumbers(int offset, int limit) { + return Stream.iterate(0, i -> i + 1) + .filter(i -> i % 2 == 0) + .skip(offset) + .limit(limit) + .collect(Collectors.toList()); + } + +} From 0ef4938069fcdde02f42ae0bd95217f64d4511c3 Mon Sep 17 00:00:00 2001 From: glopez Date: Wed, 19 Jun 2019 20:15:56 -0300 Subject: [PATCH 27/44] BAEL-2804 JPA Query Parameters Usage - formatting style Fix formatting style. --- .../baeldung/jpa/queryparams/Employee.java | 105 +++++++++-------- .../queryparams/JPAQueryParamsUnitTest.java | 107 +++++++++--------- 2 files changed, 104 insertions(+), 108 deletions(-) diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/queryparams/Employee.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/queryparams/Employee.java index e8f4a10156..bf3d459530 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/queryparams/Employee.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/queryparams/Employee.java @@ -7,74 +7,73 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; - @Entity @Table(name = "employees") public class Employee { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private Long id; - - @Column(name = "employee_number", unique = true) - private String empNumber; - - @Column(name = "employee_name") - private String name; - - @Column(name = "employee_age") - private int age; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; - public Employee() { - super(); - } + @Column(name = "employee_number", unique = true) + private String empNumber; - public Employee(Long id, String empNumber) { - super(); - this.id = id; - this.empNumber = empNumber; - } + @Column(name = "employee_name") + private String name; - public Long getId() { - return id; - } + @Column(name = "employee_age") + private int age; - public void setId(Long id) { - this.id = id; - } + public Employee() { + super(); + } - public String getName() { - return name; - } + public Employee(Long id, String empNumber) { + super(); + this.id = id; + this.empNumber = empNumber; + } - public int getAge() { - return age; - } + public Long getId() { + return id; + } - public void setAge(int age) { - this.age = age; - } + public void setId(Long id) { + this.id = id; + } - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public String getEmpNumber() { - return empNumber; - } + public int getAge() { + return age; + } - public void setEmpNumber(String empNumber) { - this.empNumber = empNumber; - } + public void setAge(int age) { + this.age = age; + } - public static long getSerialversionuid() { - return serialVersionUID; - } + public void setName(String name) { + this.name = name; + } + + public String getEmpNumber() { + return empNumber; + } + + public void setEmpNumber(String empNumber) { + this.empNumber = empNumber; + } + + public static long getSerialversionuid() { + return serialVersionUID; + } } diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java index 97f82f7914..4f320935cf 100644 --- a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/queryparams/JPAQueryParamsUnitTest.java @@ -1,7 +1,6 @@ package com.baeldung.jpa.queryparams; import java.util.Arrays; -import java.util.Collections; import java.util.List; import javax.persistence.EntityManager; @@ -24,89 +23,87 @@ import org.junit.Test; */ public class JPAQueryParamsUnitTest { - private static EntityManager entityManager; - - @BeforeClass - public static void setup() { + private static EntityManager entityManager; + + @BeforeClass + public static void setup() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-h2-queryparams"); entityManager = factory.createEntityManager(); - } + } - @Test + @Test public void givenEmpNumber_whenUsingPositionalParameter_thenReturnExpectedEmployee() { - TypedQuery query = entityManager.createQuery( - "SELECT e FROM Employee e WHERE e.empNumber = ?1" , Employee.class); - String empNumber = "A123"; - Employee employee = query.setParameter(1, empNumber).getSingleResult(); + TypedQuery query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber = ?1", Employee.class); + String empNumber = "A123"; + Employee employee = query.setParameter(1, empNumber) + .getSingleResult(); Assert.assertNotNull("Employee not found", employee); } - @Test + @Test public void givenEmpNumberList_whenUsingPositionalParameter_thenReturnExpectedEmployee() { - TypedQuery query = entityManager.createQuery( - "SELECT e FROM Employee e WHERE e.empNumber IN (?1)" , Employee.class); - List empNumbers = Arrays.asList("A123", "A124"); - List employees = query.setParameter(1, empNumbers).getResultList(); + TypedQuery query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber IN (?1)", Employee.class); + List empNumbers = Arrays.asList("A123", "A124"); + List employees = query.setParameter(1, empNumbers) + .getResultList(); Assert.assertNotNull("Employees not found", employees); Assert.assertFalse("Employees not found", employees.isEmpty()); } - + @Test public void givenEmpNumber_whenUsingNamedParameter_thenReturnExpectedEmployee() { - TypedQuery query = entityManager.createQuery( - "SELECT e FROM Employee e WHERE e.empNumber = :number" , Employee.class); - String empNumber = "A123"; - Employee employee = query.setParameter("number", empNumber).getSingleResult(); - Assert.assertNotNull("Employee not found", employee); + TypedQuery query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber = :number", Employee.class); + String empNumber = "A123"; + Employee employee = query.setParameter("number", empNumber) + .getSingleResult(); + Assert.assertNotNull("Employee not found", employee); } @Test public void givenEmpNumberList_whenUsingNamedParameter_thenReturnExpectedEmployee() { - TypedQuery query = entityManager.createQuery( - "SELECT e FROM Employee e WHERE e.empNumber IN (:numbers)" , Employee.class); - List empNumbers = Arrays.asList("A123", "A124"); - List employees = query.setParameter("numbers", empNumbers).getResultList(); - Assert.assertNotNull("Employees not found", employees); - Assert.assertFalse("Employees not found", employees.isEmpty()); + TypedQuery query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber IN (:numbers)", Employee.class); + List empNumbers = Arrays.asList("A123", "A124"); + List employees = query.setParameter("numbers", empNumbers) + .getResultList(); + Assert.assertNotNull("Employees not found", employees); + Assert.assertFalse("Employees not found", employees.isEmpty()); } - + @Test public void givenEmpNameAndEmpAge_whenUsingTwoNamedParameters_thenReturnExpectedEmployees() { - TypedQuery query = entityManager.createQuery( - "SELECT e FROM Employee e WHERE e.name = :name AND e.age = :empAge" , Employee.class); - String empName = "John Doe"; - int empAge = 55; - List employees = query - .setParameter("name", empName) - .setParameter("empAge", empAge) - .getResultList(); - Assert.assertNotNull("Employees not found!", employees); - Assert.assertTrue("Employees not found!", !employees.isEmpty()); + TypedQuery query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.name = :name AND e.age = :empAge", Employee.class); + String empName = "John Doe"; + int empAge = 55; + List employees = query.setParameter("name", empName) + .setParameter("empAge", empAge) + .getResultList(); + Assert.assertNotNull("Employees not found!", employees); + Assert.assertTrue("Employees not found!", !employees.isEmpty()); } @Test public void givenEmpNumber_whenUsingCriteriaQuery_thenReturnExpectedEmployee() { - CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - CriteriaQuery cQuery = cb.createQuery(Employee.class); - Root c = cQuery.from(Employee.class); - ParameterExpression paramEmpNumber = cb.parameter(String.class); - cQuery.select(c).where(cb.equal(c.get(Employee_.empNumber), paramEmpNumber)); - - TypedQuery query = entityManager.createQuery(cQuery); - String empNumber = "A123"; - query.setParameter(paramEmpNumber, empNumber); - Employee employee = query.getSingleResult(); - Assert.assertNotNull("Employee not found!", employee); + CriteriaQuery cQuery = cb.createQuery(Employee.class); + Root c = cQuery.from(Employee.class); + ParameterExpression paramEmpNumber = cb.parameter(String.class); + cQuery.select(c) + .where(cb.equal(c.get(Employee_.empNumber), paramEmpNumber)); + + TypedQuery query = entityManager.createQuery(cQuery); + String empNumber = "A123"; + query.setParameter(paramEmpNumber, empNumber); + Employee employee = query.getSingleResult(); + Assert.assertNotNull("Employee not found!", employee); } @Test public void givenEmpNumber_whenUsingLiteral_thenReturnExpectedEmployee() { - String empNumber = "A123"; - TypedQuery query = entityManager.createQuery( - "SELECT e FROM Employee e WHERE e.empNumber = '" + empNumber + "'", Employee.class); - Employee employee = query.getSingleResult(); - Assert.assertNotNull("Employee not found!", employee); + String empNumber = "A123"; + TypedQuery query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber = '" + empNumber + "'", Employee.class); + Employee employee = query.getSingleResult(); + Assert.assertNotNull("Employee not found!", employee); } } From d0b2aa86351f7fe9ce39329a45f28aad986051b1 Mon Sep 17 00:00:00 2001 From: Erhan Karakaya Date: Thu, 20 Jun 2019 11:00:12 +0300 Subject: [PATCH 28/44] removed empty beggining lines & added override annotation --- .../baeldung/autoservice/BingTranslationServiceProvider.java | 3 +-- .../autoservice/GoogleTranslationServiceProvider.java | 3 +-- .../java/com/baeldung/autoservice/TranslationService.java | 3 +-- .../com/baeldung/autoservice/TranslationServiceUnitTest.java | 5 +---- 4 files changed, 4 insertions(+), 10 deletions(-) diff --git a/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java b/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java index 8ef4d6a45e..86d42e80fa 100644 --- a/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java +++ b/autovalue/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java @@ -6,9 +6,8 @@ import java.util.Locale; @AutoService(TranslationService.class) public class BingTranslationServiceProvider implements TranslationService { - + @Override public String translate(String message, Locale from, Locale to) { - // implementation details return message + " (translated by Bing)"; } diff --git a/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java b/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java index 3d6d1edc9f..0bf91ee5ec 100644 --- a/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java +++ b/autovalue/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java @@ -6,9 +6,8 @@ import java.util.Locale; @AutoService(TranslationService.class) public class GoogleTranslationServiceProvider implements TranslationService { - + @Override public String translate(String message, Locale from, Locale to) { - // implementation details return message + " (translated by Google)"; } diff --git a/autovalue/src/main/java/com/baeldung/autoservice/TranslationService.java b/autovalue/src/main/java/com/baeldung/autoservice/TranslationService.java index cfcff4015c..580db46cd1 100644 --- a/autovalue/src/main/java/com/baeldung/autoservice/TranslationService.java +++ b/autovalue/src/main/java/com/baeldung/autoservice/TranslationService.java @@ -3,6 +3,5 @@ package com.baeldung.autoservice; import java.util.Locale; public interface TranslationService { - String translate(String message, Locale from, Locale to); -} +} \ No newline at end of file diff --git a/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java b/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java index 2d7c8d7b6d..9e1bd6d291 100644 --- a/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java +++ b/autovalue/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java @@ -10,25 +10,22 @@ import java.util.stream.StreamSupport; import static org.junit.Assert.assertEquals; public class TranslationServiceUnitTest { - + private ServiceLoader loader; @Before public void setUp() { - loader = ServiceLoader.load(TranslationService.class); } @Test public void whenServiceLoaderLoads_thenLoadsAllProviders() { - long count = StreamSupport.stream(loader.spliterator(), false).count(); assertEquals(2, count); } @Test public void whenServiceLoaderLoadsGoogleService_thenGoogleIsLoaded() { - TranslationService googleService = StreamSupport.stream(loader.spliterator(), false) .filter(p -> p.getClass().getSimpleName().equals("GoogleTranslationServiceProvider")) .findFirst() From 5ddae76ae115a3ac74a463efb3e0164fad4109c9 Mon Sep 17 00:00:00 2001 From: Marcos Lopez Gonzalez Date: Thu, 20 Jun 2019 19:46:17 +0200 Subject: [PATCH 29/44] code moved from core-java to core-java-exceptions --- .../core-java-exceptions/pom.xml | 51 +++++++++++-------- .../baeldung/exceptions/RootCauseFinder.java | 0 .../error/ErrorGeneratorUnitTest.java | 3 +- .../exceptions/RootCauseFinderUnitTest.java | 0 4 files changed, 31 insertions(+), 23 deletions(-) rename core-java-modules/{core-java => core-java-exceptions}/src/main/java/com/baeldung/exceptions/RootCauseFinder.java (100%) rename core-java-modules/{core-java => core-java-exceptions}/src/test/java/com/baeldung/exceptions/RootCauseFinderUnitTest.java (100%) diff --git a/core-java-modules/core-java-exceptions/pom.xml b/core-java-modules/core-java-exceptions/pom.xml index 51c4e51341..37f65882c3 100644 --- a/core-java-modules/core-java-exceptions/pom.xml +++ b/core-java-modules/core-java-exceptions/pom.xml @@ -1,26 +1,35 @@ - 4.0.0 - com.baeldung.exception.numberformat - core-java-exceptions - 0.0.1-SNAPSHOT - core-java-exceptions + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung.exception.numberformat + core-java-exceptions + 0.0.1-SNAPSHOT + core-java-exceptions - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + - - - junit - junit - 4.12 - test - - + + 3.9 + + + + + junit + junit + 4.12 + test + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/exceptions/RootCauseFinder.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/RootCauseFinder.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/exceptions/RootCauseFinder.java rename to core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/RootCauseFinder.java diff --git a/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/error/ErrorGeneratorUnitTest.java b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/error/ErrorGeneratorUnitTest.java index de56fb7113..6dcd0d72e0 100644 --- a/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/error/ErrorGeneratorUnitTest.java +++ b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/error/ErrorGeneratorUnitTest.java @@ -1,7 +1,6 @@ -package com.baeldung.error; +package com.baeldung.exception.error; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; public class ErrorGeneratorUnitTest { diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/exceptions/RootCauseFinderUnitTest.java b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/RootCauseFinderUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/exceptions/RootCauseFinderUnitTest.java rename to core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/RootCauseFinderUnitTest.java From b748c86ce3d87f71e0f9e205d9d5e306c03e50b3 Mon Sep 17 00:00:00 2001 From: Laurentiu Delcea Date: Thu, 20 Jun 2019 22:53:47 +0300 Subject: [PATCH 30/44] BAEL-2982 NanoHTTPD guide (#7148) --- libraries-server/pom.xml | 14 +++++++ .../nanohttpd/ApplicationController.java | 38 +++++++++++++++++++ .../baeldung/nanohttpd/ItemGetController.java | 22 +++++++++++ .../ApplicationControllerUnitTest.java | 37 ++++++++++++++++++ .../nanohttpd/ItemGetControllerUnitTest.java | 37 ++++++++++++++++++ 5 files changed, 148 insertions(+) create mode 100644 libraries-server/src/main/java/com/baeldung/nanohttpd/ApplicationController.java create mode 100644 libraries-server/src/main/java/com/baeldung/nanohttpd/ItemGetController.java create mode 100644 libraries-server/src/test/java/com/baeldung/nanohttpd/ApplicationControllerUnitTest.java create mode 100644 libraries-server/src/test/java/com/baeldung/nanohttpd/ItemGetControllerUnitTest.java diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml index a6ead8fb31..873cca9b9b 100644 --- a/libraries-server/pom.xml +++ b/libraries-server/pom.xml @@ -96,6 +96,19 @@ smack-java7 ${smack.version} + + + + org.nanohttpd + nanohttpd + ${nanohttpd.version} + + + org.nanohttpd + nanohttpd-nanolets + ${nanohttpd.version} + + @@ -108,6 +121,7 @@ 8.5.24 4.3.1 1.2.0 + 2.3.1 \ No newline at end of file diff --git a/libraries-server/src/main/java/com/baeldung/nanohttpd/ApplicationController.java b/libraries-server/src/main/java/com/baeldung/nanohttpd/ApplicationController.java new file mode 100644 index 0000000000..2fa54c3ae2 --- /dev/null +++ b/libraries-server/src/main/java/com/baeldung/nanohttpd/ApplicationController.java @@ -0,0 +1,38 @@ +package com.baeldung.nanohttpd; + +import fi.iki.elonen.NanoHTTPD; +import fi.iki.elonen.router.RouterNanoHTTPD; + +import java.io.IOException; + +public class ApplicationController extends RouterNanoHTTPD { + + ApplicationController() throws IOException { + super(8072); + addMappings(); + start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); + } + + @Override + public void addMappings() { + addRoute("/", IndexHandler.class); + addRoute("/users", UserHandler.class); + } + + public static class UserHandler extends DefaultHandler { + @Override + public String getText() { + return "UserA, UserB, UserC"; + } + + @Override + public String getMimeType() { + return MIME_PLAINTEXT; + } + + @Override + public Response.IStatus getStatus() { + return Response.Status.OK; + } + } +} \ No newline at end of file diff --git a/libraries-server/src/main/java/com/baeldung/nanohttpd/ItemGetController.java b/libraries-server/src/main/java/com/baeldung/nanohttpd/ItemGetController.java new file mode 100644 index 0000000000..4a9c48fbfd --- /dev/null +++ b/libraries-server/src/main/java/com/baeldung/nanohttpd/ItemGetController.java @@ -0,0 +1,22 @@ +package com.baeldung.nanohttpd; + +import fi.iki.elonen.NanoHTTPD; + +import java.io.IOException; + +public class ItemGetController extends NanoHTTPD { + + ItemGetController() throws IOException { + super(8071); + start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); + } + + @Override + public Response serve(IHTTPSession session) { + if (session.getMethod() == Method.GET) { + String itemIdRequestParam = session.getParameters().get("itemId").get(0); + return newFixedLengthResponse("Requested itemId = " + itemIdRequestParam); + } + return newFixedLengthResponse(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "The requested resource does not exist"); + } +} \ No newline at end of file diff --git a/libraries-server/src/test/java/com/baeldung/nanohttpd/ApplicationControllerUnitTest.java b/libraries-server/src/test/java/com/baeldung/nanohttpd/ApplicationControllerUnitTest.java new file mode 100644 index 0000000000..003f6ee3b7 --- /dev/null +++ b/libraries-server/src/test/java/com/baeldung/nanohttpd/ApplicationControllerUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.nanohttpd; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.*; + +public class ApplicationControllerUnitTest { + + private static final String BASE_URL = "http://localhost:8072/"; + private static final HttpClient CLIENT = HttpClientBuilder.create().build(); + + @BeforeClass + public static void setUp() throws IOException { + new ApplicationController(); + } + + @Test + public void givenServer_whenRootRouteRequested_thenHelloWorldReturned() throws IOException { + HttpResponse response = CLIENT.execute(new HttpGet(BASE_URL)); + assertTrue(IOUtils.toString(response.getEntity().getContent()).contains("Hello world!")); + assertEquals(200, response.getStatusLine().getStatusCode()); + } + + @Test + public void givenServer_whenUsersRequested_thenThenAllUsersReturned() throws IOException { + HttpResponse response = CLIENT.execute(new HttpGet(BASE_URL + "users")); + assertEquals("UserA, UserB, UserC", IOUtils.toString(response.getEntity().getContent())); + } +} \ No newline at end of file diff --git a/libraries-server/src/test/java/com/baeldung/nanohttpd/ItemGetControllerUnitTest.java b/libraries-server/src/test/java/com/baeldung/nanohttpd/ItemGetControllerUnitTest.java new file mode 100644 index 0000000000..3a4f0a4d98 --- /dev/null +++ b/libraries-server/src/test/java/com/baeldung/nanohttpd/ItemGetControllerUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.nanohttpd; + +import static org.junit.Assert.*; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.HttpClientBuilder; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.IOException; + +public class ItemGetControllerUnitTest { + + private static final String URL = "http://localhost:8071"; + private static final HttpClient CLIENT = HttpClientBuilder.create().build(); + + @BeforeClass + public static void setUp() throws IOException { + new ItemGetController(); + } + + @Test + public void givenServer_whenDoingGet_thenParamIsReadCorrectly() throws IOException { + HttpResponse response = CLIENT.execute(new HttpGet(URL + "?itemId=1234")); + assertEquals("Requested itemId = 1234", IOUtils.toString(response.getEntity().getContent())); + } + + @Test + public void givenServer_whenDoingPost_then404IsReturned() throws IOException { + HttpResponse response = CLIENT.execute(new HttpPost(URL)); + assertEquals(404, response.getStatusLine().getStatusCode()); + } +} \ No newline at end of file From 01bfd6a35321caf259318b67f0916101567c5164 Mon Sep 17 00:00:00 2001 From: nikunjgandhi1987 <51273165+nikunjgandhi1987@users.noreply.github.com> Date: Thu, 20 Jun 2019 23:19:33 -0500 Subject: [PATCH 31/44] Mini article raw type in java (#7142) * Raw type example implementation --- .../com/baeldung/rawtype/RawTypeDemo.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/rawtype/RawTypeDemo.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/rawtype/RawTypeDemo.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/rawtype/RawTypeDemo.java new file mode 100644 index 0000000000..e358219d24 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/rawtype/RawTypeDemo.java @@ -0,0 +1,25 @@ +package com.baeldung.rawtype; + +import java.util.ArrayList; +import java.util.List; + +public class RawTypeDemo { + + public static void main(String[] args) { + RawTypeDemo rawTypeDemo = new RawTypeDemo(); + rawTypeDemo.methodA(); + } + + public void methodA() { + // parameterized type + List listStr = new ArrayList<>(); + listStr.add("Hello Folks!"); + methodB(listStr); + String s = listStr.get(1); // ClassCastException at run time + } + + public void methodB(List rawList) { // Inexpressive raw type + rawList.add(1); // Unsafe operation + } + +} From d2ae74a037f18eda1da06a921b6bfcd43b7658a2 Mon Sep 17 00:00:00 2001 From: Maiklins Date: Fri, 21 Jun 2019 06:59:26 +0200 Subject: [PATCH 32/44] BAEL-2933 The Difference Between Collection.stream().forEach() and Collection.forEach() (#7137) --- .../com/baeldung/forEach/ReverseList.java | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 core-java-modules/core-java-8/src/main/java/com/baeldung/forEach/ReverseList.java diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/forEach/ReverseList.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/forEach/ReverseList.java new file mode 100644 index 0000000000..b2ce77a9f6 --- /dev/null +++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/forEach/ReverseList.java @@ -0,0 +1,84 @@ +package com.baeldung.forEach; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.function.Consumer; + +class ReverseList extends ArrayList { + + List list = Arrays.asList("A", "B", "C", "D"); + + Consumer removeElement = s -> { + System.out.println(s + " " + list.size()); + if (s != null && s.equals("A")) { + list.remove("D"); + } + }; + + @Override + public Iterator iterator() { + + final int startIndex = this.size() - 1; + final List list = this; + return new Iterator() { + + int currentIndex = startIndex; + + @Override + public boolean hasNext() { + return currentIndex >= 0; + } + + @Override + public String next() { + String next = list.get(currentIndex); + currentIndex--; + return next; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + + public void forEach(Consumer action) { + for (String s : this) { + action.accept(s); + } + } + + public void iterateParallel() { + list.forEach(System.out::print); + System.out.print(" "); + list.parallelStream().forEach(System.out::print); + } + + public void iterateReverse() { + List myList = new ReverseList(); + myList.addAll(list); + myList.forEach(System.out::print); + System.out.print(" "); + myList.stream().forEach(System.out::print); + } + + public void removeInCollectionForEach() { + list.forEach(removeElement); + } + + public void removeInStreamForEach() { + list.stream().forEach(removeElement); + } + + public static void main(String[] argv) { + + ReverseList collectionForEach = new ReverseList(); + collectionForEach.iterateParallel(); + collectionForEach.iterateReverse(); + collectionForEach.removeInCollectionForEach(); + collectionForEach.removeInStreamForEach(); + } +} \ No newline at end of file From ddc85d20b9fff36a6e2b6b48325f7e896ea3b162 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sat, 8 Jun 2019 14:58:07 +0200 Subject: [PATCH 33/44] [BAEL-2996] Apache Commons Math3 example --- .../commons/math3/MatrixMultiplication.java | 6 +++ .../commons/math/RealMatrixUnitTest.java | 41 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 libraries-apache-commons/src/main/java/com/baeldung/commons/math3/MatrixMultiplication.java create mode 100644 libraries-apache-commons/src/test/java/com/baeldung/commons/math/RealMatrixUnitTest.java diff --git a/libraries-apache-commons/src/main/java/com/baeldung/commons/math3/MatrixMultiplication.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/math3/MatrixMultiplication.java new file mode 100644 index 0000000000..12252d8d14 --- /dev/null +++ b/libraries-apache-commons/src/main/java/com/baeldung/commons/math3/MatrixMultiplication.java @@ -0,0 +1,6 @@ +package com.baeldung.commons.math3; + +public class MatrixMultiplication { + + +} diff --git a/libraries-apache-commons/src/test/java/com/baeldung/commons/math/RealMatrixUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/RealMatrixUnitTest.java new file mode 100644 index 0000000000..fca2bf6dd1 --- /dev/null +++ b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/RealMatrixUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.commons.math; + +import org.apache.commons.math3.linear.Array2DRowRealMatrix; +import org.apache.commons.math3.linear.RealMatrix; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class RealMatrixUnitTest { + + @Test + void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + RealMatrix firstMatrix = new Array2DRowRealMatrix( + new double[][] { + new double[] {1d, 5d}, + new double[] {2d, 3d}, + new double[] {1d ,7d} + } + ); + + RealMatrix secondMatrix = new Array2DRowRealMatrix( + new double[][] { + new double[] {1d, 2d, 3d, 7d}, + new double[] {5d, 2d, 8d, 1d} + } + ); + + RealMatrix expected = new Array2DRowRealMatrix( + new double[][] { + new double[] {26d, 12d, 43d, 12d}, + new double[] {17d, 10d, 30d, 17d}, + new double[] {36d, 16d, 59d, 14d} + } + ); + + RealMatrix actual = firstMatrix.multiply(secondMatrix); + + assertThat(actual).isEqualTo(expected); + } + +} From 7d71c3ac94a144df6c1b14bbdf8475ba1ee33572 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sat, 8 Jun 2019 15:17:36 +0200 Subject: [PATCH 34/44] [BAEL-2996] Added ejml example --- libraries-2/pom.xml | 14 ++++-- .../baeldung/ejml/SimpleMatrixUnitTest.java | 47 +++++++++++++++++++ 2 files changed, 57 insertions(+), 4 deletions(-) create mode 100644 libraries-2/src/test/java/com/baeldung/ejml/SimpleMatrixUnitTest.java diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 32f3f23812..a734685b80 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -50,6 +50,11 @@ picocli ${picocli.version} + + org.ejml + ejml-all + ${ejml.version} + org.springframework.boot spring-boot-starter @@ -93,10 +98,10 @@ test - - edu.uci.ics - crawler4j - ${crawler4j.version} + + edu.uci.ics + crawler4j + ${crawler4j.version} @@ -109,5 +114,6 @@ 3.17.2 4.4.0 2.1.4.RELEASE + 0.37.1 diff --git a/libraries-2/src/test/java/com/baeldung/ejml/SimpleMatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/ejml/SimpleMatrixUnitTest.java new file mode 100644 index 0000000000..0f394889c0 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/ejml/SimpleMatrixUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.ejml; + +import org.ejml.simple.SimpleMatrix; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SimpleMatrixUnitTest { + + @Test + void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + SimpleMatrix firstMatrix = new SimpleMatrix( + new double[][] { + new double[] {1d, 5d}, + new double[] {2d, 3d}, + new double[] {1d ,7d} + } + ); + + SimpleMatrix secondMatrix = new SimpleMatrix( + new double[][] { + new double[] {1d, 2d, 3d, 7d}, + new double[] {5d, 2d, 8d, 1d} + } + ); + + SimpleMatrix expected = new SimpleMatrix( + new double[][] { + new double[] {26d, 12d, 43d, 12d}, + new double[] {17d, 10d, 30d, 17d}, + new double[] {36d, 16d, 59d, 14d} + } + ); + + SimpleMatrix actual = firstMatrix.mult(secondMatrix); + + assertThat(actual.numRows()).isEqualTo(expected.numRows()); + assertThat(actual.numCols()).isEqualTo(expected.numCols()); + for (int row = 0; row < actual.numRows(); row++) { + for (int col = 0; col < actual.numCols(); col++) { + assertThat(actual.get(row, col)) + .describedAs("Cells at [%d, %d] don't match", row, col) + .isEqualTo(expected.get(row, col)); + } + } + } +} From 4b14001cb3aace5c793ae1033abbc765a68710a7 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sat, 8 Jun 2019 22:03:00 +0200 Subject: [PATCH 35/44] [BAEL-2996] Added Colt library example --- libraries-2/pom.xml | 6 +++ .../baeldung/colt/DoubleMatrix2DUniTest.java | 43 +++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUniTest.java diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index a734685b80..b936465e82 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -55,6 +55,11 @@ ejml-all ${ejml.version} + + colt + colt + ${colt.version} + org.springframework.boot spring-boot-starter @@ -115,5 +120,6 @@ 4.4.0 2.1.4.RELEASE 0.37.1 + 1.2.0 diff --git a/libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUniTest.java b/libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUniTest.java new file mode 100644 index 0000000000..54d10e8cef --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUniTest.java @@ -0,0 +1,43 @@ +package com.baeldung.colt; + +import cern.colt.matrix.DoubleFactory2D; +import cern.colt.matrix.DoubleMatrix2D; +import cern.colt.matrix.linalg.Algebra; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class DoubleMatrix2DUniTest { + + @Test + void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + DoubleFactory2D doubleFactory2D = DoubleFactory2D.dense; + + DoubleMatrix2D firstMatrix = doubleFactory2D.make( + new double[][] { + new double[] {1d, 5d}, + new double[] {2d, 3d}, + new double[] {1d ,7d} + }); + + DoubleMatrix2D secondMatrix = doubleFactory2D.make( + new double[][] { + new double[] {1d, 2d, 3d, 7d}, + new double[] {5d, 2d, 8d, 1d} + } + ); + + DoubleMatrix2D expected = doubleFactory2D.make( + new double[][] { + new double[] {26d, 12d, 43d, 12d}, + new double[] {17d, 10d, 30d, 17d}, + new double[] {36d, 16d, 59d, 14d} + } + ); + + Algebra algebra = new Algebra(); + DoubleMatrix2D actual = algebra.mult(firstMatrix, secondMatrix); + + assertThat(actual).isEqualTo(expected); + } +} From 082aa7d0a6a369407a589499b57b06f0f4516fc8 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sat, 8 Jun 2019 22:19:02 +0200 Subject: [PATCH 36/44] [BAEL-2996] Added la4j library example --- libraries-2/pom.xml | 6 +++ ...iTest.java => DoubleMatrix2DUnitTest.java} | 2 +- .../baeldung/la4j/Basic2DMatrixUnitTest.java | 39 +++++++++++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) rename libraries-2/src/test/java/com/baeldung/colt/{DoubleMatrix2DUniTest.java => DoubleMatrix2DUnitTest.java} (97%) create mode 100644 libraries-2/src/test/java/com/baeldung/la4j/Basic2DMatrixUnitTest.java diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index b936465e82..aca47f957d 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -60,6 +60,11 @@ colt ${colt.version} + + org.la4j + la4j + ${la4j.version} + org.springframework.boot spring-boot-starter @@ -121,5 +126,6 @@ 2.1.4.RELEASE 0.37.1 1.2.0 + 0.6.0 diff --git a/libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUniTest.java b/libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUnitTest.java similarity index 97% rename from libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUniTest.java rename to libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUnitTest.java index 54d10e8cef..d88d1a150a 100644 --- a/libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUniTest.java +++ b/libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUnitTest.java @@ -7,7 +7,7 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -class DoubleMatrix2DUniTest { +class DoubleMatrix2DUnitTest { @Test void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { diff --git a/libraries-2/src/test/java/com/baeldung/la4j/Basic2DMatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/la4j/Basic2DMatrixUnitTest.java new file mode 100644 index 0000000000..cf0f132cae --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/la4j/Basic2DMatrixUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.la4j; + +import org.junit.jupiter.api.Test; +import org.la4j.Matrix; +import org.la4j.matrix.dense.Basic2DMatrix; + +import static org.assertj.core.api.Assertions.assertThat; + +class Basic2DMatrixUnitTest { + + @Test + void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + Matrix firstMatrix = new Basic2DMatrix( + new double[][]{ + new double[]{1d, 5d}, + new double[]{2d, 3d}, + new double[]{1d, 7d} + }); + + Matrix secondMatrix = new Basic2DMatrix( + new double[][]{ + new double[]{1d, 2d, 3d, 7d}, + new double[]{5d, 2d, 8d, 1d} + } + ); + + Matrix expected = new Basic2DMatrix( + new double[][]{ + new double[]{26d, 12d, 43d, 12d}, + new double[]{17d, 10d, 30d, 17d}, + new double[]{36d, 16d, 59d, 14d} + } + ); + + Matrix actual = firstMatrix.multiply(secondMatrix); + + assertThat(actual).isEqualTo(expected); + } +} From 8a8f880d336c2564fe015ea48877ba26de78a35a Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sun, 16 Jun 2019 14:40:02 +0200 Subject: [PATCH 37/44] [BAEL-2996] Improved test with simpler matrix validation --- .../java/com/baeldung/ejml/SimpleMatrixUnitTest.java | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/libraries-2/src/test/java/com/baeldung/ejml/SimpleMatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/ejml/SimpleMatrixUnitTest.java index 0f394889c0..7fba7e00a2 100644 --- a/libraries-2/src/test/java/com/baeldung/ejml/SimpleMatrixUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/ejml/SimpleMatrixUnitTest.java @@ -34,14 +34,6 @@ class SimpleMatrixUnitTest { SimpleMatrix actual = firstMatrix.mult(secondMatrix); - assertThat(actual.numRows()).isEqualTo(expected.numRows()); - assertThat(actual.numCols()).isEqualTo(expected.numCols()); - for (int row = 0; row < actual.numRows(); row++) { - for (int col = 0; col < actual.numCols(); col++) { - assertThat(actual.get(row, col)) - .describedAs("Cells at [%d, %d] don't match", row, col) - .isEqualTo(expected.get(row, col)); - } - } + assertThat(actual).matches(m -> m.isIdentical(expected, 0d)); } } From e885264b5f2a29cb153b2d58b8acd301f69f2754 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sun, 16 Jun 2019 15:58:30 +0200 Subject: [PATCH 38/44] [BAEL-2996] Added ND4J dependency and matrices multiplication test --- libraries-2/pom.xml | 8 +++- .../com/baeldung/nd4j/INDArrayUnitTest.java | 40 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 libraries-2/src/test/java/com/baeldung/nd4j/INDArrayUnitTest.java diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index aca47f957d..bcb4f51bc2 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -55,6 +55,11 @@ ejml-all ${ejml.version} + + org.nd4j + nd4j-native + ${nd4j.version} + colt colt @@ -124,7 +129,8 @@ 3.17.2 4.4.0 2.1.4.RELEASE - 0.37.1 + 0.38 + 1.0.0-beta4 1.2.0 0.6.0 diff --git a/libraries-2/src/test/java/com/baeldung/nd4j/INDArrayUnitTest.java b/libraries-2/src/test/java/com/baeldung/nd4j/INDArrayUnitTest.java new file mode 100644 index 0000000000..a09eef9a57 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/nd4j/INDArrayUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.nd4j; + +import org.junit.jupiter.api.Test; +import org.nd4j.linalg.api.ndarray.INDArray; +import org.nd4j.linalg.factory.Nd4j; + +import static org.assertj.core.api.Assertions.assertThat; + +class INDArrayUnitTest { + + @Test + void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + INDArray firstMatrix = Nd4j.create( + new double[][]{ + new double[]{1d, 5d}, + new double[]{2d, 3d}, + new double[]{1d, 7d} + } + ); + + INDArray secondMatrix = Nd4j.create( + new double[][] { + new double[] {1d, 2d, 3d, 7d}, + new double[] {5d, 2d, 8d, 1d} + } + ); + + INDArray expected = Nd4j.create( + new double[][] { + new double[] {26d, 12d, 43d, 12d}, + new double[] {17d, 10d, 30d, 17d}, + new double[] {36d, 16d, 59d, 14d} + } + ); + + INDArray actual = firstMatrix.mmul(secondMatrix); + + assertThat(actual).isEqualTo(expected); + } +} From 874f8d07c87325ddf729a500b468ea61dd6645e2 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sun, 16 Jun 2019 15:58:56 +0200 Subject: [PATCH 39/44] [BAEL-2996] Fixed formatting --- .../src/test/java/com/baeldung/la4j/Basic2DMatrixUnitTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries-2/src/test/java/com/baeldung/la4j/Basic2DMatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/la4j/Basic2DMatrixUnitTest.java index cf0f132cae..af6274998e 100644 --- a/libraries-2/src/test/java/com/baeldung/la4j/Basic2DMatrixUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/la4j/Basic2DMatrixUnitTest.java @@ -15,7 +15,8 @@ class Basic2DMatrixUnitTest { new double[]{1d, 5d}, new double[]{2d, 3d}, new double[]{1d, 7d} - }); + } + ); Matrix secondMatrix = new Basic2DMatrix( new double[][]{ From 5296f37727eff8c634f940666513516cad59bc54 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Fri, 21 Jun 2019 06:03:09 +0200 Subject: [PATCH 40/44] [BAEL-2996] Small fixes --- libraries-2/pom.xml | 20 +++++++++---------- .../baeldung/colt/DoubleMatrix2DUnitTest.java | 3 ++- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index bcb4f51bc2..8f223e7ea0 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -60,16 +60,16 @@ nd4j-native ${nd4j.version} - - colt - colt - ${colt.version} - - - org.la4j - la4j - ${la4j.version} - + + org.la4j + la4j + ${la4j.version} + + + colt + colt + ${colt.version} + org.springframework.boot spring-boot-starter diff --git a/libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUnitTest.java b/libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUnitTest.java index d88d1a150a..8b541f3974 100644 --- a/libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUnitTest.java @@ -18,7 +18,8 @@ class DoubleMatrix2DUnitTest { new double[] {1d, 5d}, new double[] {2d, 3d}, new double[] {1d ,7d} - }); + } + ); DoubleMatrix2D secondMatrix = doubleFactory2D.make( new double[][] { From bc498d61b3659364c61869f374f7c40b93773245 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Fri, 21 Jun 2019 06:40:30 +0200 Subject: [PATCH 41/44] [BAEL-2996] Moved previous tests and added own implementation --- .../colt/DoubleMatrix2DUnitTest.java | 2 +- .../ejml/SimpleMatrixUnitTest.java | 2 +- .../matrices/homemade/MatrixUnitTest.java | 52 +++++++++++++++++++ .../la4j/Basic2DMatrixUnitTest.java | 2 +- .../{ => matrices}/nd4j/INDArrayUnitTest.java | 2 +- 5 files changed, 56 insertions(+), 4 deletions(-) rename libraries-2/src/test/java/com/baeldung/{ => matrices}/colt/DoubleMatrix2DUnitTest.java (97%) rename libraries-2/src/test/java/com/baeldung/{ => matrices}/ejml/SimpleMatrixUnitTest.java (96%) create mode 100644 libraries-2/src/test/java/com/baeldung/matrices/homemade/MatrixUnitTest.java rename libraries-2/src/test/java/com/baeldung/{ => matrices}/la4j/Basic2DMatrixUnitTest.java (96%) rename libraries-2/src/test/java/com/baeldung/{ => matrices}/nd4j/INDArrayUnitTest.java (96%) diff --git a/libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java similarity index 97% rename from libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUnitTest.java rename to libraries-2/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java index 8b541f3974..f21d6ab12c 100644 --- a/libraries-2/src/test/java/com/baeldung/colt/DoubleMatrix2DUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.colt; +package com.baeldung.matrices.colt; import cern.colt.matrix.DoubleFactory2D; import cern.colt.matrix.DoubleMatrix2D; diff --git a/libraries-2/src/test/java/com/baeldung/ejml/SimpleMatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java similarity index 96% rename from libraries-2/src/test/java/com/baeldung/ejml/SimpleMatrixUnitTest.java rename to libraries-2/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java index 7fba7e00a2..eb022d752f 100644 --- a/libraries-2/src/test/java/com/baeldung/ejml/SimpleMatrixUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.ejml; +package com.baeldung.matrices.ejml; import org.ejml.simple.SimpleMatrix; import org.junit.jupiter.api.Test; diff --git a/libraries-2/src/test/java/com/baeldung/matrices/homemade/MatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/homemade/MatrixUnitTest.java new file mode 100644 index 0000000000..b118e5503d --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/matrices/homemade/MatrixUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.matrices.homemade; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class MatrixUnitTest { + + @Test + void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + double[][] firstMatrix = { + new double[]{1d, 5d}, + new double[]{2d, 3d}, + new double[]{1d, 7d} + }; + + double[][] secondMatrix = { + new double[]{1d, 2d, 3d, 7d}, + new double[]{5d, 2d, 8d, 1d} + }; + + double[][] expected = { + new double[]{26d, 12d, 43d, 12d}, + new double[]{17d, 10d, 30d, 17d}, + new double[]{36d, 16d, 59d, 14d} + }; + + double[][] actual = multiplyMatrices(firstMatrix, secondMatrix); + + assertThat(actual).isEqualTo(expected); + } + + private double[][] multiplyMatrices(double[][] firstMatrix, double[][] secondMatrix) { + double[][] result = new double[firstMatrix.length][secondMatrix[0].length]; + + for (int row = 0; row < result.length; row++) { + for (int col = 0; col < result[row].length; col++) { + result[row][col] = multiplyMatricesCell(firstMatrix, secondMatrix, row, col); + } + } + + return result; + } + + private double multiplyMatricesCell(double[][] firstMatrix, double[][] secondMatrix, int row, int col) { + double cell = 0; + for (int i = 0; i < secondMatrix.length; i++) { + cell += firstMatrix[row][i] * secondMatrix[i][col]; + } + return cell; + } +} diff --git a/libraries-2/src/test/java/com/baeldung/la4j/Basic2DMatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java similarity index 96% rename from libraries-2/src/test/java/com/baeldung/la4j/Basic2DMatrixUnitTest.java rename to libraries-2/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java index af6274998e..ef2d50aa08 100644 --- a/libraries-2/src/test/java/com/baeldung/la4j/Basic2DMatrixUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.la4j; +package com.baeldung.matrices.la4j; import org.junit.jupiter.api.Test; import org.la4j.Matrix; diff --git a/libraries-2/src/test/java/com/baeldung/nd4j/INDArrayUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java similarity index 96% rename from libraries-2/src/test/java/com/baeldung/nd4j/INDArrayUnitTest.java rename to libraries-2/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java index a09eef9a57..6f3502726c 100644 --- a/libraries-2/src/test/java/com/baeldung/nd4j/INDArrayUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.nd4j; +package com.baeldung.matrices.nd4j; import org.junit.jupiter.api.Test; import org.nd4j.linalg.api.ndarray.INDArray; From 327fc24a4b8ee533951959255e3a266d970ead12 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Fri, 21 Jun 2019 07:42:20 +0200 Subject: [PATCH 42/44] [BAEL-2996] Moving all test under this module and adding benchmarking --- libraries-2/pom.xml | 13 +++++++++++++ .../matrices/MatrixMultiplicationBenchmarking.java | 11 +++++++++++ .../matrices/apache}/RealMatrixUnitTest.java | 12 +++++++++--- .../matrices/colt/DoubleMatrix2DUnitTest.java | 11 +++++++++-- .../matrices/ejml/SimpleMatrixUnitTest.java | 11 +++++++++-- ...rixUnitTest.java => HomemadeMatrixUnitTest.java} | 10 ++++++++-- .../matrices/la4j/Basic2DMatrixUnitTest.java | 11 +++++++++-- .../baeldung/matrices/nd4j/INDArrayUnitTest.java | 10 ++++++++-- 8 files changed, 76 insertions(+), 13 deletions(-) create mode 100644 libraries-2/src/test/java/com/baeldung/matrices/MatrixMultiplicationBenchmarking.java rename {libraries-apache-commons/src/test/java/com/baeldung/commons/math => libraries-2/src/test/java/com/baeldung/matrices/apache}/RealMatrixUnitTest.java (76%) rename libraries-2/src/test/java/com/baeldung/matrices/homemade/{MatrixUnitTest.java => HomemadeMatrixUnitTest.java} (84%) diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 8f223e7ea0..c18b4aae64 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -118,6 +118,18 @@ crawler4j ${crawler4j.version} + + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + @@ -133,5 +145,6 @@ 1.0.0-beta4 1.2.0 0.6.0 + 1.19 diff --git a/libraries-2/src/test/java/com/baeldung/matrices/MatrixMultiplicationBenchmarking.java b/libraries-2/src/test/java/com/baeldung/matrices/MatrixMultiplicationBenchmarking.java new file mode 100644 index 0000000000..fff6805a89 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/matrices/MatrixMultiplicationBenchmarking.java @@ -0,0 +1,11 @@ +package com.baeldung.matrices; + +import org.openjdk.jmh.Main; + +public class MatrixMultiplicationBenchmarking { + + public static void main(String[] args) throws Exception { + Main.main(args); + } + +} diff --git a/libraries-apache-commons/src/test/java/com/baeldung/commons/math/RealMatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/apache/RealMatrixUnitTest.java similarity index 76% rename from libraries-apache-commons/src/test/java/com/baeldung/commons/math/RealMatrixUnitTest.java rename to libraries-2/src/test/java/com/baeldung/matrices/apache/RealMatrixUnitTest.java index fca2bf6dd1..05944e7b3a 100644 --- a/libraries-apache-commons/src/test/java/com/baeldung/commons/math/RealMatrixUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/matrices/apache/RealMatrixUnitTest.java @@ -1,15 +1,21 @@ -package com.baeldung.commons.math; +package com.baeldung.matrices.apache; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.RealMatrix; import org.junit.jupiter.api.Test; +import org.openjdk.jmh.annotations.*; import static org.assertj.core.api.Assertions.assertThat; -class RealMatrixUnitTest { +@BenchmarkMode(Mode.AverageTime) +@Fork(value = 2) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +public class RealMatrixUnitTest { @Test - void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + @Benchmark + public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { RealMatrix firstMatrix = new Array2DRowRealMatrix( new double[][] { new double[] {1d, 5d}, diff --git a/libraries-2/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java index f21d6ab12c..fb4a419eb0 100644 --- a/libraries-2/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/matrices/colt/DoubleMatrix2DUnitTest.java @@ -4,13 +4,19 @@ import cern.colt.matrix.DoubleFactory2D; import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.linalg.Algebra; import org.junit.jupiter.api.Test; +import org.openjdk.jmh.annotations.*; import static org.assertj.core.api.Assertions.assertThat; -class DoubleMatrix2DUnitTest { +@BenchmarkMode(Mode.AverageTime) +@Fork(value = 2) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +public class DoubleMatrix2DUnitTest { @Test - void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + @Benchmark + public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { DoubleFactory2D doubleFactory2D = DoubleFactory2D.dense; DoubleMatrix2D firstMatrix = doubleFactory2D.make( @@ -41,4 +47,5 @@ class DoubleMatrix2DUnitTest { assertThat(actual).isEqualTo(expected); } + } diff --git a/libraries-2/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java index eb022d752f..b025266a1d 100644 --- a/libraries-2/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/matrices/ejml/SimpleMatrixUnitTest.java @@ -2,13 +2,19 @@ package com.baeldung.matrices.ejml; import org.ejml.simple.SimpleMatrix; import org.junit.jupiter.api.Test; +import org.openjdk.jmh.annotations.*; import static org.assertj.core.api.Assertions.assertThat; -class SimpleMatrixUnitTest { +@BenchmarkMode(Mode.AverageTime) +@Fork(value = 2) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +public class SimpleMatrixUnitTest { @Test - void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + @Benchmark + public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { SimpleMatrix firstMatrix = new SimpleMatrix( new double[][] { new double[] {1d, 5d}, @@ -36,4 +42,5 @@ class SimpleMatrixUnitTest { assertThat(actual).matches(m -> m.isIdentical(expected, 0d)); } + } diff --git a/libraries-2/src/test/java/com/baeldung/matrices/homemade/MatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/homemade/HomemadeMatrixUnitTest.java similarity index 84% rename from libraries-2/src/test/java/com/baeldung/matrices/homemade/MatrixUnitTest.java rename to libraries-2/src/test/java/com/baeldung/matrices/homemade/HomemadeMatrixUnitTest.java index b118e5503d..be9e483d5b 100644 --- a/libraries-2/src/test/java/com/baeldung/matrices/homemade/MatrixUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/matrices/homemade/HomemadeMatrixUnitTest.java @@ -1,13 +1,19 @@ package com.baeldung.matrices.homemade; import org.junit.jupiter.api.Test; +import org.openjdk.jmh.annotations.*; import static org.assertj.core.api.Assertions.assertThat; -class MatrixUnitTest { +@BenchmarkMode(Mode.AverageTime) +@Fork(value = 2) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +public class HomemadeMatrixUnitTest { @Test - void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + @Benchmark + public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { double[][] firstMatrix = { new double[]{1d, 5d}, new double[]{2d, 3d}, diff --git a/libraries-2/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java index ef2d50aa08..afb84ff3db 100644 --- a/libraries-2/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/matrices/la4j/Basic2DMatrixUnitTest.java @@ -3,13 +3,19 @@ package com.baeldung.matrices.la4j; import org.junit.jupiter.api.Test; import org.la4j.Matrix; import org.la4j.matrix.dense.Basic2DMatrix; +import org.openjdk.jmh.annotations.*; import static org.assertj.core.api.Assertions.assertThat; -class Basic2DMatrixUnitTest { +@BenchmarkMode(Mode.AverageTime) +@Fork(value = 2) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +public class Basic2DMatrixUnitTest { @Test - void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + @Benchmark + public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { Matrix firstMatrix = new Basic2DMatrix( new double[][]{ new double[]{1d, 5d}, @@ -37,4 +43,5 @@ class Basic2DMatrixUnitTest { assertThat(actual).isEqualTo(expected); } + } diff --git a/libraries-2/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java b/libraries-2/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java index 6f3502726c..fb3030bccf 100644 --- a/libraries-2/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/matrices/nd4j/INDArrayUnitTest.java @@ -3,13 +3,18 @@ package com.baeldung.matrices.nd4j; import org.junit.jupiter.api.Test; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; +import org.openjdk.jmh.annotations.*; import static org.assertj.core.api.Assertions.assertThat; -class INDArrayUnitTest { +@BenchmarkMode(Mode.AverageTime) +@Fork(value = 2) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +public class INDArrayUnitTest { @Test - void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { + public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() { INDArray firstMatrix = Nd4j.create( new double[][]{ new double[]{1d, 5d}, @@ -37,4 +42,5 @@ class INDArrayUnitTest { assertThat(actual).isEqualTo(expected); } + } From bc8fbaf579054b968b9708bf8fa44b9e65c32cff Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sat, 22 Jun 2019 11:40:10 +0200 Subject: [PATCH 43/44] =?UTF-8?q?=C3=83[BAEL-2996]=20Used=20qualified=20cl?= =?UTF-8?q?ass=20for=20benchmarking?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../baeldung/matrices/MatrixMultiplicationBenchmarking.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/libraries-2/src/test/java/com/baeldung/matrices/MatrixMultiplicationBenchmarking.java b/libraries-2/src/test/java/com/baeldung/matrices/MatrixMultiplicationBenchmarking.java index fff6805a89..1e3b183aa7 100644 --- a/libraries-2/src/test/java/com/baeldung/matrices/MatrixMultiplicationBenchmarking.java +++ b/libraries-2/src/test/java/com/baeldung/matrices/MatrixMultiplicationBenchmarking.java @@ -1,11 +1,9 @@ package com.baeldung.matrices; -import org.openjdk.jmh.Main; - public class MatrixMultiplicationBenchmarking { public static void main(String[] args) throws Exception { - Main.main(args); + org.openjdk.jmh.Main.main(args); } } From 9ec362f520b10f01ae749a793e6181e034de19fe Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sat, 22 Jun 2019 11:43:33 +0200 Subject: [PATCH 44/44] =?UTF-8?q?[BAEL-2996]=20Removed=20useless=20class?= =?UTF-8?q?=C3=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/baeldung/commons/math3/MatrixMultiplication.java | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 libraries-apache-commons/src/main/java/com/baeldung/commons/math3/MatrixMultiplication.java diff --git a/libraries-apache-commons/src/main/java/com/baeldung/commons/math3/MatrixMultiplication.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/math3/MatrixMultiplication.java deleted file mode 100644 index 12252d8d14..0000000000 --- a/libraries-apache-commons/src/main/java/com/baeldung/commons/math3/MatrixMultiplication.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.commons.math3; - -public class MatrixMultiplication { - - -}